/** @format */ import {Log} from './LogUtils' import {ConstValue} from '../data/ConstValue' class wxUtils { public wxSystemInfo: wx.systemInfo = null public wxLaunchOptions: any = null public wxIsAuthor: boolean = false public wxMenuButtonPos = null public hideCB: any = null public showCB: any = null public wxOnHide: boolean = false public bannerAd: wx.BannerAd[] = [] public wxGameClubBtn: any = null public scene: string | number = '' public canvas: wx.Canvas = null public isWeChat(): boolean { // @ts-ignore let _global = typeof window === 'undefined' ? global : window // @ts-ignore return cc.sys.platform == cc.sys.WECHAT_GAME && !cc.sys.isBrowser && typeof _global.qq === 'undefined' } public init() { if (!this.isWeChat()) { return } this.wxSystemInfo = wx.getSystemInfoSync() if (!this.canvas) this.canvas = wx.createCanvas() Log.info('getSystemInfo', this.wxSystemInfo) } public getNodeCanvasSize(node: cc.Node) { let frameSize = cc.view.getFrameSize() let winSize = cc.winSize let left = ((winSize.width * 0.5 + node.x - node.width * 0.5) / winSize.width) * frameSize.width let top = ((winSize.height * 0.5 - node.y - node.height * 0.5) / winSize.height) * frameSize.height let width = (node.width / winSize.width) * frameSize.width let height = (node.height / winSize.height) * frameSize.height return {left, top, width, height} } public login(hostUrl, successCB, failCB) { wx.login({ success: res => { successCB && successCB(res) }, fail: failCB, }) } public request(reqUrl, reqMethod, successCB, failCB, type) { wx.request({ url: reqUrl, method: reqMethod, success: res => { successCB && successCB(res.data) }, fail: () => { failCB && failCB() }, responseType: type, }) } public reset(width, height) { if (!this.isWeChat()) { return } } public startShare(shareQuery: string = '', title?: string, imageUrl?: string) { // if (!this.isWeChat() || !ConstData.config.shareArr) { // return // } // if (!title) { // const shareObj = ConstData.config.shareArr[Math.floor(Math.random() * ConstData.config.shareArr.length)] // title = shareObj.shareWord // imageUrl = shareObj.url // shareQuery += `&imageChannel=${shareObj.imageChannel}` // } // wx.onShareAppMessage(() => ({ // title: title, // imageUrl: imageUrl, // query: shareQuery, // })) // wx.showShareMenu({withShareTicket: true}) } public share(shareQuery, title?: string, imageUrl?: string) { // if (!this.isWeChat() || !ConstData.config.shareArr) { // return // } // const shareObj = ConstData.config.shareArr[Math.floor(Math.random() * ConstData.config.shareArr.length)] // if (!title) { // title = shareObj.shareWord // } // if (!imageUrl) { // imageUrl = shareObj.url // shareQuery += `&imageChannel=${shareObj.imageChannel}` // } // wx.shareAppMessage({ // title: title, // imageUrl: imageUrl, // query: shareQuery, // }) } public getShareInfo(shareTicket, successCB, failCB) { if (!this.isWeChat()) { return } // @ts-ignore wx.getShareInfo({ shareTicket, success: res => { successCB(res) }, fail: failCB, }) } public setData(k, v) { if (!this.isWeChat()) { return } if (!this.isHigherSDKVersion('1.9.92')) { return } wx.setUserCloudStorage({ KVDataList: [{key: k, value: v}], success: e => {}, fail: e => {}, }) } public deleteData(key) { if (!this.isWeChat()) { return } wx.removeUserCloudStorage({ keyList: [key], success: e => {}, fail: e => {}, }) } public postMessage(_cmd, _data) { if (!this.isWeChat()) { return } const openDataContext = wx.getOpenDataContext() openDataContext.postMessage({ cmd: _cmd, data: _data, }) } public showWebImage(url) { if (!this.isWeChat()) { return } wx.previewImage({ current: url, urls: [url], success: () => {}, fail: () => {}, complete: () => {}, }) } public downloadFile(_urls, successFunc, failFunc, completeFunc) { if (!wx.downloadFile) { return } wx.downloadFile({ url: _urls, success: successFunc, fail: failFunc, complete: completeFunc, }) } public shock() { if (!this.isWeChat()) { return } wx.vibrateLong({ success: () => {}, fail: () => {}, }) } public createFeedbackButton(node: cc.Node) { if (!this.isWeChat()) { return } let canvasSize = this.getNodeCanvasSize(node) let style: WechatMinigame.OptionStyle = { backgroundColor: '', borderColor: '', borderRadius: 0, borderWidth: 0, color: '', fontSize: 0, height: canvasSize.height, left: canvasSize.left, lineHeight: 0, textAlign: 'center', top: canvasSize.top, width: canvasSize.width, } let button = wx.createFeedbackButton({ type: 'image', image: '', style, }) return button } public openConversation(sucFunc, failFunc) { if (!this.isHigherSDKVersion('2.0.3')) { return } wx.openCustomerServiceConversation({ success: sucFunc, fail: failFunc, }) } public saveIMGForShare(sucFunc, failFunc, node: cc.Node) { if (!this.isWeChat()) { return } let canvasData = this.getNodeCanvasSize(node) this.canvas.toTempFilePath({ x: canvasData.left, y: canvasData.top, width: canvasData.width, height: canvasData.height, success(res) { // .可以保存该截屏图片 wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: sucFunc, fail: failFunc, }) }, }) } public loadUserInfo(succ, fail) { // 读取玩家微信数据 wx.getUserInfo({ success: res => { if (succ) { succ(res.userInfo) } }, fail: () => { if (fail) { fail() } }, }) } public navigateToMiniProgram(appid, apppath) { if (!this.isWeChat()) { return } if (this.isHigherSDKVersion('2.2.0')) { wx.navigateToMiniProgram({ appId: appid, path: apppath, envVersion: 'release', extraData: null, fail: res => { this.showToast('跳转失败,请重试') }, success: () => {}, }) } else { this.showToast('当前微信版本过低,请升级到最新版本') } } public showToast(title, icon: any = 'none', duration = 2000) { wx.showToast({ title, icon, duration, } as any) } public showModal(title, content, cancelText, confirmText, success, fail) { if (!this.isWeChat()) { return } wx.showModal({ cancelText, confirmText, title, content, success(res) { if (res.confirm) { success() } }, fail, showCancel: true, }) } public groupShare(title, url, rQuery) { if (!this.isWeChat()) { return } wx.shareAppMessage({ title, imageUrl: url, query: rQuery, }) } public onHide(callback) { if (this.isWeChat()) { if (this.hideCB) { wx.offHide(this.hideCB) } this.hideCB = res => { if (callback) { callback() } this.wxOnHide = true } wx.onHide(this.hideCB) } } public onShow(callback) { if (this.isWeChat()) { if (this.showCB) { wx.offShow(this.showCB) } this.showCB = res => { Log.info('show back: ', res) this.scene = res && res.scene ? res.scene : this.scene if (callback) { callback(res) } this.wxOnHide = false } wx.onShow(this.showCB) } } public launchBack() { if (this.isWeChat()) { this.wxLaunchOptions = wx.getLaunchOptionsSync() this.scene = this.wxLaunchOptions && this.wxLaunchOptions.scene ? this.wxLaunchOptions.scene : this.scene Log.info('launchBack:wxLaunchOptions=>', this.wxLaunchOptions) } } public checkUpdate() { if (this.isWeChat() && this.isHigherSDKVersion('1.9.90') && typeof wx.getUpdateManager === 'function') { Log.info('检查更新') const updateManager = wx.getUpdateManager() if (this.isHigherWXVersion('6.6.7') || cc.sys.os === cc.sys.OS_IOS) { updateManager.onCheckForUpdate(res => { Log.info('res.hasUpdate', res.hasUpdate) if (res.hasUpdate) { Log.info('需要更新') } else { Log.info('无更新') } }) updateManager.onUpdateReady(() => { wx.showModal({ title: '提示', content: '新版本下载完成,是否立即重启', success(res) { if (res.confirm) { updateManager.applyUpdate() } }, }) }) updateManager.onUpdateFailed(() => { wx.showModal({ title: '提示', content: '更新失败', showCancel: false, } as any) }) } } } public canShowAd() { return cc.sys.platform === cc.sys.WECHAT_GAME } public createBannerAd(adsID) { if (!this.canShowAd()) { return } const {screenWidth, screenHeight} = this.wxSystemInfo if (this.isHigherSDKVersion('2.0.4')) { if (this.bannerAd[adsID]) { return } const bannerAd = wx.createBannerAd({ adUnitId: adsID, style: { /** banner 广告组件的高度 */ height: 60, /** banner 广告组件的左上角横坐标 */ left: 0, /** banner 广告组件的左上角纵坐标 */ top: 0, /** banner 广告组件的宽度 */ width: 300, }, }) this.bannerAd[adsID] = bannerAd } } public showBannerAd(adsID) { if (!this.canShowAd()) { return } if (adsID && this.bannerAd[adsID] !== null) { this.bannerAd[adsID].show().then(() => Log.info('showBannerAd ', adsID)) } else if (adsID) { this.createBannerAd(adsID) } } public hideBannerAd(adsID) { if (!this.canShowAd()) { return } if (adsID && this.bannerAd[adsID] !== null) { this.bannerAd[adsID].hide() this.bannerAd[adsID].destroy() this.bannerAd[adsID] = null this.createBannerAd(adsID) } } public showRewardAd(adUnitId, onClose, onErr) { if (wx === null || wx.createRewardedVideoAd === null) { if (onErr) { onErr() return } } const videoAd = wx.createRewardedVideoAd({ adUnitId, }) const closeFunc = () => { if (onClose) { onClose() } videoAd.offClose(closeFunc) } const errFunc = () => { if (onErr) { onErr() } videoAd.offError(errFunc) } videoAd.onError(errFunc) videoAd.onClose(closeFunc) const ad = videoAd.load() Log.info('showRewardAd', adUnitId) ad.then(() => { videoAd.show() }).catch(e => { Log.error('showRewardAd catch: ', e) videoAd.offClose(closeFunc) }) } // 基础库版本号 public isHigherSDKVersion(targetVersion) { if (!this.isWeChat()) { return false } if (targetVersion === undefined) { return false } return this.isHigherVersion(this.wxSystemInfo.SDKVersion, targetVersion) } // 微信版本号 public isHigherWXVersion(targetVersion) { if (!this.isWeChat()) { return false } if (targetVersion === undefined) { return false } return this.isHigherVersion(this.wxSystemInfo.version, targetVersion) } public isHigherVersion(curVersion, targetVersion) { let i let tmpCur let tmpTarget const verCur = curVersion.split('.') const verTarget = targetVersion.split('.') if (verCur.length > verTarget) { return true } for (i = 0; i < verCur.length; ++i) { tmpCur = Number(verCur[i]) tmpTarget = Number(verTarget[i]) if (tmpCur > tmpTarget) { return true } else if (tmpCur < tmpTarget) { return false } else if (i === verCur.length - 1 && tmpCur >= tmpTarget) { return true } } Log.info(`cur: ${curVersion},target: ${targetVersion}`) return false } public checkSessionKey(successCB, failCB) { if (this.isWeChat()) { wx.checkSession({ success: () => { Log.info('checkSessionKey is success') if (successCB) { successCB() } }, fail: () => { Log.info('checkSessionKey is fail') failCB() }, }) } } public createGameClubButton(node: cc.Node) { if (this.isHigherSDKVersion('2.0.3')) { let canvasSize = this.getNodeCanvasSize(node) let style: WechatMinigame.OptionStyle = { backgroundColor: '', borderColor: '', borderRadius: 0, borderWidth: 0, color: '', fontSize: 0, height: canvasSize.height, left: canvasSize.left, lineHeight: 0, textAlign: 'center', top: canvasSize.top, width: canvasSize.width, } let btn = wx.createGameClubButton({ icon: undefined, image: '', style, type: 'text', text: '', }) // @ts-ignore btn.hide() this.wxGameClubBtn = btn } // this.WxGameClubBtn = null; } public showOrHideWxClubBtn(show: boolean = false) { if (this.wxGameClubBtn) { if (show) { this.wxGameClubBtn.show() } else { this.wxGameClubBtn.hide() } } } public getMenuButtonBounding() { if (this.isHigherSDKVersion('2.1.0')) { if (!this.wxMenuButtonPos) { this.wxMenuButtonPos = wx.getMenuButtonBoundingClientRect() } } } public requestMidasPayment(_offerId, num, _success, _fail) { const obj: WechatMinigame.RequestMidasPaymentOption = { mode: 'game', env: ConstValue.DEBUG ? 1 : 0, offerId: _offerId, currencyType: 'CNY', buyQuantity: num, zoneId: '1', success: _success, fail: _fail, platform: 'android', } wx.requestMidasPayment(obj) } public setClipboardData(content) { if (!this.isWeChat()) { return } if (this.isHigherSDKVersion('1.1.0')) { wx.setClipboardData({ data: content, success: () => { wx.getClipboardData({ success: getClipboardres => { this.showToast('成功将玩家ID复制到剪切板') }, }) }, }) } else { this.showToast('复制到剪切板失败,请升级当前微信版本') } } public createAuthorizeButton(success, fail, nodeAuthorize: cc.Node) { let canvasSize = this.getNodeCanvasSize(nodeAuthorize) let style: WechatMinigame.OptionStyle = { backgroundColor: '', borderColor: '', borderRadius: 0, borderWidth: 0, color: '', fontSize: 0, height: canvasSize.height, left: canvasSize.left, lineHeight: 0, textAlign: 'center', top: canvasSize.top, width: canvasSize.width, } const authorizeBtn = wx.createUserInfoButton({ withCredentials: false, type: 'text', text: '', style, }) authorizeBtn.onTap(res => { if (res.userInfo) { this.showToast('授权成功') this.wxIsAuthor = true authorizeBtn.hide() if (success) { success() } } else { this.wxIsAuthor = false this.showToast('授权失败') if (fail) { fail() } } }) return authorizeBtn } public checkUserIsAuthorize(success, fail) { // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope const self = this wx.getSetting({ success(res) { if (res.authSetting['scope.userInfo']) { // // 已经授权,直接返回授权成功 // console.log('checkUserIsAuthorize success'); self.wxIsAuthor = true if (success) { success() } } else { // console.log('checkUserIsAuthorize fail'); self.wxIsAuthor = false if (fail) { fail() } } }, }) } public requestSubscribeMessage(id: string, success?: Function, fail?: Function) { if (!this.isWeChat()) { return } // @ts-ignore if (wx.requestSubscribeMessage) { // @ts-ignore wx.requestSubscribeMessage({ tmplIds: [id], success(res) { console.log(res) // res === { // errMsg: "requestSubscribeSystemMessage:ok", // SYS_MSG_TYPE_INTERACTIVE: "accept", // SYS_MSG_TYPE_RANK: 'reject' // } success && success(res) }, fail() { fail && fail() }, }) } else { fail && fail() } } // 获取订阅消息设置 public getSubscriptionsSetting(success: Function, fail: Function) { if (!this.isWeChat()) { fail && fail() return } wx.getSetting({ success(res: any) { console.log(res.subscriptionsSetting) // res.subscriptionsSetting = { // mainSwitch: true, // 订阅消息总开关 // itemSettings: { // 每一项开关 // SYS_MSG_TYPE_INTERACTIVE: 'accept', // 小游戏系统订阅消息 // SYS_MSG_TYPE_RANK: 'accept' // zun-LzcQyW-edafCVvzPkK4de2Rllr1fFpw2A_x0oXE: 'reject', // 普通一次性订阅消息 // ke_OZC_66gZxALLcsuI7ilCJSP2OJ2vWo2ooUPpkWrw: 'ban', // } // } success && success(res.subscriptionsSetting) }, fail() { fail && fail() }, }) } } export const WxUtils = new wxUtils()