WechatTool.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. import PlatUtils from "./PlatUtils";
  2. import { utils } from "./Utils";
  3. import YZ_Constant, { AttributedKey, AttributedType, AttributedValue, BannerLocationToEnum, LevelStatus } from "./YZ_Constant";
  4. import YZ_LocalStorage from "./YZ_LocalStorage";
  5. const { ccclass, property } = cc._decorator;
  6. const ST_ServerUrl: string = "https://apps.youlesp.com/gss?";
  7. /**
  8. * 游戏盒子的请求链接
  9. */
  10. const GB_ServerUrl: string = "https://apps.youlesp.com/gbs?";
  11. // 默认配置
  12. let ST_DefaultServerConfig: string = "";
  13. // 默认配置
  14. let GB_DefaultServerConfig: string = "";
  15. const ST_LoadConfigInterval: number = 5000; // 毫秒
  16. @ccclass
  17. export default class WechatTool {
  18. /**
  19. * 服务器配置信息
  20. */
  21. _serverConfig: any = null;
  22. public get ServerConfig() {
  23. return this._serverConfig;
  24. }
  25. /**
  26. * 游戏盒子配置信息
  27. */
  28. _gameBoxServerConfig: any = null;
  29. public get gameBoxServerConfig() {
  30. return this._gameBoxServerConfig;
  31. }
  32. //设备UID
  33. _uid: string = "0";
  34. public get uid() {
  35. if (this._uid != "0") return this._uid;
  36. this._login();
  37. return "0";
  38. }
  39. //服务器返回UID
  40. _service_uid: string = "0";
  41. /**
  42. * 服务器返回UID
  43. */
  44. public get serviceId() {
  45. if (this._service_uid != "0") return this._service_uid;
  46. this._login();
  47. return "0";
  48. }
  49. _sysInfo: any = null;
  50. public get SysInfo() {
  51. return this._sysInfo;
  52. }
  53. _shareCallback: Function = null;
  54. _isShare: boolean = false;
  55. _lastUpdateTime: number = 0;
  56. _appIdList: string[] = [];
  57. _jumpIds: string = "";
  58. //启动来源的场景:
  59. _luanchType: string = "";
  60. clue_token: string = "" //字节token
  61. wx_code: string = "" //登录后返回的code
  62. //来源APPID
  63. _source_app_id: string = "";
  64. //启动参数
  65. _luanchData: string = "";
  66. /**
  67. *
  68. * @param data 配置数据
  69. */
  70. public init(data: string) {
  71. if (PlatUtils.IsWechat) {
  72. //@ts-ignore
  73. try {
  74. //@ts-ignore
  75. this._sysInfo = wx.getSystemInfoSync()
  76. utils.showLog("微信小游戏平台信息: " + JSON.stringify(this.SysInfo));
  77. } catch (e) {
  78. // Do something when catch error
  79. }
  80. try {
  81. this._luanchData = YZ_LocalStorage.getItem(YZ_Constant.ST_LUANCH_DATA);
  82. this._luanchType = YZ_LocalStorage.getItem(YZ_Constant.ST_LUANCH_TYPE);
  83. //@ts-ignore
  84. let options = wx.getLaunchOptionsSync()
  85. options && utils.showLog(">>获取到小程序启动参数:" + JSON.stringify(options));
  86. if (this._luanchData && this._luanchType) {
  87. utils.showLog("获取到本地缓存数据启动类型:" + this._luanchType);
  88. utils.showLog("获取到本地缓存数据启动参数:" + this._luanchData);
  89. } else {
  90. if (options) {
  91. if (options.scene) {
  92. utils.showLog("获取到启动场景值:" + options.scene);
  93. this._luanchType = options.scene;
  94. YZ_LocalStorage.setItem(YZ_Constant.ST_LUANCH_TYPE, this._luanchType);
  95. }
  96. if (options.query) {
  97. let queryData = JSON.stringify(options.query);
  98. this._luanchData = queryData;
  99. YZ_LocalStorage.setItem(YZ_Constant.ST_LUANCH_DATA, this._luanchData);
  100. utils.showLog("获取到小程序启动参数:" + queryData);
  101. }
  102. if (options.referrerInfo && JSON.stringify(options.referrerInfo) != "{}") {
  103. utils.showLog("获取到小程序来源信息:" + JSON.stringify(options.referrerInfo));
  104. if (options.referrerInfo.appId) {
  105. utils.showLog("获取到小程序启动来源的appId:" + options.referrerInfo.appId);
  106. this._source_app_id = options.referrerInfo.appId;
  107. }
  108. }
  109. }
  110. }
  111. } catch (erro) {
  112. utils.showLog("获取到小程序启动参数异常");
  113. }
  114. if (data) {
  115. let configObj: any = JSON.parse(data);
  116. if (configObj && configObj.wechat) {
  117. ST_DefaultServerConfig = JSON.stringify(configObj.wechat);
  118. }
  119. if (configObj && configObj.gamebox) {
  120. GB_DefaultServerConfig = JSON.stringify(configObj.gamebox);
  121. }
  122. }
  123. // 拉取服务器配置
  124. // this.loadJumpIds().then(() => {
  125. // console.log("本地跳转ID加载成功!");
  126. // this._loadConfig();
  127. // }).catch((erro) => {
  128. // console.error("本地跳转ID加载失败:", erro);
  129. this._loadConfig();
  130. // })
  131. //加载配置的跳转ID
  132. // this.loadAppIdList();
  133. // 开启右上角转发
  134. //@ts-ignore
  135. wx.showShareMenu();
  136. //@ts-ignore
  137. wx.onShareAppMessage(this._getShareInfo.bind(this));
  138. //@ts-ignore
  139. wx.onShow((res) => {
  140. cc.log("OnShow");
  141. if (this._isShare) {
  142. this._isShare = false;
  143. if (this._shareCallback) {
  144. this._shareCallback(true, "分享成功!");
  145. }
  146. }
  147. this._checkForUpdate();
  148. utils.emitCommonEvent(YZ_Constant.EC_OnShow);
  149. });
  150. //@ts-ignore
  151. wx.onHide(() => {
  152. cc.log("onHide");
  153. utils.emitCommonEvent(YZ_Constant.EC_OnHide);
  154. });
  155. this._checkForUpdate();
  156. }
  157. }
  158. _checkForUpdate() {
  159. if (PlatUtils.IsWechat) {
  160. if ((new Date()).getTime() - this._lastUpdateTime < ST_LoadConfigInterval) {
  161. cc.log("检查更新太频繁!");
  162. return;
  163. }
  164. this._lastUpdateTime = (new Date()).getTime();
  165. if (this.isOverMinVersion("1.9.90")) {
  166. cc.log("检查更新......");
  167. //@ts-ignore
  168. const updateManager = wx.getUpdateManager();
  169. updateManager.onCheckForUpdate((res) => {
  170. // 请求完新版本信息的回调
  171. if (res.hasUpdate) {
  172. cc.log("有新版本需要更新!");
  173. } else {
  174. cc.log("没有新版本!");
  175. }
  176. });
  177. updateManager.onUpdateReady(() => {
  178. //@ts-ignore
  179. wx.showModal({
  180. title: '更新提示',
  181. content: '新版本已经准备好,是否重启应用?',
  182. success(res) {
  183. if (res.confirm) {
  184. // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
  185. updateManager.applyUpdate();
  186. }
  187. }
  188. });
  189. });
  190. updateManager.onUpdateFailed(() => {
  191. // 新版本下载失败
  192. cc.log("新版本下载失败!");
  193. });
  194. }
  195. }
  196. }
  197. _buildServerUrl() {
  198. let url: string = "";
  199. if (utils.config.wechatconfig && utils.config.wechatconfig.appID) {
  200. let appid: string = utils.config.wechatconfig.appID;
  201. let channel: string = "wechat";
  202. let jumpId: string = this._jumpIds ? this._jumpIds : utils.config.wechatconfig.jumpId;
  203. url = ST_ServerUrl + `kyx=true&app_id=${appid}&channel=${channel}&jump_id=${jumpId}`;
  204. } else {
  205. cc.log("微信 APPID配置出错!");
  206. }
  207. return url;
  208. }
  209. _buildGameBoxServerUrl() {
  210. let url: string = GB_ServerUrl + `m=ghome&index=0&type=1`;
  211. return url;
  212. }
  213. _loadConfig() {
  214. if (PlatUtils.IsWechat) {
  215. cc.log("加载服务器配置.......");
  216. let method: string = "m=g";
  217. let url: string = ST_ServerUrl + method
  218. // let jumpId: string = this._jumpIds ? this._jumpIds : utils.config.wechatconfig.jumpId;
  219. // url += `&jump_id=${jumpId}`
  220. utils.commomHttpRequest(url, (ret, data) => {
  221. if (ret) {
  222. cc.log("微信服务器配置数据获取成功: data = ", data);
  223. if (data) {
  224. let result = JSON.parse(data);
  225. if (result) {
  226. if (!utils.DebugLoacalConfig) {
  227. this._serverConfig = result;
  228. } else {
  229. cc.warn("开启了本地数据测试,使用本地配置!");
  230. }
  231. } else {
  232. cc.log("微信服务器配置数据不是合法的JSON数据, 使用本地配置!");
  233. }
  234. }
  235. } else {
  236. cc.log("微信服务器配置数据获取失败, 使用本地配置!");
  237. }
  238. if (!this._serverConfig) {
  239. this._serverConfig = JSON.parse(ST_DefaultServerConfig);
  240. } else {
  241. if (this._serverConfig.shares && this._serverConfig.shares.sy_title) {
  242. utils.config.otherconfig.shareTitle = this._serverConfig.shares.sy_title;
  243. }
  244. if (this._serverConfig.shares && this._serverConfig.shares.sy_img) {
  245. utils.config.otherconfig.shareImgUrl = this._serverConfig.shares.sy_img;
  246. }
  247. if (this._serverConfig.is_local_pos_id == "false") {
  248. // 使用服务器下发的广告id
  249. cc.log("使用服务器下发的广告ID");
  250. utils.config.wechatconfig.insertId = this.ServerConfig.intersititia_pos_id || utils.config.wechatconfig.insertId;
  251. utils.config.wechatconfig.videoId = this.ServerConfig.video_pos_id || utils.config.wechatconfig.videoId;
  252. utils.config.wechatconfig.boxId = this._serverConfig.box_pos_id || utils.config.wechatconfig.boxId;
  253. utils.config.wechatconfig.bannerBoxId = this._serverConfig.banner_box_pos_id || utils.config.wechatconfig.bannerBoxId;
  254. utils.config.wechatconfig.nativeBannerId = this._serverConfig.native_banner_pos_id || utils.config.wechatconfig.nativeBannerId;
  255. utils.config.wechatconfig.nativeInsertIds = this._serverConfig.native_intersititial_pos_id || utils.config.wechatconfig.nativeInsertIds;
  256. let bannerLocation: string[] = ["home", "game", "level", "skin", "pause", "over"];
  257. for (let i = 0; i < bannerLocation.length; i++) {
  258. if (this.ServerConfig.banner_pos_id[bannerLocation[i]]) {
  259. utils.config.wechatconfig.setBannerId(BannerLocationToEnum(bannerLocation[i]), this.ServerConfig.banner_pos_id[bannerLocation[i]]);
  260. }
  261. }
  262. if (this.ServerConfig.native_customad_configs) {
  263. for (let i = 0; i < this.ServerConfig.native_customad_configs.length; i++) {
  264. utils.showLog("获取到原生模版广告配置:" + this.ServerConfig.native_customad_configs[i].location, ">>>>", JSON.stringify(this.ServerConfig.native_customad_configs[i]));
  265. utils.config.wechatconfig.setCustomAdInfo(this.ServerConfig.native_customad_configs[i].location, this.ServerConfig.native_customad_configs[i]);
  266. }
  267. }
  268. } else {
  269. cc.log("使用本地配置的广告ID");
  270. }
  271. }
  272. utils.emitServerInitEvent();
  273. if (this._serverConfig && this._serverConfig.openBox) {
  274. if (this._serverConfig.openBox != "true") {
  275. cc.log("服务器游戏盒子配置为关闭状态!");
  276. return;
  277. }
  278. url = this._buildGameBoxServerUrl();
  279. utils.commomHttpRequest(url, (ret, data) => {
  280. if (ret) {
  281. cc.log("微信游戏盒子服务器配置数据获取成功: data = ", data);
  282. if (data) {
  283. let result = JSON.parse(data);
  284. if (result) {
  285. if (!utils.DebugLoacalConfig) {
  286. this._gameBoxServerConfig = result;
  287. } else {
  288. cc.warn("开启了本地数据测试,使用本地配置!");
  289. }
  290. } else {
  291. cc.log("微信游戏盒子微信服务器配置数据不是合法的JSON数据, 使用本地配置!");
  292. }
  293. }
  294. } else {
  295. cc.log("微信游戏盒子服务器配置数据获取失败, 使用本地配置!");
  296. }
  297. if (!this._gameBoxServerConfig) {
  298. this._gameBoxServerConfig = JSON.parse(GB_DefaultServerConfig);
  299. }
  300. });
  301. }
  302. });
  303. }
  304. }
  305. /**
  306. *
  307. * @param id 跳转ID
  308. * @param callback 跳转回调
  309. */
  310. public navigateToMiniProgram(id: string, callback: Function, path?: string) {
  311. if (PlatUtils.IsWechat) {
  312. let completeCallback: Function = callback;
  313. //@ts-ignore
  314. wx.navigateToMiniProgram({
  315. appId: id.indexOf(":") > -1 ? id.split(":")[0] : id,
  316. path: path ? path : "",
  317. success(res) {
  318. if (completeCallback) {
  319. completeCallback(true);
  320. }
  321. },
  322. fail(res) {
  323. // cc.log("跳转失败!", id);
  324. cc.log(`跳转失败! id=${id}; res=${JSON.stringify(res)}`);
  325. if (completeCallback) {
  326. completeCallback(false);
  327. }
  328. }
  329. });
  330. }
  331. }
  332. public getSystemInfo() {
  333. if (PlatUtils.IsWechat) {
  334. //@ts-ignore
  335. return wx.getSystemInfoSync();
  336. }
  337. }
  338. public previewImage(url: string) {
  339. if (PlatUtils.IsWechat) {
  340. //@ts-ignore
  341. wx.previewImage({
  342. urls: [url] // 需要预览的图片http链接列表
  343. });
  344. }
  345. }
  346. public share(callback: Function = null) {
  347. if (PlatUtils.IsWechat) {
  348. this._shareCallback = callback;
  349. this._isShare = true;
  350. //@ts-ignore
  351. wx.shareAppMessage(this._getShareInfo());
  352. }
  353. }
  354. /**
  355. * 上报数据
  356. */
  357. public postData(otherGameAppId: string) {
  358. if (PlatUtils.IsWechat) {
  359. let method = "m=rjump";
  360. let url: string = ST_ServerUrl + method + `&jump_app_id=${otherGameAppId}`;
  361. cc.log("上报数据, url=", url);
  362. utils.commomHttpRequest(url, function (ret, data) {
  363. if (ret) {
  364. cc.log("数据上报成功!");
  365. } else {
  366. cc.log("数据上报失败!");
  367. }
  368. });
  369. }
  370. }
  371. /**
  372. * 上报互推组件数据
  373. * @param otherGameAppId 跳转的ID
  374. * @param location 当前位置
  375. * @param status 0:点击,1:跳转成功
  376. */
  377. public postDataByLocation(otherGameAppId: string, location: string, status: number = 0) {
  378. if (PlatUtils.IsWechat) {
  379. let method = "m=rjump";
  380. let url: string = ST_ServerUrl + method + `&jump_app_id=${otherGameAppId}&location=${location}&status=${status}`
  381. utils.commomHttpRequest(url, function (ret, data) {
  382. if (ret) {
  383. cc.log("数据上报成功!");
  384. } else {
  385. cc.log("数据上报失败!");
  386. }
  387. });
  388. }
  389. }
  390. /**
  391. * 上报互推组件显示位置
  392. * @param otherGameAppId 跳转的ID
  393. * @param location 当前位置
  394. * @param status 0:点击,1:跳转成功
  395. */
  396. public postRecommentShowData(location: string) {
  397. if (PlatUtils.IsWechat) {
  398. let method = "m=rjumpshow";
  399. let url: string = ST_ServerUrl + method + `&location=${location}`;
  400. utils.commomHttpRequest(url, function (ret, data) {
  401. if (ret) {
  402. cc.log("数据上报成功!");
  403. } else {
  404. cc.log("数据上报失败!");
  405. }
  406. }.bind(this));
  407. }
  408. }
  409. _getShareInfo() {
  410. if (PlatUtils.IsWechat) {
  411. return {
  412. title: utils.config.otherconfig.shareTitle,
  413. imageUrl: utils.config.otherconfig.shareImgUrl
  414. };
  415. }
  416. return {};
  417. }
  418. public isOverMinVersion(minVersion: string) {
  419. //@ts-ignore
  420. let curVersion: string = wx.getSystemInfoSync().SDKVersion;
  421. return this._compareVersion(curVersion, minVersion) >= 0
  422. }
  423. _compareVersion(v1, v2) {
  424. v1 = v1.split('.')
  425. v2 = v2.split('.')
  426. const len = Math.max(v1.length, v2.length)
  427. while (v1.length < len) {
  428. v1.push('0')
  429. }
  430. while (v2.length < len) {
  431. v2.push('0')
  432. }
  433. for (let i = 0; i < len; i++) {
  434. const num1 = parseInt(v1[i])
  435. const num2 = parseInt(v2[i])
  436. if (num1 > num2) {
  437. return 1
  438. } else if (num1 < num2) {
  439. return -1
  440. }
  441. }
  442. return 0
  443. }
  444. /**
  445. * 获取交叉推广数据
  446. */
  447. public getRecommondGameList() {
  448. if (PlatUtils.IsWechat && utils.wechatTool && utils.wechatTool.ServerConfig) {
  449. return utils.wechatTool.ServerConfig.jump_list;
  450. }
  451. return null;
  452. }
  453. // /**
  454. // * 加载游戏配置的跳转ID
  455. // */
  456. // loadAppIdList() {
  457. // CompatibleTool.LoadResRes("./src/game.json", (err, res) => {
  458. // if (err) {
  459. // cc.error('加载game.json文件出错', err);
  460. // return;
  461. // }
  462. // if (res && res.navigateToMiniProgramAppIdList && res.navigateToMiniProgramAppIdList.length) {
  463. // let taskQty = res.subpackages.length;
  464. // for (let i = 0; i < taskQty; i++) {
  465. // this._appIdList.push(res.navigateToMiniProgramAppIdList[i].name);
  466. // }
  467. // cc.log("配置的跳转ID:", this._appIdList);
  468. // }
  469. // });
  470. // }
  471. /**
  472. * 验证ID 是否配置
  473. * @param appId 应用ID
  474. */
  475. checkAppId(appId: string) {
  476. if (utils.config.wechatconfig.jumpId.indexOf(appId) > -1) {
  477. return true;
  478. }
  479. cc.log("appId :", appId, "不再配置列表中!");
  480. return false;
  481. }
  482. _loginTime: number = 0;
  483. _loginInterval: number = 30;
  484. _login() {
  485. let curTime: number = new Date().getTime();
  486. let interval: number = (curTime - this._loginTime) / 1000;
  487. if (interval > 0 && interval < this._loginInterval) {
  488. utils.showLog(`登录请求间隔小于:${this._loginInterval}秒`);
  489. return;
  490. }
  491. this._loginTime = curTime;
  492. let self = this;
  493. this._uid = YZ_LocalStorage.getItem(YZ_Constant.ST_UID);
  494. this._uid = this._uid ? this._uid : "0";
  495. this._service_uid = YZ_LocalStorage.getItem(YZ_Constant.ST_SERVICE_UID);
  496. this._service_uid = this._service_uid ? this._service_uid : "0";
  497. utils.showLog("获取本地保存的uid=" + this._uid + ",服务器UID=" + this._service_uid);
  498. if (this._uid == "0") {
  499. //@ts-ignore
  500. wx.login({
  501. success(res) {
  502. if (res.code) {
  503. self.wx_code = res.code;
  504. self.reportLogin(res.code);
  505. } else {
  506. utils.showLog('登录失败!' + res.errMsg)
  507. }
  508. },
  509. fail() {
  510. },
  511. complete() {
  512. self.reportLogin();
  513. }
  514. })
  515. }
  516. }
  517. _reportLoginTime: number = 0;
  518. _reportLoginInterval: number = 30;
  519. isReport: boolean = false;
  520. isReportActive: boolean = false;
  521. /**
  522. * 上报登录接口获取UID
  523. */
  524. async reportLogin(code: string = "") {
  525. if (this.isReport) return;
  526. this.isReport = true;
  527. let self = this;
  528. let curTime: number = new Date().getTime();
  529. let interval: number = (curTime - this._reportLoginTime) / 1000;
  530. if (interval > 0 && interval < this._reportLoginInterval) {
  531. utils.showLog(`上报登录获取UID小于:${this._reportLoginInterval}秒`);
  532. return;
  533. }
  534. this._reportLoginTime = curTime;
  535. let method = "m=login";
  536. let url: string = ST_ServerUrl + method + `&device_data=${encodeURI(JSON.stringify(this._sysInfo))}&code=${code}`;
  537. utils.commomHttpRequest(url, (ret, data) => {
  538. if (ret) {
  539. if (data) {
  540. utils.showLog("#data=" + data);
  541. let result = JSON.parse(data);
  542. if (result.uid) {
  543. self._service_uid = "" + result.uid;
  544. if (!self.isReportActive) {
  545. self.isReportActive = true;
  546. this.reportAttributedEvent(AttributedType.Active, AttributedKey.Active, AttributedValue.Active);
  547. }
  548. YZ_LocalStorage.setItem(YZ_Constant.ST_SERVICE_UID, self._service_uid);
  549. }
  550. if (result.device_uid) {
  551. self._uid = "" + result.device_uid;
  552. YZ_LocalStorage.setItem(YZ_Constant.ST_UID, self._uid);
  553. }
  554. utils.showLog("服务器请求登录成功! _service_uid=" + self._service_uid + " #device_id=" + self._uid);
  555. }
  556. }
  557. this.isReport = false;
  558. })
  559. }
  560. passCount: number = 0; //通关数据
  561. playCount: number = 0; //开始关卡数据
  562. /**
  563. * 上报关卡数据
  564. * @param level 当前关卡ID
  565. * @param levelName 关卡名称
  566. * @param status 状态
  567. */
  568. public postLevel(level: string, status: LevelStatus, levelName?: string) {
  569. if (PlatUtils.IsWechat) {
  570. if (status == LevelStatus.GameWin) {
  571. this.passCount++;
  572. if (this.passCount === utils.getConfigByKey("pass_level_count_active")) {
  573. this.reportAttributedEvent(AttributedType.GameAddiction, AttributedKey.GameAddiction, AttributedValue.PassLevelCountAction);
  574. }
  575. } else if (status === LevelStatus.GameStart) {
  576. this.playCount++;
  577. if (this.playCount == utils.getConfigByKey("play_level_count_active")) {
  578. this.reportAttributedEvent(AttributedType.GameAddiction, AttributedKey.GameAddiction, AttributedValue.PlayLevelCountAction);
  579. }
  580. }
  581. let method = "m=rlevel";
  582. let url: string = ST_ServerUrl + method + `&level_id=${level}&level_name=${encodeURI(levelName)}&status=${status}`;
  583. utils.commomHttpRequest(url, function (ret, data) {
  584. if (ret) {
  585. utils.showLog("关卡数据上报成功!");
  586. } else {
  587. utils.showLog("关卡数据上报失败!");
  588. }
  589. }.bind(this));
  590. }
  591. }
  592. /**
  593. * 上报自定义事件
  594. * @param level 当前关卡ID
  595. * @param levelName 关卡名称
  596. * @param status 状态
  597. */
  598. public sendEvent(eventName: string) {
  599. if (PlatUtils.IsWechat) {
  600. let method = "m=revent";
  601. let url: string = ST_ServerUrl + method + `&event=${encodeURI(eventName)}`;
  602. utils.commomHttpRequest(url, function (ret, data) {
  603. if (ret) {
  604. utils.showLog("上报自定义事件成功!");
  605. } else {
  606. utils.showLog("上报自定义事件失败!");
  607. }
  608. }.bind(this));
  609. }
  610. }
  611. /**
  612. * 弹出提示框
  613. * @param msg 消息
  614. */
  615. public showToast(msg: string) {
  616. if (PlatUtils.IsWechat) {
  617. //@ts-ignore
  618. wx.showToast({
  619. title: msg,
  620. icon: "none",
  621. duration: 2000,
  622. success(res) {
  623. console.log(`${res}`);
  624. },
  625. fail(res) {
  626. console.log(`showToast调用失败`);
  627. }
  628. });
  629. }
  630. }
  631. /**
  632. * 上报归因事件
  633. * @param eventType 事件类型 0 激活, 25:关键行为
  634. * @param eventValue 事件描述
  635. */
  636. public reportAttributedEvent(eventType: AttributedType, eventKey: AttributedKey, eventValue: AttributedValue) {
  637. if (this._luanchType != "1069" && this._luanchType != "1036" && this._luanchType != "1065") {
  638. utils.showLog("luanchType=" + this._luanchType + ",不进行归因上报");
  639. return;
  640. }
  641. utils.showLog("上报归因事件: #eventType=" + eventType + "#eventKey=" + eventKey + "#eventValue=" + eventValue);
  642. if (eventType == AttributedType.Active && YZ_LocalStorage.getItem(YZ_Constant.ST_IS_REPORT_USER_ACTIVE)) {
  643. utils.showLog("用户已经上报过激活,不再进行激活上报!");
  644. return;
  645. } else if (eventType == AttributedType.GameAddiction && YZ_LocalStorage.getItem(YZ_Constant.ST_IS_REPORT_GAME_ADDICTION)) {
  646. utils.showLog("用户已经上报过关键行为,不再进行激活上报!");
  647. return;
  648. }
  649. let xhr = new XMLHttpRequest();
  650. xhr.timeout = 15000; // 单位毫秒
  651. let data: any = {};
  652. data.app_id = utils.config.wechatconfig.appID;
  653. data.channel = "wechat_kyx";
  654. data.uid = this._service_uid;
  655. data.event_type = eventType;
  656. data.event_key = eventKey;
  657. data.event_value = eventValue;
  658. data.app_version = utils.config.wechatconfig.version;
  659. data.code = this.wx_code;
  660. // data.clue_token = this.clue_token;
  661. data.luanchDate = encodeURI(this._luanchData);
  662. utils.showLog("归因请求参数:" + JSON.stringify(data));
  663. let requestData = JSON.stringify(data);
  664. utils.showLog("归因 > json_data=" + utils.aesEncrypt(requestData));
  665. let requestUrl: string = `https://track.youletd.com/wechatcounterpart/dockingreturn?json=${utils.aesEncrypt(requestData)}&time_stamp=${(new Date()).getTime()}`;
  666. utils.showLog("归因服务器地址:" + requestUrl);
  667. xhr.open('GET', requestUrl);
  668. xhr.send();
  669. xhr.onreadystatechange = function () {
  670. utils.showLog("请求状态改变, reaedyState=", xhr.readyState, "; status=", xhr.status);
  671. if (xhr.readyState == 4) {
  672. if (xhr.status == 200) {
  673. if (eventType == AttributedType.Active) YZ_LocalStorage.setItem(YZ_Constant.ST_IS_REPORT_USER_ACTIVE, "true");
  674. if (eventType == AttributedType.GameAddiction) YZ_LocalStorage.setItem(YZ_Constant.ST_IS_REPORT_GAME_ADDICTION, "true");
  675. utils.showLog("归因上报成功:", xhr.responseText);
  676. } else {
  677. utils.showLog("归因上报失败!");
  678. }
  679. }
  680. }
  681. xhr.ontimeout = function () {
  682. utils.showLog("归因请求超时!");
  683. }
  684. xhr.onerror = function (err) {
  685. utils.showLog("归因请求失败!");
  686. }
  687. }
  688. /**
  689. * 友盟游戏开始上报
  690. * @param levelID
  691. */
  692. public umaOnStart(levelID: string) {
  693. if (!this.checkUmeng()) return;
  694. //@ts-ignore
  695. wx.uma.stage.onStart({
  696. stageId: levelID,//该字段名称不可修改,必传
  697. stageName: `第${levelID}关`// 关卡id
  698. })
  699. }
  700. /**
  701. *
  702. * @returns 是否开启友盟
  703. */
  704. private checkUmeng(): boolean {
  705. //@ts-ignore
  706. if (!wx.uma) {
  707. utils.showLog("未对接友盟SDK");
  708. return false;
  709. }
  710. return true;
  711. }
  712. /**
  713. * 友盟结算上报
  714. * @param levelID 关卡id
  715. * @param stageId
  716. * @param event
  717. */
  718. public umaReportedLevel(levelID: string, event: LevelStatus) {
  719. if (!this.checkUmeng()) return;
  720. //@ts-ignore
  721. wx.uma.stage.onEnd({
  722. stageId: levelID,//该字段名称不可修改,必传
  723. stageName: `第${levelID}关`,
  724. event: event
  725. })
  726. }
  727. /**
  728. * 友盟自定义事件
  729. * @param eventId 事件ID,注意:事件ID必须要在后台配置
  730. * @param params 事件内容
  731. */
  732. public umaTrackEvent(eventId: string, params?) {
  733. if (!this.checkUmeng()) return;
  734. //@ts-ignore
  735. wx.uma.trackEvent(eventId, params);
  736. }
  737. }