123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760 |
- /** @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()
|