WxMgr.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. // Learn TypeScript:
  2. // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/typescript.html
  3. // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
  4. // Learn Attribute:
  5. // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
  6. // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
  7. // Learn life-cycle callbacks:
  8. // - [Chinese] https://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
  9. // - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html
  10. import GameM from "./GameM";
  11. import AdM from "./AdM";
  12. import HttpM from "./HttpM";
  13. const { ccclass, property } = cc._decorator;
  14. @ccclass
  15. export default class WxMgr extends cc.Component {
  16. ///单例
  17. private static instance: WxMgr = null
  18. public static getInstance() {
  19. if (this.instance == null) {
  20. this.instance = new WxMgr()
  21. }
  22. return this.instance
  23. }
  24. /** 视频广告 主动 */
  25. public videoAd = null;
  26. /** 视频广告 被动 */
  27. public videoAdPop = null
  28. /** 视频在播放 */
  29. videoPlaying = false;
  30. /** 视频类型 */
  31. watchType = "";
  32. /** 记点击的Item挂载脚本 */
  33. item = null;
  34. /** 加载失败提示 */
  35. hasLoadFailTip = false;
  36. /** 授权按钮 */
  37. authorizeBtn = null;
  38. /** 插屏广告 */
  39. interstitialAd = null;
  40. /** banner广告 */
  41. bannerAd = null;
  42. // LIFE-CYCLE CALLBACKS:
  43. goldShare = false
  44. /** 分享微信隐藏时间 */
  45. wxHideTime = 0
  46. openVibrate = false
  47. curRegionID = ''
  48. wxAuthSetting = false
  49. videoId = 'adunit-04ac9913b89d488c'
  50. popVideoId = 'adunit-32acceb75658f8da'
  51. interstitialAdID = 'adunit-a14b760c9181d6e4'
  52. bannerADID = ''
  53. bannerDayTimes = 0
  54. bannerDayMax = 10
  55. bannerCanRefresh = false
  56. effectSoundVol = 0
  57. // onLoad () {}
  58. start() {
  59. }
  60. // update (dt) {}
  61. init() {
  62. // this.getUserLocation();
  63. if (window['wx']) {
  64. window['wx'].showShareMenu({
  65. withShareTicket: true
  66. })
  67. /** 返回 */
  68. window['wx'].onShow(function (res) {
  69. console.log("wx.onShow ", res);
  70. WxMgr.getInstance().videoPlaying = false;
  71. // GameCore.cache.loginSceneID = res.scene;
  72. // GameCore.audioMgr.playMusic(GameCore.audioMgr.audioObj.bg)
  73. // GameCore.httpMgr.getSwitchs();
  74. // WxMgr.getInstance().checkShare()
  75. WxMgr.getInstance().bannerCanRefresh = true
  76. })
  77. /** 切出去 */
  78. window['wx'].onHide(function (res) {
  79. console.log("wx.onHide ", res);
  80. // 缓存离线时间
  81. // let nowtime = new Date().getTime();
  82. // cc.sys.localStorage.setItem(GameCore.cache.localOfflintTime, nowtime.toString());
  83. // WxMgr.getInstance().videoPlaying = true;
  84. })
  85. // let info = window['wx'].getLaunchOptionsSync();
  86. // GameCore.cache.loginSceneID = info.scene;
  87. // console.log('当前场景值: ', GameCore.cache.loginSceneID)
  88. // GameCore.httpMgr.getSwitchs();
  89. WxMgr.getInstance().onShare()
  90. WxMgr.getInstance().initRewardVideoAd();
  91. }
  92. }
  93. /** 显示提示
  94. * @param content 提示内容
  95. */
  96. showToast(content) {
  97. if (!window['wx'])
  98. return;
  99. window['wx'].showToast({
  100. title: content,
  101. icon: 'none',
  102. duration: 800
  103. });
  104. }
  105. /** 显示确定框
  106. * @param title 名称
  107. * @param content 提示内容
  108. * @param func 回调函数
  109. * @param param 回调函数参数
  110. */
  111. showModal(title, content, func = null, param = null, cancelfunc = null) {
  112. var self = this;
  113. if (window['wx'] == null) {
  114. return;
  115. }
  116. window['wx'].showModal({
  117. title: title,
  118. content: content,
  119. success(res) {
  120. if (res.confirm) {
  121. console.log('用户点击确定');
  122. if (func) {
  123. if (param) {
  124. func(param);
  125. } else {
  126. func();
  127. }
  128. }
  129. } else if (res.cancel) {
  130. console.log('用户点击取消');
  131. if (cancelfunc) {
  132. cancelfunc();
  133. }
  134. }
  135. }
  136. })
  137. }
  138. /** 阿拉丁埋点
  139. * @param eventName 触发事件
  140. * @param key 事件名称
  141. * @param value 事件对象
  142. */
  143. aldSendEvent(eventName, data) {
  144. if (!window['wx'])
  145. return;
  146. if (!window['wx'].aldSendEvent)
  147. return;
  148. if (eventName == "加载失败") {
  149. if (!this.hasLoadFailTip) {
  150. this.hasLoadFailTip = true;
  151. this.showModal("", "当前网络不佳,请检查网络后重试", this.applyUpdate(), null, this.applyUpdate());
  152. }
  153. }
  154. window['wx'].aldSendEvent(eventName, data);
  155. }
  156. /** 阿拉丁埋点 关卡开始
  157. * @param levelID 关卡ID
  158. * @param levelName 关卡名称
  159. */
  160. aldSendStart(levelID, levelName) {
  161. if (!window['wx'])
  162. return;
  163. if (!window['wx'].aldStage)
  164. return;
  165. //关卡完成
  166. window['wx'].aldStage.onStart({
  167. stageId: levelID, //关卡ID 该字段必传
  168. stageName: levelName, //关卡名称 该字段必传
  169. userId: "", //用户ID 可选
  170. })
  171. }
  172. /** 阿拉丁埋点 关卡开始
  173. * @param levelID 关卡ID
  174. * @param levelName 关卡名称
  175. * @param event 关卡事件
  176. */
  177. aldSendRunning(levelID, levelName, event) {
  178. if (!window['wx'])
  179. return;
  180. if (!window['wx'].aldStage)
  181. return;
  182. //关卡中,用户使用道具
  183. window['wx'].aldStage.onRunning({
  184. stageId: levelID, //关卡ID 该字段必传
  185. stageName: levelName, //关卡名称 该字段必传
  186. userId: "", //用户ID 可选
  187. event: event, //使用道具 关卡进行中,用户触发的操作 该字段必传
  188. params: {
  189. itemName: "",//使用道具名称 该字段必传
  190. }
  191. })
  192. }
  193. /** 阿拉丁埋点 关卡完成
  194. * @param levelID 关卡ID
  195. * @param levelName 关卡名称
  196. * @param event 关卡完成 关卡进行中,用户触发的操作 该字段必传
  197. */
  198. aldSendEnd(levelID, levelName, event) {
  199. if (!window['wx'])
  200. return;
  201. if (!window['wx'].aldStage)
  202. return;
  203. //关卡完成
  204. window['wx'].aldStage.onEnd({
  205. stageId: levelID, //关卡ID 该字段必传
  206. stageName: levelName, //关卡名称 该字段必传
  207. userId: "", //用户ID 可选
  208. event: event, //关卡完成 关卡进行中,用户触发的操作 该字段必传
  209. params: {
  210. desc: "" //描述
  211. }
  212. })
  213. }
  214. applyUpdate() {
  215. let updateManager = window['wx'].getUpdateManager()
  216. updateManager.applyUpdate();
  217. }
  218. /**每一分钟存储一次离线收益时间 */
  219. localOffline() {
  220. // if (this.outlineBack) {
  221. // return;
  222. // }
  223. // this.outlineBack = function () {
  224. // let _now = new Date().getTime();
  225. // cc.sys.localStorage.setItem(GameCore.cache.localOfflintTime, String(_now));
  226. // }
  227. // this.schedule(this.outlineBack, 60);
  228. }
  229. /** 预加载激励视频 */
  230. initRewardVideoAd() {
  231. var self = this;
  232. if (!window['wx'])
  233. return;
  234. //主动拉视频
  235. self.videoAd = window['wx'].createRewardedVideoAd({
  236. adUnitId: WxMgr.getInstance().videoId,
  237. multiton: true
  238. });
  239. if (self.videoAd == null || self.videoAd == undefined) {
  240. console.log("videoAd is null");
  241. return;
  242. }
  243. self.videoAd.onLoad(() => {
  244. // GameCore.cache.hasVideo = true;
  245. console.log('激励视频 广告加载成功')
  246. })
  247. self.videoAd.onError(err => {
  248. console.log("rewardAderror:", err)
  249. })
  250. self.videoAd.onClose(res => {
  251. self.videoPlaying = false;
  252. // GameCore.audioMgr.setResumeMusic();
  253. GameM.audioM.setResumeMusic()
  254. GameM.audioM.setEffectVolume(1)
  255. // 用户点击了【关闭广告】按钮
  256. // 小于 2.1.0 的基础库版本,res 是一个 undefined
  257. if (res && res.isEnded || res === undefined) {
  258. // 正常播放结束,可以下发游戏奖励
  259. AdM.onVideoWatchEnd()
  260. } else {
  261. // 播放中途退出,不下发游戏奖励
  262. AdM.onWatchCancleEnd()
  263. // WxMgr.getInstance().showToast('观看完整视频才能获得奖励')
  264. }
  265. })
  266. //被动拉视频
  267. self.videoAdPop = window['wx'].createRewardedVideoAd({
  268. adUnitId: WxMgr.getInstance().popVideoId,
  269. multiton: true
  270. });
  271. if (self.videoAdPop == null || self.videoAdPop == undefined) {
  272. console.log("videoAdPop is null");
  273. return;
  274. }
  275. self.videoAdPop.onLoad(() => {
  276. // GameCore.cache.hasVideo = true;
  277. console.log('激励视频 广告加载成功')
  278. })
  279. self.videoAdPop.onError(err => {
  280. console.log("rewardAderror:", err)
  281. })
  282. self.videoAdPop.onClose(res => {
  283. self.videoPlaying = false;
  284. // GameCore.audioMgr.setResumeMusic();
  285. GameM.audioM.setResumeMusic()
  286. GameM.audioM.setEffectVolume(1)
  287. // 用户点击了【关闭广告】按钮
  288. // 小于 2.1.0 的基础库版本,res 是一个 undefined
  289. if (res && res.isEnded || res === undefined) {
  290. // 正常播放结束,可以下发游戏奖励
  291. AdM.onVideoWatchEnd()
  292. } else {
  293. // 播放中途退出,不下发游戏奖励
  294. AdM.onWatchCancleEnd()
  295. // WxMgr.getInstance().showToast('观看完整视频才能获得奖励')
  296. }
  297. })
  298. }
  299. /** 播放广告
  300. * @param type 1 主动拉视频 2 被动拉视频
  301. */
  302. showRewardAd(type) {
  303. var self = this;
  304. if (window['wx'] == null) {
  305. return;
  306. }
  307. let ad = null
  308. if (type == 0) {
  309. ad = self.videoAd
  310. }
  311. else {
  312. ad = self.videoAdPop
  313. }
  314. if (ad != null && ad != undefined) {
  315. GameM.audioM.setPauseMusic()
  316. // this.effectSoundVol = GameM.audioM.getEffectVolume()
  317. GameM.audioM.setEffectVolume(0)
  318. self.videoPlaying = true;
  319. ad.show()
  320. .catch(err => {
  321. self.videoPlaying = false;
  322. GameM.audioM.setResumeMusic()
  323. GameM.audioM.setEffectVolume(1)
  324. //视频加载失败
  325. AdM.onWatchFailEnd()
  326. })
  327. }
  328. else {
  329. AdM.onWatchFailEnd()
  330. }
  331. }
  332. /**短震动 */
  333. vibShort() {
  334. if (window['wx'] == null) {
  335. return;
  336. }
  337. // if (!this.openVibrate) {
  338. // return;
  339. // }
  340. window['wx'].vibrateShort({
  341. success: res => {
  342. },
  343. fail: res => { },
  344. complete: () => { }
  345. });
  346. }
  347. /**长震动 */
  348. vibLong() {
  349. if (window['wx'] == null) {
  350. return;
  351. }
  352. // if (!this.openVibrate) {
  353. // return;
  354. // }
  355. window['wx'].vibrateLong({
  356. success: res => {
  357. // console.log('--------------------------------长震动成功----------------------')
  358. },
  359. fail: err => {
  360. // console.log('--------------------------------长震动失败', err)
  361. },
  362. complete: () => { }
  363. });
  364. }
  365. /**
  366. * 监听用户点击右上角菜单的「转发」按钮
  367. */
  368. onShare() {
  369. if (window['wx'] == null) {
  370. return;
  371. }
  372. window['wx'].onShareAppMessage(() => ({
  373. title: '快来降伏武将,领取红包吧!',
  374. imageUrl: GameM.commonData.resURL + 'share_pic/share.png' // 图片 URL
  375. }))
  376. }
  377. /**主动转发
  378. * @param type 分享类型 0 单挑
  379. */
  380. shareBox() {
  381. if (window['wx'] == null) {
  382. return;
  383. }
  384. window['wx'].shareAppMessage({
  385. title: `快来降伏武将,领取红包吧!`,
  386. imageUrl: GameM.commonData.resURL + 'share_pic/share.png', // 图片 URL
  387. // query: "roomID=" + roomID + "&inviteType=" + type + "&userName=" + GameCore.cache.wxUserName_data + "&userAvatar=" + GameCore.cache.wxUserHead_data,
  388. success: function () {
  389. console.log("分享成功");
  390. }
  391. });
  392. }
  393. checkShare() {
  394. if (this.goldShare) {
  395. this.goldShare = false
  396. let date = new Date()
  397. //分享成功
  398. if ((date.getTime() - this.wxHideTime) * 0.001 > 3) {
  399. cc.find('Canvas').getComponent('CoreNode').onShareEndGold()
  400. }
  401. else {
  402. this.showToast('分享失败,请点击更多的群分享!')
  403. }
  404. }
  405. }
  406. /** 微信登陆 */
  407. gameLogin() {
  408. let wx = window["wx"];
  409. if (wx == null) {
  410. return;
  411. }
  412. wx.login({
  413. success(res) {
  414. if (res.code) {
  415. GameM.commonData.wxCode = res.code;
  416. console.log("微信登陆成功,获到code ", res.code);
  417. HttpM.Instance.init()
  418. }
  419. else {
  420. console.log('登陆失败! ', res.errMsg)
  421. }
  422. }
  423. })
  424. }
  425. /** 微信授权 */
  426. getSetting() {
  427. let wx = window["wx"];
  428. if (wx == null) {
  429. return;
  430. }
  431. wx.getSetting({
  432. success: function (res) {
  433. console.log("授权信息 ", res);
  434. var authSetting = res.authSetting;
  435. let info = window['wx'].getLaunchOptionsSync();
  436. let sw, sh, sr, sb;
  437. // if (info.query.inviteType == 0) {
  438. // sw = 2000;
  439. // sh = 2000;
  440. // sr = 0;
  441. // sb = 0;
  442. // }
  443. // else {
  444. // sw = 60;
  445. // sh = 60;
  446. // sr = 25;
  447. // sb = 325;
  448. // }
  449. sw = 60;
  450. sh = 60;
  451. sr = 25;
  452. sb = 325;
  453. if (authSetting['scope.userInfo'] === true) {
  454. // 用户已授权,可以直接调用相关 API
  455. WxMgr.getInstance().wxAuthSetting = true;
  456. wx.getUserInfo({
  457. success: function (res) {
  458. var userInfo = res.userInfo;
  459. var nickName = userInfo.nickName;
  460. var avatarUrl = userInfo.avatarUrl;
  461. var openId = userInfo.openId;
  462. // var gender = userInfo.gender; //性别 0:未知、1:男、2:女
  463. // var province = userInfo.province;
  464. // var city = userInfo.city;
  465. // var country = userInfo.country;
  466. // GameCore.cache.wxUserHead_data = avatarUrl;
  467. // GameCore.cache.wxUserName_data = nickName;
  468. // WxMgr.getInstance().postAuthorize();
  469. }
  470. })
  471. } else if (authSetting['scope.userInfo'] === false) {
  472. WxMgr.getInstance().wxAuthSetting = false;
  473. // 用户已拒绝授权,再调用相关 API 或者 wx.authorize 会失败,需要引导用户到设置页面打开授权开关
  474. WxMgr.getInstance().showToast("您未授权,不能提现")
  475. } else {
  476. // 未询问过用户授权,调用相关 API 或者 wx.authorize 会弹窗询问用户
  477. wx.login(
  478. {
  479. success: (res) => {
  480. var button = wx.createUserInfoButton(
  481. {
  482. type: 'text',
  483. text: '',
  484. style:
  485. {
  486. // left: wx.getSystemInfoSync().windowWidth / 2,
  487. // top: wx.getSystemInfoSync().windowHeight / 2,
  488. right: sr,
  489. bottom: sb,
  490. width: sw,
  491. height: sh,
  492. // lineHeight: 600,
  493. backgroundColor: '#ff0000',
  494. // color: '#4b3623',
  495. // textAlign: 'center',
  496. // fontSize: 20,
  497. // borderRadius: 4
  498. }
  499. })
  500. button.onTap((res) => {
  501. if (res.errMsg == "getUserInfo:ok") {
  502. WxMgr.getInstance().wxAuthSetting = true;
  503. console.log("授权用户信息")
  504. //获取到用户信息
  505. // GameCore.cache.wxUserHead_data = res.userInfo.avatarUrl;
  506. // GameCore.cache.wxUserName_data = res.userInfo.nickName;
  507. HttpM.Instance.wxlogin()
  508. //清除微信授权按钮
  509. button.destroy();
  510. }
  511. else {
  512. WxMgr.getInstance().wxAuthSetting = false;
  513. console.log("授权失败");
  514. button.destroy();
  515. }
  516. })
  517. WxMgr.getInstance().authorizeBtn = button;
  518. WxMgr.getInstance().authorizeBtn.hide();
  519. console.log("授权按钮创建成功")
  520. }
  521. })
  522. }
  523. }
  524. })
  525. }
  526. /** 显示/隐藏授权按钮
  527. * @param state true 显示 false 隐藏
  528. */
  529. showAuthorize(state) {
  530. console.log("授权按钮状态 ", state)
  531. if (!WxMgr.getInstance().wxAuthSetting && WxMgr.getInstance().authorizeBtn) {
  532. if (state) {
  533. WxMgr.getInstance().authorizeBtn.show();
  534. // WxMgr.getInstance().authorizeBtn.hide();
  535. console.log("授权按钮状态 显示")
  536. }
  537. else {
  538. WxMgr.getInstance().authorizeBtn.hide();
  539. console.log("授权按钮状态 隐藏")
  540. }
  541. }
  542. }
  543. // /** 登陆服务器 */
  544. // loginNet() {
  545. // let httpRequest = new XMLHttpRequest();
  546. // if (!httpRequest) {
  547. // alert('Giving up :( Cannot create an XMLHTTP instance');
  548. // return false;
  549. // }
  550. // httpRequest.onreadystatechange = function () {
  551. // if (httpRequest.readyState === XMLHttpRequest.DONE) {
  552. // if (httpRequest.status === 200) {
  553. // var responseStr = httpRequest.responseText;
  554. // let response = JSON.parse(responseStr);
  555. // console.log("登陆服务器成功 ", response);
  556. // GameCore.cache.token = response.data.token;
  557. // WxMgr.getInstance().getSetting();
  558. // } else {
  559. // console.log('issue with the request loginNet.');
  560. // }
  561. // }
  562. // };
  563. // httpRequest.open('GET', 'https://api-brawlv.y7y.net/api/1.0/login?code=' + GameCore.cache.wxCode);
  564. // httpRequest.send();
  565. // }
  566. /**获取授权 */
  567. // postAuthorize() {
  568. // let httpRequest = new XMLHttpRequest();
  569. // if (!httpRequest) {
  570. // alert('Giving up :( Cannot create an XMLHTTP instance');
  571. // return false;
  572. // }
  573. // httpRequest.onreadystatechange = function () {
  574. // if (httpRequest.readyState === XMLHttpRequest.DONE) {
  575. // if (httpRequest.status === 200) {
  576. // var response = httpRequest.responseText;
  577. // response = JSON.parse(response);
  578. // console.log("获取授权成功 ", response)
  579. // } else {
  580. // console.log('There was a problem with the request postAuthorize.');
  581. // }
  582. // }
  583. // };
  584. // var data = {
  585. // "username": GameCore.cache.wxUserName_data,
  586. // "avatar": GameCore.cache.wxUserHead_data
  587. // };
  588. // httpRequest.setRequestHeader("token", GameCore.cache.token);
  589. // httpRequest.open('POST', 'https://api-brawlv.y7y.net/api/1.0/login');
  590. // httpRequest.send(JSON.stringify(data));
  591. // }
  592. /**获取用户成功 */
  593. getUsers(num) {
  594. // let httpRequest = new XMLHttpRequest();
  595. // if (!httpRequest) {
  596. // alert('Giving up :( Cannot create an XMLHTTP instance');
  597. // return false;
  598. // }
  599. // httpRequest.onreadystatechange = function () {
  600. // if (httpRequest.readyState === XMLHttpRequest.DONE) {
  601. // if (httpRequest.status === 200) {
  602. // var response = httpRequest.responseText;
  603. // response = JSON.parse(response);
  604. // console.log("获取用户成功 ", response)
  605. // GameCore.cache.friendList = response.data;
  606. // let curNode = cc.find("Canvas/main");
  607. // if (curNode) {
  608. // curNode.getComponent("StartSceneUi").freshFiendContent();
  609. // }
  610. // } else {
  611. // console.log('There was a problem with the request postAuthorize.');
  612. // }
  613. // }
  614. // };
  615. // httpRequest.setRequestHeader("token", GameCore.cache.token);
  616. // httpRequest.open('GET', 'https://api-brawlv.y7y.net/api/1.0/player?num=' + num.toString());
  617. // httpRequest.send();
  618. }
  619. /** 插屏 */
  620. createInterstitialAd() {
  621. if (!window['wx']) {
  622. return;
  623. }
  624. this.interstitialAd = window['wx'].createInterstitialAd({ adUnitId: WxMgr.getInstance().interstitialAdID })
  625. this.interstitialAd.onLoad(() => {
  626. console.log('插屏 广告加载成功')
  627. })
  628. this.interstitialAd.show().catch((err) => {
  629. console.error(err)
  630. })
  631. this.interstitialAd.onError(err => {
  632. console.log(err)
  633. })
  634. this.interstitialAd.onClose(res => {
  635. console.log('插屏 广告关闭')
  636. })
  637. }
  638. private realtop = 0;
  639. private bannerTop = 0;
  640. private bannerHeight = 0;
  641. public bannerError = false;
  642. /**创建banner
  643. * @param type 0 最下方靠左 1 左上角 2 最下方居中 3 disy中间位置向下偏移 4 最底下向上偏移
  644. */
  645. createBannerAd(type = 0, disy = 0) {
  646. var self = this;
  647. if (!window['wx']) return;
  648. var info = window['wx'].getSystemInfoSync();
  649. let phoneWidth = info.screenWidth; //手机屏幕宽度
  650. let phoneHeight = info.screenHeight; //手机屏幕高度
  651. if (!self.bannerAd) {
  652. let banID;
  653. // if (Math.random() <= 1) {
  654. banID = WxMgr.getInstance().bannerADID
  655. self.bannerAd = window['wx'].createBannerAd({
  656. adUnitId: banID,
  657. style: {
  658. left: 0,
  659. top: phoneHeight,
  660. width: 360,
  661. }
  662. })
  663. // }
  664. // else {
  665. // console.log('444444444444')
  666. // banID = GameCore.cache.bannerBoxADID
  667. // // 创建格子广告实例,提前初始化
  668. // self.bannerAd = window['wx'].createGridAd({
  669. // adUnitId: banID,
  670. // adTheme: 'white',
  671. // gridCount: 5,
  672. // style: {
  673. // left: 0,
  674. // top: 0,
  675. // width: 330,
  676. // opacity: 0.8
  677. // }
  678. // })
  679. // }
  680. // console.log('ccccc ')
  681. }
  682. let setHeight = false;
  683. if (self.bannerAd == null || self.bannerAd == undefined) {
  684. console.log("bannerAd is null");
  685. return;
  686. }
  687. self.bannerAd.onResize(res => {
  688. self.realtop = self.bannerAd.style.realHeight;
  689. if (phoneHeight > 1334) {
  690. self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5;
  691. self.bannerAd.style.top = phoneHeight - self.realtop - 30;
  692. self.bannerTop = 1060;
  693. } else {
  694. let tempH = self.bannerHeight * phoneHeight / 750;
  695. if (type == 0) {
  696. self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5 - 150;
  697. self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight;
  698. }
  699. else if (type == 1) {
  700. self.bannerAd.style.left = 0
  701. self.bannerAd.style.top = 0
  702. }
  703. else if (type == 2) {
  704. self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5;
  705. self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight;
  706. }
  707. else if (type == 3) {
  708. self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5;
  709. self.bannerAd.style.top = phoneHeight * 0.5 + disy;
  710. }
  711. else if (type == 4) {
  712. self.bannerAd.style.left = (phoneWidth - self.bannerAd.style.realWidth) * 0.5;
  713. self.bannerAd.style.top = phoneHeight - self.bannerAd.style.realHeight - disy;
  714. }
  715. self.bannerTop = self.bannerAd.style.top * 750 / phoneHeight - 60;
  716. //重设banner广告宽度
  717. if (!setHeight) {
  718. setHeight = true;
  719. let rate = self.realtop / tempH;
  720. if (type == 1) {
  721. rate = 2;
  722. }
  723. self.bannerAd.style.width = self.bannerAd.style.realWidth / rate;
  724. }
  725. }
  726. })
  727. self.bannerAd.onLoad(res => {
  728. self.bannerError = false;
  729. console.log("bannerAdLoad: ");
  730. WxMgr.getInstance().bannerDayTimes++
  731. // GameCore.setLocalData(GameCore.cache.localStorageKey.bannerDayTimes, WxMgr.getInstance().bannerDayTimes, 1)
  732. });
  733. self.bannerAd.onError(res => {
  734. console.log("加载banner错误:", res);
  735. self.bannerError = true;
  736. });
  737. self.bannerAd.show().catch((err) => {
  738. self.bannerError = true;
  739. console.log('显示banner错误:', err)
  740. });
  741. }
  742. checkBannerFresh() {
  743. if (WxMgr.getInstance().bannerDayTimes >= WxMgr.getInstance().bannerDayMax) {
  744. return false
  745. }
  746. else {
  747. return true
  748. }
  749. }
  750. /**隐藏广告 */
  751. showBannerAD() {
  752. if (this.bannerAd != null && this.bannerAd != undefined) {
  753. this.bannerAd.show();
  754. }
  755. }
  756. /**隐藏广告 */
  757. hideBannerAD() {
  758. if (this.bannerAd != null && this.bannerAd != undefined) {
  759. this.bannerAd.hide();
  760. }
  761. }
  762. /**
  763. * 销毁banner广告
  764. */
  765. destroyBannerAD() {
  766. if (WxMgr.getInstance().bannerCanRefresh || WxMgr.getInstance().checkBannerFresh()) {
  767. WxMgr.getInstance().bannerCanRefresh = false
  768. if (this.bannerAd != null && this.bannerAd != undefined) {
  769. this.bannerAd.destroy();
  770. this.bannerAd = null;
  771. }
  772. }
  773. else {
  774. WxMgr.getInstance().hideBannerAD()
  775. }
  776. }
  777. /** 复制
  778. * @param str 复制内容
  779. */
  780. clipboardData(str) {
  781. if (!window['wx']) {
  782. return
  783. }
  784. window['wx'].setClipboardData({
  785. data: str,
  786. success(res) {
  787. window['wx'].getClipboardData({
  788. success(res) {
  789. console.log(res.data) // data
  790. }
  791. })
  792. }
  793. })
  794. }
  795. }