// Learn TypeScript: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html // Learn Attribute: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html // Learn life-cycle callbacks: // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html import GameM from "./GameM"; import AdM from "./AdM"; import HttpM from "./HttpM"; const { ccclass, property } = cc._decorator; @ccclass export default class WxMgr extends cc.Component { ///单例 private static instance: WxMgr = null public static getInstance() { if (this.instance == null) { this.instance = new WxMgr() } return this.instance } /** 视频广告 主动 */ public videoAd = null; /** 视频广告 被动 */ public videoAdPop = null /** 视频在播放 */ videoPlaying = false; /** 视频类型 */ watchType = ""; /** 记点击的Item挂载脚本 */ item = null; /** 加载失败提示 */ hasLoadFailTip = false; /** 授权按钮 */ authorizeBtn = null; /** 插屏广告 */ interstitialAd = null; /** banner广告 */ bannerAd = null; // LIFE-CYCLE CALLBACKS: goldShare = false /** 分享微信隐藏时间 */ wxHideTime = 0 openVibrate = false curRegionID = '' wxAuthSetting = false videoId = 'adunit-04ac9913b89d488c' popVideoId = 'adunit-32acceb75658f8da' interstitialAdID = 'adunit-a14b760c9181d6e4' bannerADID = '' bannerDayTimes = 0 bannerDayMax = 10 bannerCanRefresh = false effectSoundVol = 0 // onLoad () {} start() { } // update (dt) {} init() { // this.getUserLocation(); if (window['wx']) { window['wx'].showShareMenu({ withShareTicket: true }) /** 返回 */ window['wx'].onShow(function (res) { console.log("wx.onShow ", res); WxMgr.getInstance().videoPlaying = false; // GameCore.cache.loginSceneID = res.scene; // GameCore.audioMgr.playMusic(GameCore.audioMgr.audioObj.bg) // GameCore.httpMgr.getSwitchs(); // WxMgr.getInstance().checkShare() WxMgr.getInstance().bannerCanRefresh = true }) /** 切出去 */ window['wx'].onHide(function (res) { console.log("wx.onHide ", res); // 缓存离线时间 // let nowtime = new Date().getTime(); // cc.sys.localStorage.setItem(GameCore.cache.localOfflintTime, nowtime.toString()); // WxMgr.getInstance().videoPlaying = true; }) // let info = window['wx'].getLaunchOptionsSync(); // GameCore.cache.loginSceneID = info.scene; // console.log('当前场景值: ', GameCore.cache.loginSceneID) // GameCore.httpMgr.getSwitchs(); WxMgr.getInstance().onShare() WxMgr.getInstance().initRewardVideoAd(); } } /** 显示提示 * @param content 提示内容 */ showToast(content) { if (!window['wx']) return; window['wx'].showToast({ title: content, icon: 'none', duration: 800 }); } /** 显示确定框 * @param title 名称 * @param content 提示内容 * @param func 回调函数 * @param param 回调函数参数 */ showModal(title, content, func = null, param = null, cancelfunc = null) { var self = this; if (window['wx'] == null) { return; } window['wx'].showModal({ title: title, content: content, success(res) { if (res.confirm) { console.log('用户点击确定'); if (func) { if (param) { func(param); } else { func(); } } } else if (res.cancel) { console.log('用户点击取消'); if (cancelfunc) { cancelfunc(); } } } }) } /** 阿拉丁埋点 * @param eventName 触发事件 * @param key 事件名称 * @param value 事件对象 */ aldSendEvent(eventName, data) { if (!window['wx']) return; if (!window['wx'].aldSendEvent) return; if (eventName == "加载失败") { if (!this.hasLoadFailTip) { this.hasLoadFailTip = true; this.showModal("", "当前网络不佳,请检查网络后重试", this.applyUpdate(), null, this.applyUpdate()); } } window['wx'].aldSendEvent(eventName, data); } /** 阿拉丁埋点 关卡开始 * @param levelID 关卡ID * @param levelName 关卡名称 */ aldSendStart(levelID, levelName) { if (!window['wx']) return; if (!window['wx'].aldStage) return; //关卡完成 window['wx'].aldStage.onStart({ stageId: levelID, //关卡ID 该字段必传 stageName: levelName, //关卡名称 该字段必传 userId: "", //用户ID 可选 }) } /** 阿拉丁埋点 关卡开始 * @param levelID 关卡ID * @param levelName 关卡名称 * @param event 关卡事件 */ aldSendRunning(levelID, levelName, event) { if (!window['wx']) return; if (!window['wx'].aldStage) return; //关卡中,用户使用道具 window['wx'].aldStage.onRunning({ stageId: levelID, //关卡ID 该字段必传 stageName: levelName, //关卡名称 该字段必传 userId: "", //用户ID 可选 event: event, //使用道具 关卡进行中,用户触发的操作 该字段必传 params: { itemName: "",//使用道具名称 该字段必传 } }) } /** 阿拉丁埋点 关卡完成 * @param levelID 关卡ID * @param levelName 关卡名称 * @param event 关卡完成 关卡进行中,用户触发的操作 该字段必传 */ aldSendEnd(levelID, levelName, event) { if (!window['wx']) return; if (!window['wx'].aldStage) return; //关卡完成 window['wx'].aldStage.onEnd({ stageId: levelID, //关卡ID 该字段必传 stageName: levelName, //关卡名称 该字段必传 userId: "", //用户ID 可选 event: event, //关卡完成 关卡进行中,用户触发的操作 该字段必传 params: { desc: "" //描述 } }) } applyUpdate() { let updateManager = window['wx'].getUpdateManager() updateManager.applyUpdate(); } /**每一分钟存储一次离线收益时间 */ localOffline() { // if (this.outlineBack) { // return; // } // this.outlineBack = function () { // let _now = new Date().getTime(); // cc.sys.localStorage.setItem(GameCore.cache.localOfflintTime, String(_now)); // } // this.schedule(this.outlineBack, 60); } /** 预加载激励视频 */ initRewardVideoAd() { var self = this; if (!window['wx']) return; //主动拉视频 self.videoAd = window['wx'].createRewardedVideoAd({ adUnitId: WxMgr.getInstance().videoId, multiton: true }); if (self.videoAd == null || self.videoAd == undefined) { console.log("videoAd is null"); return; } self.videoAd.onLoad(() => { // GameCore.cache.hasVideo = true; console.log('激励视频 广告加载成功') }) self.videoAd.onError(err => { console.log("rewardAderror:", err) }) self.videoAd.onClose(res => { self.videoPlaying = false; // GameCore.audioMgr.setResumeMusic(); GameM.audioM.setResumeMusic() GameM.audioM.setEffectVolume(1) // 用户点击了【关闭广告】按钮 // 小于 2.1.0 的基础库版本,res 是一个 undefined if (res && res.isEnded || res === undefined) { // 正常播放结束,可以下发游戏奖励 AdM.onVideoWatchEnd() } else { // 播放中途退出,不下发游戏奖励 AdM.onWatchCancleEnd() // WxMgr.getInstance().showToast('观看完整视频才能获得奖励') } }) //被动拉视频 self.videoAdPop = window['wx'].createRewardedVideoAd({ adUnitId: WxMgr.getInstance().popVideoId, multiton: true }); if (self.videoAdPop == null || self.videoAdPop == undefined) { console.log("videoAdPop is null"); return; } self.videoAdPop.onLoad(() => { // GameCore.cache.hasVideo = true; console.log('激励视频 广告加载成功') }) self.videoAdPop.onError(err => { console.log("rewardAderror:", err) }) self.videoAdPop.onClose(res => { self.videoPlaying = false; // GameCore.audioMgr.setResumeMusic(); GameM.audioM.setResumeMusic() GameM.audioM.setEffectVolume(1) // 用户点击了【关闭广告】按钮 // 小于 2.1.0 的基础库版本,res 是一个 undefined if (res && res.isEnded || res === undefined) { // 正常播放结束,可以下发游戏奖励 AdM.onVideoWatchEnd() } else { // 播放中途退出,不下发游戏奖励 AdM.onWatchCancleEnd() // WxMgr.getInstance().showToast('观看完整视频才能获得奖励') } }) } /** 播放广告 * @param type 1 主动拉视频 2 被动拉视频 */ showRewardAd(type) { var self = this; if (window['wx'] == null) { return; } let ad = null if (type == 0) { ad = self.videoAd } else { ad = self.videoAdPop } if (ad != null && ad != undefined) { GameM.audioM.setPauseMusic() // this.effectSoundVol = GameM.audioM.getEffectVolume() GameM.audioM.setEffectVolume(0) self.videoPlaying = true; ad.show() .catch(err => { self.videoPlaying = false; GameM.audioM.setResumeMusic() GameM.audioM.setEffectVolume(1) //视频加载失败 AdM.onWatchFailEnd() }) } else { AdM.onWatchFailEnd() } } /**短震动 */ vibShort() { if (window['wx'] == null) { return; } // if (!this.openVibrate) { // return; // } window['wx'].vibrateShort({ success: res => { }, fail: res => { }, complete: () => { } }); } /**长震动 */ vibLong() { if (window['wx'] == null) { return; } // if (!this.openVibrate) { // return; // } window['wx'].vibrateLong({ success: res => { // console.log('--------------------------------长震动成功----------------------') }, fail: err => { // console.log('--------------------------------长震动失败', err) }, complete: () => { } }); } /** * 监听用户点击右上角菜单的「转发」按钮 */ onShare() { if (window['wx'] == null) { return; } window['wx'].onShareAppMessage(() => ({ title: '快来降伏武将,领取红包吧!', imageUrl: GameM.commonData.resURL + 'share_pic/share.png' // 图片 URL })) } /**主动转发 * @param type 分享类型 0 单挑 */ shareBox() { if (window['wx'] == null) { return; } window['wx'].shareAppMessage({ title: `快来降伏武将,领取红包吧!`, imageUrl: GameM.commonData.resURL + 'share_pic/share.png', // 图片 URL // query: "roomID=" + roomID + "&inviteType=" + type + "&userName=" + GameCore.cache.wxUserName_data + "&userAvatar=" + GameCore.cache.wxUserHead_data, success: function () { console.log("分享成功"); } }); } checkShare() { if (this.goldShare) { this.goldShare = false let date = new Date() //分享成功 if ((date.getTime() - this.wxHideTime) * 0.001 > 3) { cc.find('Canvas').getComponent('CoreNode').onShareEndGold() } else { this.showToast('分享失败,请点击更多的群分享!') } } } /** 微信登陆 */ gameLogin() { let wx = window["wx"]; if (wx == null) { return; } wx.login({ success(res) { if (res.code) { GameM.commonData.wxCode = res.code; console.log("微信登陆成功,获到code ", res.code); HttpM.Instance.init() } else { console.log('登陆失败! ', res.errMsg) } } }) } /** 微信授权 */ getSetting() { let wx = window["wx"]; if (wx == null) { return; } wx.getSetting({ success: function (res) { console.log("授权信息 ", res); var authSetting = res.authSetting; let info = window['wx'].getLaunchOptionsSync(); let sw, sh, sr, sb; // if (info.query.inviteType == 0) { // sw = 2000; // sh = 2000; // sr = 0; // sb = 0; // } // else { // sw = 60; // sh = 60; // sr = 25; // sb = 325; // } sw = 60; sh = 60; sr = 25; sb = 325; if (authSetting['scope.userInfo'] === true) { // 用户已授权,可以直接调用相关 API WxMgr.getInstance().wxAuthSetting = true; wx.getUserInfo({ success: function (res) { var userInfo = res.userInfo; var nickName = userInfo.nickName; var avatarUrl = userInfo.avatarUrl; var openId = userInfo.openId; // var gender = userInfo.gender; //性别 0:未知、1:男、2:女 // var province = userInfo.province; // var city = userInfo.city; // var country = userInfo.country; // GameCore.cache.wxUserHead_data = avatarUrl; // GameCore.cache.wxUserName_data = nickName; // WxMgr.getInstance().postAuthorize(); } }) } else if (authSetting['scope.userInfo'] === false) { WxMgr.getInstance().wxAuthSetting = false; // 用户已拒绝授权,再调用相关 API 或者 wx.authorize 会失败,需要引导用户到设置页面打开授权开关 WxMgr.getInstance().showToast("您未授权,不能提现") } else { // 未询问过用户授权,调用相关 API 或者 wx.authorize 会弹窗询问用户 wx.login( { success: (res) => { var button = wx.createUserInfoButton( { type: 'text', text: '', style: { // left: wx.getSystemInfoSync().windowWidth / 2, // top: wx.getSystemInfoSync().windowHeight / 2, right: sr, bottom: sb, width: sw, height: sh, // lineHeight: 600, backgroundColor: '#ff0000', // color: '#4b3623', // textAlign: 'center', // fontSize: 20, // borderRadius: 4 } }) button.onTap((res) => { if (res.errMsg == "getUserInfo:ok") { WxMgr.getInstance().wxAuthSetting = true; console.log("授权用户信息") //获取到用户信息 // GameCore.cache.wxUserHead_data = res.userInfo.avatarUrl; // GameCore.cache.wxUserName_data = res.userInfo.nickName; HttpM.Instance.wxlogin() //清除微信授权按钮 button.destroy(); } else { WxMgr.getInstance().wxAuthSetting = false; console.log("授权失败"); button.destroy(); } }) WxMgr.getInstance().authorizeBtn = button; WxMgr.getInstance().authorizeBtn.hide(); console.log("授权按钮创建成功") } }) } } }) } /** 显示/隐藏授权按钮 * @param state true 显示 false 隐藏 */ showAuthorize(state) { console.log("授权按钮状态 ", state) if (!WxMgr.getInstance().wxAuthSetting && WxMgr.getInstance().authorizeBtn) { if (state) { WxMgr.getInstance().authorizeBtn.show(); // WxMgr.getInstance().authorizeBtn.hide(); console.log("授权按钮状态 显示") } else { WxMgr.getInstance().authorizeBtn.hide(); console.log("授权按钮状态 隐藏") } } } // /** 登陆服务器 */ // loginNet() { // let httpRequest = new XMLHttpRequest(); // if (!httpRequest) { // alert('Giving up :( Cannot create an XMLHTTP instance'); // return false; // } // httpRequest.onreadystatechange = function () { // if (httpRequest.readyState === XMLHttpRequest.DONE) { // if (httpRequest.status === 200) { // var responseStr = httpRequest.responseText; // let response = JSON.parse(responseStr); // console.log("登陆服务器成功 ", response); // GameCore.cache.token = response.data.token; // WxMgr.getInstance().getSetting(); // } else { // console.log('issue with the request loginNet.'); // } // } // }; // httpRequest.open('GET', 'https://api-brawlv.y7y.net/api/1.0/login?code=' + GameCore.cache.wxCode); // httpRequest.send(); // } /**获取授权 */ // postAuthorize() { // let httpRequest = new XMLHttpRequest(); // if (!httpRequest) { // alert('Giving up :( Cannot create an XMLHTTP instance'); // return false; // } // httpRequest.onreadystatechange = function () { // if (httpRequest.readyState === XMLHttpRequest.DONE) { // if (httpRequest.status === 200) { // var response = httpRequest.responseText; // response = JSON.parse(response); // console.log("获取授权成功 ", response) // } else { // console.log('There was a problem with the request postAuthorize.'); // } // } // }; // var data = { // "username": GameCore.cache.wxUserName_data, // "avatar": GameCore.cache.wxUserHead_data // }; // httpRequest.setRequestHeader("token", GameCore.cache.token); // httpRequest.open('POST', 'https://api-brawlv.y7y.net/api/1.0/login'); // httpRequest.send(JSON.stringify(data)); // } /**获取用户成功 */ getUsers(num) { // let httpRequest = new XMLHttpRequest(); // if (!httpRequest) { // alert('Giving up :( Cannot create an XMLHTTP instance'); // return false; // } // httpRequest.onreadystatechange = function () { // if (httpRequest.readyState === XMLHttpRequest.DONE) { // if (httpRequest.status === 200) { // var response = httpRequest.responseText; // response = JSON.parse(response); // console.log("获取用户成功 ", response) // GameCore.cache.friendList = response.data; // let curNode = cc.find("Canvas/main"); // if (curNode) { // curNode.getComponent("StartSceneUi").freshFiendContent(); // } // } else { // console.log('There was a problem with the request postAuthorize.'); // } // } // }; // httpRequest.setRequestHeader("token", GameCore.cache.token); // httpRequest.open('GET', 'https://api-brawlv.y7y.net/api/1.0/player?num=' + num.toString()); // httpRequest.send(); } /** 插屏 */ createInterstitialAd() { if (!window['wx']) { return; } this.interstitialAd = window['wx'].createInterstitialAd({ adUnitId: WxMgr.getInstance().interstitialAdID }) this.interstitialAd.onLoad(() => { console.log('插屏 广告加载成功') }) this.interstitialAd.show().catch((err) => { console.error(err) }) this.interstitialAd.onError(err => { console.log(err) }) this.interstitialAd.onClose(res => { console.log('插屏 广告关闭') }) } private realtop = 0; private bannerTop = 0; private bannerHeight = 0; public bannerError = false; /**创建banner * @param type 0 最下方靠左 1 左上角 2 最下方居中 3 disy中间位置向下偏移 4 最底下向上偏移 */ createBannerAd(type = 0, disy = 0) { var self = this; if (!window['wx']) return; var info = window['wx'].getSystemInfoSync(); let phoneWidth = info.screenWidth; //手机屏幕宽度 let phoneHeight = info.screenHeight; //手机屏幕高度 if (!self.bannerAd) { let banID; // if (Math.random() <= 1) { banID = WxMgr.getInstance().bannerADID self.bannerAd = window['wx'].createBannerAd({ adUnitId: banID, style: { left: 0, top: phoneHeight, width: 360, } }) // } // else { // console.log('444444444444') // banID = GameCore.cache.bannerBoxADID // // 创建格子广告实例,提前初始化 // self.bannerAd = window['wx'].createGridAd({ // adUnitId: banID, // adTheme: 'white', // gridCount: 5, // style: { // left: 0, // top: 0, // width: 330, // opacity: 0.8 // } // }) // } // console.log('ccccc ') } let setHeight = false; if (self.bannerAd == null || self.bannerAd == undefined) { console.log("bannerAd is null"); return; } self.bannerAd.onResize(res => { self.realtop = self.bannerAd.style.realHeight; if (phoneHeight > 1334) { self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5; self.bannerAd.style.top = phoneHeight - self.realtop - 30; self.bannerTop = 1060; } else { let tempH = self.bannerHeight * phoneHeight / 750; if (type == 0) { self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5 - 150; self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight; } else if (type == 1) { self.bannerAd.style.left = 0 self.bannerAd.style.top = 0 } else if (type == 2) { self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5; self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight; } else if (type == 3) { self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5; self.bannerAd.style.top = phoneHeight * 0.5 + disy; } else if (type == 4) { self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5; self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight - disy; } self.bannerTop = self.bannerAd.style.top * 750 / phoneHeight - 60; //重设banner广告宽度 if (!setHeight) { setHeight = true; let rate = self.realtop / tempH; if (type == 1) { rate = 2; } self.bannerAd.style.width = self.bannerAd.style.realWidth / rate; } } }) self.bannerAd.onLoad(res => { self.bannerError = false; console.log("bannerAdLoad: "); WxMgr.getInstance().bannerDayTimes++ // GameCore.setLocalData(GameCore.cache.localStorageKey.bannerDayTimes, WxMgr.getInstance().bannerDayTimes, 1) }); self.bannerAd.onError(res => { console.log("加载banner错误:", res); self.bannerError = true; }); self.bannerAd.show().catch((err) => { self.bannerError = true; console.log('显示banner错误:', err) }); } checkBannerFresh() { if (WxMgr.getInstance().bannerDayTimes >= WxMgr.getInstance().bannerDayMax) { return false } else { return true } } /**隐藏广告 */ showBannerAD() { if (this.bannerAd != null && this.bannerAd != undefined) { this.bannerAd.show(); } } /**隐藏广告 */ hideBannerAD() { if (this.bannerAd != null && this.bannerAd != undefined) { this.bannerAd.hide(); } } /** * 销毁banner广告 */ destroyBannerAD() { if (WxMgr.getInstance().bannerCanRefresh || WxMgr.getInstance().checkBannerFresh()) { WxMgr.getInstance().bannerCanRefresh = false if (this.bannerAd != null && this.bannerAd != undefined) { this.bannerAd.destroy(); this.bannerAd = null; } } else { WxMgr.getInstance().hideBannerAD() } } /** 复制 * @param str 复制内容 */ clipboardData(str) { if (!window['wx']) { return } window['wx'].setClipboardData({ data: str, success(res) { window['wx'].getClipboardData({ success(res) { console.log(res.data) // data } }) } }) } }