WxUtils.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /** @format */
  2. import {Log} from './LogUtils'
  3. import {ConstValue} from '../data/ConstValue'
  4. class wxUtils {
  5. public wxSystemInfo: wx.systemInfo = null
  6. public wxLaunchOptions: any = null
  7. public wxIsAuthor: boolean = false
  8. public wxMenuButtonPos = null
  9. public hideCB: any = null
  10. public showCB: any = null
  11. public wxOnHide: boolean = false
  12. public bannerAd: wx.BannerAd[] = []
  13. public wxGameClubBtn: any = null
  14. public scene: string | number = ''
  15. public canvas: wx.Canvas = null
  16. public isWeChat(): boolean {
  17. // @ts-ignore
  18. let _global = typeof window === 'undefined' ? global : window
  19. // @ts-ignore
  20. return cc.sys.platform == cc.sys.WECHAT_GAME && !cc.sys.isBrowser && typeof _global.qq === 'undefined'
  21. }
  22. public init() {
  23. if (!this.isWeChat()) {
  24. return
  25. }
  26. this.wxSystemInfo = wx.getSystemInfoSync()
  27. if (!this.canvas) this.canvas = wx.createCanvas()
  28. Log.info('getSystemInfo', this.wxSystemInfo)
  29. }
  30. public getNodeCanvasSize(node: cc.Node) {
  31. let frameSize = cc.view.getFrameSize()
  32. let winSize = cc.winSize
  33. let left = ((winSize.width * 0.5 + node.x - node.width * 0.5) / winSize.width) * frameSize.width
  34. let top = ((winSize.height * 0.5 - node.y - node.height * 0.5) / winSize.height) * frameSize.height
  35. let width = (node.width / winSize.width) * frameSize.width
  36. let height = (node.height / winSize.height) * frameSize.height
  37. return {left, top, width, height}
  38. }
  39. public login(hostUrl, successCB, failCB) {
  40. wx.login({
  41. success: res => {
  42. successCB && successCB(res)
  43. },
  44. fail: failCB,
  45. })
  46. }
  47. public request(reqUrl, reqMethod, successCB, failCB, type) {
  48. wx.request({
  49. url: reqUrl,
  50. method: reqMethod,
  51. success: res => {
  52. successCB && successCB(res.data)
  53. },
  54. fail: () => {
  55. failCB && failCB()
  56. },
  57. responseType: type,
  58. })
  59. }
  60. public reset(width, height) {
  61. if (!this.isWeChat()) {
  62. return
  63. }
  64. }
  65. public startShare(shareQuery: string = '', title?: string, imageUrl?: string) {
  66. // if (!this.isWeChat() || !ConstData.config.shareArr) {
  67. // return
  68. // }
  69. // if (!title) {
  70. // const shareObj = ConstData.config.shareArr[Math.floor(Math.random() * ConstData.config.shareArr.length)]
  71. // title = shareObj.shareWord
  72. // imageUrl = shareObj.url
  73. // shareQuery += `&imageChannel=${shareObj.imageChannel}`
  74. // }
  75. // wx.onShareAppMessage(() => ({
  76. // title: title,
  77. // imageUrl: imageUrl,
  78. // query: shareQuery,
  79. // }))
  80. // wx.showShareMenu({withShareTicket: true})
  81. }
  82. public share(shareQuery, title?: string, imageUrl?: string) {
  83. // if (!this.isWeChat() || !ConstData.config.shareArr) {
  84. // return
  85. // }
  86. // const shareObj = ConstData.config.shareArr[Math.floor(Math.random() * ConstData.config.shareArr.length)]
  87. // if (!title) {
  88. // title = shareObj.shareWord
  89. // }
  90. // if (!imageUrl) {
  91. // imageUrl = shareObj.url
  92. // shareQuery += `&imageChannel=${shareObj.imageChannel}`
  93. // }
  94. // wx.shareAppMessage({
  95. // title: title,
  96. // imageUrl: imageUrl,
  97. // query: shareQuery,
  98. // })
  99. }
  100. public getShareInfo(shareTicket, successCB, failCB) {
  101. if (!this.isWeChat()) {
  102. return
  103. }
  104. // @ts-ignore
  105. wx.getShareInfo({
  106. shareTicket,
  107. success: res => {
  108. successCB(res)
  109. },
  110. fail: failCB,
  111. })
  112. }
  113. public setData(k, v) {
  114. if (!this.isWeChat()) {
  115. return
  116. }
  117. if (!this.isHigherSDKVersion('1.9.92')) {
  118. return
  119. }
  120. wx.setUserCloudStorage({
  121. KVDataList: [{key: k, value: v}],
  122. success: e => {},
  123. fail: e => {},
  124. })
  125. }
  126. public deleteData(key) {
  127. if (!this.isWeChat()) {
  128. return
  129. }
  130. wx.removeUserCloudStorage({
  131. keyList: [key],
  132. success: e => {},
  133. fail: e => {},
  134. })
  135. }
  136. public postMessage(_cmd, _data) {
  137. if (!this.isWeChat()) {
  138. return
  139. }
  140. const openDataContext = wx.getOpenDataContext()
  141. openDataContext.postMessage({
  142. cmd: _cmd,
  143. data: _data,
  144. })
  145. }
  146. public showWebImage(url) {
  147. if (!this.isWeChat()) {
  148. return
  149. }
  150. wx.previewImage({
  151. current: url,
  152. urls: [url],
  153. success: () => {},
  154. fail: () => {},
  155. complete: () => {},
  156. })
  157. }
  158. public downloadFile(_urls, successFunc, failFunc, completeFunc) {
  159. if (!wx.downloadFile) {
  160. return
  161. }
  162. wx.downloadFile({
  163. url: _urls,
  164. success: successFunc,
  165. fail: failFunc,
  166. complete: completeFunc,
  167. })
  168. }
  169. public shock() {
  170. if (!this.isWeChat()) {
  171. return
  172. }
  173. wx.vibrateLong({
  174. success: () => {},
  175. fail: () => {},
  176. })
  177. }
  178. public createFeedbackButton(node: cc.Node) {
  179. if (!this.isWeChat()) {
  180. return
  181. }
  182. let canvasSize = this.getNodeCanvasSize(node)
  183. let style: WechatMinigame.OptionStyle = {
  184. backgroundColor: '',
  185. borderColor: '',
  186. borderRadius: 0,
  187. borderWidth: 0,
  188. color: '',
  189. fontSize: 0,
  190. height: canvasSize.height,
  191. left: canvasSize.left,
  192. lineHeight: 0,
  193. textAlign: 'center',
  194. top: canvasSize.top,
  195. width: canvasSize.width,
  196. }
  197. let button = wx.createFeedbackButton({
  198. type: 'image',
  199. image: '',
  200. style,
  201. })
  202. return button
  203. }
  204. public openConversation(sucFunc, failFunc) {
  205. if (!this.isHigherSDKVersion('2.0.3')) {
  206. return
  207. }
  208. wx.openCustomerServiceConversation({
  209. success: sucFunc,
  210. fail: failFunc,
  211. })
  212. }
  213. public saveIMGForShare(sucFunc, failFunc, node: cc.Node) {
  214. if (!this.isWeChat()) {
  215. return
  216. }
  217. let canvasData = this.getNodeCanvasSize(node)
  218. this.canvas.toTempFilePath({
  219. x: canvasData.left,
  220. y: canvasData.top,
  221. width: canvasData.width,
  222. height: canvasData.height,
  223. success(res) {
  224. // .可以保存该截屏图片
  225. wx.saveImageToPhotosAlbum({
  226. filePath: res.tempFilePath,
  227. success: sucFunc,
  228. fail: failFunc,
  229. })
  230. },
  231. })
  232. }
  233. public loadUserInfo(succ, fail) {
  234. // 读取玩家微信数据
  235. wx.getUserInfo({
  236. success: res => {
  237. if (succ) {
  238. succ(res.userInfo)
  239. }
  240. },
  241. fail: () => {
  242. if (fail) {
  243. fail()
  244. }
  245. },
  246. })
  247. }
  248. public navigateToMiniProgram(appid, apppath) {
  249. if (!this.isWeChat()) {
  250. return
  251. }
  252. if (this.isHigherSDKVersion('2.2.0')) {
  253. wx.navigateToMiniProgram({
  254. appId: appid,
  255. path: apppath,
  256. envVersion: 'release',
  257. extraData: null,
  258. fail: res => {
  259. this.showToast('跳转失败,请重试')
  260. },
  261. success: () => {},
  262. })
  263. } else {
  264. this.showToast('当前微信版本过低,请升级到最新版本')
  265. }
  266. }
  267. public showToast(title, icon: any = 'none', duration = 2000) {
  268. wx.showToast({
  269. title,
  270. icon,
  271. duration,
  272. } as any)
  273. }
  274. public showModal(title, content, cancelText, confirmText, success, fail) {
  275. if (!this.isWeChat()) {
  276. return
  277. }
  278. wx.showModal({
  279. cancelText,
  280. confirmText,
  281. title,
  282. content,
  283. success(res) {
  284. if (res.confirm) {
  285. success()
  286. }
  287. },
  288. fail,
  289. showCancel: true,
  290. })
  291. }
  292. public groupShare(title, url, rQuery) {
  293. if (!this.isWeChat()) {
  294. return
  295. }
  296. wx.shareAppMessage({
  297. title,
  298. imageUrl: url,
  299. query: rQuery,
  300. })
  301. }
  302. public onHide(callback) {
  303. if (this.isWeChat()) {
  304. if (this.hideCB) {
  305. wx.offHide(this.hideCB)
  306. }
  307. this.hideCB = res => {
  308. if (callback) {
  309. callback()
  310. }
  311. this.wxOnHide = true
  312. }
  313. wx.onHide(this.hideCB)
  314. }
  315. }
  316. public onShow(callback) {
  317. if (this.isWeChat()) {
  318. if (this.showCB) {
  319. wx.offShow(this.showCB)
  320. }
  321. this.showCB = res => {
  322. Log.info('show back: ', res)
  323. this.scene = res && res.scene ? res.scene : this.scene
  324. if (callback) {
  325. callback(res)
  326. }
  327. this.wxOnHide = false
  328. }
  329. wx.onShow(this.showCB)
  330. }
  331. }
  332. public launchBack() {
  333. if (this.isWeChat()) {
  334. this.wxLaunchOptions = wx.getLaunchOptionsSync()
  335. this.scene = this.wxLaunchOptions && this.wxLaunchOptions.scene ? this.wxLaunchOptions.scene : this.scene
  336. Log.info('launchBack:wxLaunchOptions=>', this.wxLaunchOptions)
  337. }
  338. }
  339. public checkUpdate() {
  340. if (this.isWeChat() && this.isHigherSDKVersion('1.9.90') && typeof wx.getUpdateManager === 'function') {
  341. Log.info('检查更新')
  342. const updateManager = wx.getUpdateManager()
  343. if (this.isHigherWXVersion('6.6.7') || cc.sys.os === cc.sys.OS_IOS) {
  344. updateManager.onCheckForUpdate(res => {
  345. Log.info('res.hasUpdate', res.hasUpdate)
  346. if (res.hasUpdate) {
  347. Log.info('需要更新')
  348. } else {
  349. Log.info('无更新')
  350. }
  351. })
  352. updateManager.onUpdateReady(() => {
  353. wx.showModal({
  354. title: '提示',
  355. content: '新版本下载完成,是否立即重启',
  356. success(res) {
  357. if (res.confirm) {
  358. updateManager.applyUpdate()
  359. }
  360. },
  361. })
  362. })
  363. updateManager.onUpdateFailed(() => {
  364. wx.showModal({
  365. title: '提示',
  366. content: '更新失败',
  367. showCancel: false,
  368. } as any)
  369. })
  370. }
  371. }
  372. }
  373. public canShowAd() {
  374. return cc.sys.platform === cc.sys.WECHAT_GAME
  375. }
  376. public createBannerAd(adsID) {
  377. if (!this.canShowAd()) {
  378. return
  379. }
  380. const {screenWidth, screenHeight} = this.wxSystemInfo
  381. if (this.isHigherSDKVersion('2.0.4')) {
  382. if (this.bannerAd[adsID]) {
  383. return
  384. }
  385. const bannerAd = wx.createBannerAd({
  386. adUnitId: adsID,
  387. style: {
  388. /** banner 广告组件的高度 */
  389. height: 60,
  390. /** banner 广告组件的左上角横坐标 */
  391. left: 0,
  392. /** banner 广告组件的左上角纵坐标 */
  393. top: 0,
  394. /** banner 广告组件的宽度 */
  395. width: 300,
  396. },
  397. })
  398. this.bannerAd[adsID] = bannerAd
  399. }
  400. }
  401. public showBannerAd(adsID) {
  402. if (!this.canShowAd()) {
  403. return
  404. }
  405. if (adsID && this.bannerAd[adsID] !== null) {
  406. this.bannerAd[adsID].show().then(() => Log.info('showBannerAd ', adsID))
  407. } else if (adsID) {
  408. this.createBannerAd(adsID)
  409. }
  410. }
  411. public hideBannerAd(adsID) {
  412. if (!this.canShowAd()) {
  413. return
  414. }
  415. if (adsID && this.bannerAd[adsID] !== null) {
  416. this.bannerAd[adsID].hide()
  417. this.bannerAd[adsID].destroy()
  418. this.bannerAd[adsID] = null
  419. this.createBannerAd(adsID)
  420. }
  421. }
  422. public showRewardAd(adUnitId, onClose, onErr) {
  423. if (wx === null || wx.createRewardedVideoAd === null) {
  424. if (onErr) {
  425. onErr()
  426. return
  427. }
  428. }
  429. const videoAd = wx.createRewardedVideoAd({
  430. adUnitId,
  431. })
  432. const closeFunc = () => {
  433. if (onClose) {
  434. onClose()
  435. }
  436. videoAd.offClose(closeFunc)
  437. }
  438. const errFunc = () => {
  439. if (onErr) {
  440. onErr()
  441. }
  442. videoAd.offError(errFunc)
  443. }
  444. videoAd.onError(errFunc)
  445. videoAd.onClose(closeFunc)
  446. const ad = videoAd.load()
  447. Log.info('showRewardAd', adUnitId)
  448. ad.then(() => {
  449. videoAd.show()
  450. }).catch(e => {
  451. Log.error('showRewardAd catch: ', e)
  452. videoAd.offClose(closeFunc)
  453. })
  454. }
  455. // 基础库版本号
  456. public isHigherSDKVersion(targetVersion) {
  457. if (!this.isWeChat()) {
  458. return false
  459. }
  460. if (targetVersion === undefined) {
  461. return false
  462. }
  463. return this.isHigherVersion(this.wxSystemInfo.SDKVersion, targetVersion)
  464. }
  465. // 微信版本号
  466. public isHigherWXVersion(targetVersion) {
  467. if (!this.isWeChat()) {
  468. return false
  469. }
  470. if (targetVersion === undefined) {
  471. return false
  472. }
  473. return this.isHigherVersion(this.wxSystemInfo.version, targetVersion)
  474. }
  475. public isHigherVersion(curVersion, targetVersion) {
  476. let i
  477. let tmpCur
  478. let tmpTarget
  479. const verCur = curVersion.split('.')
  480. const verTarget = targetVersion.split('.')
  481. if (verCur.length > verTarget) {
  482. return true
  483. }
  484. for (i = 0; i < verCur.length; ++i) {
  485. tmpCur = Number(verCur[i])
  486. tmpTarget = Number(verTarget[i])
  487. if (tmpCur > tmpTarget) {
  488. return true
  489. } else if (tmpCur < tmpTarget) {
  490. return false
  491. } else if (i === verCur.length - 1 && tmpCur >= tmpTarget) {
  492. return true
  493. }
  494. }
  495. Log.info(`cur: ${curVersion},target: ${targetVersion}`)
  496. return false
  497. }
  498. public checkSessionKey(successCB, failCB) {
  499. if (this.isWeChat()) {
  500. wx.checkSession({
  501. success: () => {
  502. Log.info('checkSessionKey is success')
  503. if (successCB) {
  504. successCB()
  505. }
  506. },
  507. fail: () => {
  508. Log.info('checkSessionKey is fail')
  509. failCB()
  510. },
  511. })
  512. }
  513. }
  514. public createGameClubButton(node: cc.Node) {
  515. if (this.isHigherSDKVersion('2.0.3')) {
  516. let canvasSize = this.getNodeCanvasSize(node)
  517. let style: WechatMinigame.OptionStyle = {
  518. backgroundColor: '',
  519. borderColor: '',
  520. borderRadius: 0,
  521. borderWidth: 0,
  522. color: '',
  523. fontSize: 0,
  524. height: canvasSize.height,
  525. left: canvasSize.left,
  526. lineHeight: 0,
  527. textAlign: 'center',
  528. top: canvasSize.top,
  529. width: canvasSize.width,
  530. }
  531. let btn = wx.createGameClubButton({
  532. icon: undefined,
  533. image: '',
  534. style,
  535. type: 'text',
  536. text: '',
  537. })
  538. // @ts-ignore
  539. btn.hide()
  540. this.wxGameClubBtn = btn
  541. }
  542. // this.WxGameClubBtn = null;
  543. }
  544. public showOrHideWxClubBtn(show: boolean = false) {
  545. if (this.wxGameClubBtn) {
  546. if (show) {
  547. this.wxGameClubBtn.show()
  548. } else {
  549. this.wxGameClubBtn.hide()
  550. }
  551. }
  552. }
  553. public getMenuButtonBounding() {
  554. if (this.isHigherSDKVersion('2.1.0')) {
  555. if (!this.wxMenuButtonPos) {
  556. this.wxMenuButtonPos = wx.getMenuButtonBoundingClientRect()
  557. }
  558. }
  559. }
  560. public requestMidasPayment(_offerId, num, _success, _fail) {
  561. const obj: WechatMinigame.RequestMidasPaymentOption = {
  562. mode: 'game',
  563. env: ConstValue.DEBUG ? 1 : 0,
  564. offerId: _offerId,
  565. currencyType: 'CNY',
  566. buyQuantity: num,
  567. zoneId: '1',
  568. success: _success,
  569. fail: _fail,
  570. platform: 'android',
  571. }
  572. wx.requestMidasPayment(obj)
  573. }
  574. public setClipboardData(content) {
  575. if (!this.isWeChat()) {
  576. return
  577. }
  578. if (this.isHigherSDKVersion('1.1.0')) {
  579. wx.setClipboardData({
  580. data: content,
  581. success: () => {
  582. wx.getClipboardData({
  583. success: getClipboardres => {
  584. this.showToast('成功将玩家ID复制到剪切板')
  585. },
  586. })
  587. },
  588. })
  589. } else {
  590. this.showToast('复制到剪切板失败,请升级当前微信版本')
  591. }
  592. }
  593. public createAuthorizeButton(success, fail, nodeAuthorize: cc.Node) {
  594. let canvasSize = this.getNodeCanvasSize(nodeAuthorize)
  595. let style: WechatMinigame.OptionStyle = {
  596. backgroundColor: '',
  597. borderColor: '',
  598. borderRadius: 0,
  599. borderWidth: 0,
  600. color: '',
  601. fontSize: 0,
  602. height: canvasSize.height,
  603. left: canvasSize.left,
  604. lineHeight: 0,
  605. textAlign: 'center',
  606. top: canvasSize.top,
  607. width: canvasSize.width,
  608. }
  609. const authorizeBtn = wx.createUserInfoButton({
  610. withCredentials: false,
  611. type: 'text',
  612. text: '',
  613. style,
  614. })
  615. authorizeBtn.onTap(res => {
  616. if (res.userInfo) {
  617. this.showToast('授权成功')
  618. this.wxIsAuthor = true
  619. authorizeBtn.hide()
  620. if (success) {
  621. success()
  622. }
  623. } else {
  624. this.wxIsAuthor = false
  625. this.showToast('授权失败')
  626. if (fail) {
  627. fail()
  628. }
  629. }
  630. })
  631. return authorizeBtn
  632. }
  633. public checkUserIsAuthorize(success, fail) {
  634. // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
  635. const self = this
  636. wx.getSetting({
  637. success(res) {
  638. if (res.authSetting['scope.userInfo']) {
  639. // // 已经授权,直接返回授权成功
  640. // console.log('checkUserIsAuthorize success');
  641. self.wxIsAuthor = true
  642. if (success) {
  643. success()
  644. }
  645. } else {
  646. // console.log('checkUserIsAuthorize fail');
  647. self.wxIsAuthor = false
  648. if (fail) {
  649. fail()
  650. }
  651. }
  652. },
  653. })
  654. }
  655. public requestSubscribeMessage(id: string, success?: Function, fail?: Function) {
  656. if (!this.isWeChat()) {
  657. return
  658. }
  659. // @ts-ignore
  660. if (wx.requestSubscribeMessage) {
  661. // @ts-ignore
  662. wx.requestSubscribeMessage({
  663. tmplIds: [id],
  664. success(res) {
  665. console.log(res)
  666. // res === {
  667. // errMsg: "requestSubscribeSystemMessage:ok",
  668. // SYS_MSG_TYPE_INTERACTIVE: "accept",
  669. // SYS_MSG_TYPE_RANK: 'reject'
  670. // }
  671. success && success(res)
  672. },
  673. fail() {
  674. fail && fail()
  675. },
  676. })
  677. } else {
  678. fail && fail()
  679. }
  680. }
  681. // 获取订阅消息设置
  682. public getSubscriptionsSetting(success: Function, fail: Function) {
  683. if (!this.isWeChat()) {
  684. fail && fail()
  685. return
  686. }
  687. wx.getSetting({
  688. success(res: any) {
  689. console.log(res.subscriptionsSetting)
  690. // res.subscriptionsSetting = {
  691. // mainSwitch: true, // 订阅消息总开关
  692. // itemSettings: { // 每一项开关
  693. // SYS_MSG_TYPE_INTERACTIVE: 'accept', // 小游戏系统订阅消息
  694. // SYS_MSG_TYPE_RANK: 'accept'
  695. // zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'reject', // 普通一次性订阅消息
  696. // ke_OZC_66gZxALLcsuI7ilCJSP2OJ2vWo2ooUPpkWrw: 'ban',
  697. // }
  698. // }
  699. success && success(res.subscriptionsSetting)
  700. },
  701. fail() {
  702. fail && fail()
  703. },
  704. })
  705. }
  706. }
  707. export const WxUtils = new wxUtils()