YZ_Tool_QQ.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. import PlatUtils from "./PlatUtils";
  2. import { utils } from "./Utils";
  3. import YZ_Constant, { 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. const POST_ServerUrl: string = "https://report.youletd.com/gss?";
  8. // 默认配置
  9. let ST_DefaultServerConfig: string = "";
  10. @ccclass
  11. export default class YZ_Tool_QQ {
  12. /**
  13. * 服务器配置信息
  14. */
  15. _serverConfig: any = null;
  16. public get ServerConfig() {
  17. return this._serverConfig;
  18. }
  19. _sysInfo: any = {};
  20. public get SysInfo() {
  21. return this._sysInfo;
  22. }
  23. // 桌面图标是否创建
  24. _shortcutCreated: boolean = false;
  25. public get ShortcutCreated() {
  26. return this._shortcutCreated;
  27. }
  28. _shareCallback: Function = null;
  29. _isShare: boolean = false;
  30. //设备UID
  31. _uid: string = "0";
  32. /**
  33. * 当前版本号
  34. */
  35. public gameVersion(): string {
  36. return utils.config.qqconfig.version;
  37. }
  38. public get uid() {
  39. // if (this._service_uid != "0") return this._uid;
  40. // this._login();
  41. return "0";
  42. }
  43. //服务器返回UID
  44. _service_uid: string = "0";
  45. /**
  46. * 服务器返回UID
  47. */
  48. public get serviceId() {
  49. if (this._service_uid != "0") return this._service_uid;
  50. this.reportLogin();
  51. return "0";
  52. }
  53. _loginTime: number = 0;
  54. _loginInterval: number = 30;
  55. async _login() {
  56. let curTime: number = new Date().getTime();
  57. let interval: number = (curTime - this._loginTime) / 1000;
  58. if (interval > 0 && interval < 30) {
  59. utils.showLog(`登录请求间隔小于:${this._loginInterval}秒`);
  60. return;
  61. }
  62. this._loginTime = curTime;
  63. let self = this;
  64. utils.showLog("qq暂时不获取uid,uid全部为0");
  65. this._uid = "0";
  66. // this.reportLogin();
  67. }
  68. _reportLoginTime: number = 0;
  69. _reportLoginInterval: number = 30;
  70. isReport: boolean = false;
  71. /**
  72. * 上报登录接口获取UID
  73. */
  74. reportLogin() {
  75. if (this.isReport) return;
  76. this.isReport = true;
  77. let self = this;
  78. let curTime: number = new Date().getTime();
  79. let interval: number = (curTime - self._reportLoginTime) / 1000;
  80. // utils.showLog(interval, " <<<<<<,interval", " _reportLoginTime >>>", self._reportLoginTime);
  81. // console.log(curTime, curTime - self._reportLoginTime, interval)
  82. if (interval > 0 && interval < 30) {
  83. utils.showLog(`上报登录获取UID小于:${self._reportLoginInterval}秒`);
  84. return;
  85. }
  86. self._reportLoginTime = curTime;
  87. let method = "m=login";
  88. let url: string = ST_ServerUrl + method + `&device_data=0`;
  89. utils.commomHttpRequest(url, (ret, data) => {
  90. if (ret) {
  91. if (data) {
  92. let result = JSON.parse(data);
  93. utils.showLog("data=" + data);
  94. utils.showLog("result=" + result);
  95. utils.showLog("result.uid=" + result.uid);
  96. if (result.uid) {
  97. self._service_uid = "" + result.uid;
  98. console.log("self._service_uid:" + self._service_uid)
  99. utils.showLog("服务器请求登录成功! _service_uid=" + self._service_uid);
  100. YZ_LocalStorage.setItem(YZ_Constant.ST_SERVICE_UID, self._service_uid);
  101. }
  102. }
  103. } else {
  104. utils.showLog("获取数据失败1");
  105. }
  106. this.isReport = false;
  107. })
  108. }
  109. /**
  110. *
  111. * @param data 配置数据
  112. */
  113. public init(data: string) {
  114. if (PlatUtils.IsQQ) {
  115. if (data) {
  116. let configObj: any = JSON.parse(data);
  117. if (configObj && configObj.qq) {
  118. ST_DefaultServerConfig = JSON.stringify(configObj.qq);
  119. }
  120. }
  121. this._service_uid = YZ_LocalStorage.getItem(YZ_Constant.ST_SERVICE_UID);
  122. this._service_uid = this._service_uid ? this._service_uid : "0";
  123. try {
  124. //@ts-ignore
  125. this._sysInfo = qq.getSystemInfoSync()
  126. utils.showLog("QQ 小游戏平台信息: ", JSON.stringify(this.SysInfo));
  127. } catch (e) {
  128. utils.showLog("QQ 小游戏平台数据获取失败!");
  129. }
  130. this._loadConfig();
  131. // 开启右上角转发
  132. //@ts-ignore
  133. qq.showShareMenu();
  134. //@ts-ignore
  135. qq.onShareAppMessage(this._getShareInfo.bind(this));
  136. //@ts-ignore
  137. qq.onShow((res) => {
  138. utils.showLog("OnShow: ", res);
  139. if (this._isShare) {
  140. this._isShare = false;
  141. if (this._shareCallback) {
  142. this._shareCallback(true, "分享成功!");
  143. }
  144. }
  145. });
  146. utils.registerServerInitEvent(() => {
  147. if (this.canCreateShortcut()) {
  148. if (utils.ServerConfig && utils.ServerConfig.start_auto_create_short_cut_time) {
  149. utils.SendEvent("组件初始化成功,弹出自动创建桌面!");
  150. utils.showLog(`组件初始化成功,${utils.ServerConfig.start_auto_create_short_cut_time}秒后弹出自动创建桌面!`)
  151. setTimeout(() => {
  152. this.createShortcut((res) => {
  153. if (res) {
  154. utils.showLog("自动创建桌面成功!");
  155. } else {
  156. utils.showLog("自动创建桌面失败!");
  157. }
  158. });
  159. }, utils.ServerConfig.start_auto_create_short_cut_time * 1000);
  160. }
  161. }
  162. if (utils.ServerConfig && utils.ServerConfig.auto_add_favorites && utils.ServerConfig.auto_add_favorites == "true") {
  163. utils.showLog('自动添加到搜藏');
  164. this.addFavorites();
  165. }
  166. utils.showLog('组件初始化完成,验证是否登陆!', utils.ServerConfig.add_recent_color_sign);
  167. if (utils.ServerConfig && utils.ServerConfig.add_recent_color_sign) {
  168. if (utils.ServerConfig.add_recent_color_sign == 1) {
  169. this.addColorSign();
  170. } else {
  171. //@ts-ignore
  172. qq.checkSession({
  173. success: () => {
  174. utils.showLog("session_key 未过期,并且在本生命周期一直有效");
  175. this.addRecentColorSign();
  176. // session_key 未过期,并且在本生命周期一直有效
  177. },
  178. fail: () => {
  179. // session_key 已经失效,需要重新执行登录流程
  180. //@ts-ignore
  181. qq.login({
  182. success: (res) => {
  183. if (res.code) {
  184. utils.showLog('登录成功!');
  185. this.addRecentColorSign();
  186. } else {
  187. utils.showLog('登录失败!' + res.errMsg)
  188. }
  189. }
  190. })
  191. }
  192. })
  193. }
  194. }
  195. }, this);
  196. }
  197. }
  198. /**
  199. * 添加到彩签
  200. */
  201. addRecentColorSign() {
  202. utils.showLog("调用添加彩签>>>>>>>");
  203. //@ts-ignore
  204. qq.addRecentColorSign({
  205. query: 'a=1&b=2',
  206. success(res) {
  207. utils.showLog('addRecentColorSign success: ', res);
  208. },
  209. fail(err) {
  210. utils.showLog('addRecentColorSign fail: ', err);
  211. },
  212. complete(res) {
  213. utils.showLog('addRecentColorSign complete: ', res);
  214. }
  215. })
  216. }
  217. _loadConfig() {
  218. if (PlatUtils.IsQQ) {
  219. let method: string = "m=g";
  220. utils.commomHttpRequest(ST_ServerUrl + method, (ret, data) => {
  221. if (ret) {
  222. utils.showLog("QQ服务器配置数据获取成功: 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. utils.showLog("QQ服务器配置数据不是合法的JSON数据, 使用本地配置!");
  233. }
  234. }
  235. } else {
  236. utils.showLog("QQ服务器配置数据获取失败, 使用本地配置!");
  237. }
  238. if (!this._serverConfig) {
  239. this._serverConfig = JSON.parse(ST_DefaultServerConfig);
  240. } else {
  241. if (this._serverConfig.shares) {
  242. if (this._serverConfig.shares.sy_title) {
  243. utils.config.otherconfig.shareTitle = this._serverConfig.shares.sy_title;
  244. }
  245. if (this._serverConfig.shares.sy_img) {
  246. utils.config.otherconfig.shareImgUrl = this._serverConfig.shares.sy_img;
  247. }
  248. }
  249. if (this._serverConfig.is_local_pos_id
  250. && this._serverConfig.is_local_pos_id == "false") {
  251. // 使用服务器下发的广告id
  252. utils.showLog("使用服务器下发的广告id");
  253. utils.config.qqconfig.bannerId = this._serverConfig.banner_pos_id;
  254. utils.config.qqconfig.insertId = this._serverConfig.intersititia_pos_id;
  255. utils.config.qqconfig.videoId = this._serverConfig.video_pos_id;
  256. utils.config.qqconfig.boxId = this._serverConfig.box_pos_id;
  257. utils.config.qqconfig.bannerBoxId = this._serverConfig.banner_box_pos_id;
  258. } else {
  259. utils.showLog("使用本地配置的广告ID");
  260. }
  261. }
  262. utils.emitServerInitEvent();
  263. });
  264. }
  265. }
  266. public getSystemInfo() {
  267. if (PlatUtils.IsQQ) {
  268. return this._sysInfo;
  269. }
  270. }
  271. public share(callback: Function = null) {
  272. if (PlatUtils.IsQQ) {
  273. this._shareCallback = callback;
  274. this._isShare = true;
  275. //@ts-ignore
  276. qq.shareAppMessage(this._getShareInfo());
  277. }
  278. }
  279. /**
  280. * 上报数据
  281. */
  282. public postData(otherGameAppId: string) {
  283. if (PlatUtils.IsQQ) {
  284. let appid: string = utils.config.qqconfig.appID;
  285. let uid: string = "0";
  286. let channel: string = "qq";
  287. let url: string = `https://apps.youlesp.com/gs?m=jump&app_id=${appid}&uid=${uid}&channel=${channel}&jump_app_id=${otherGameAppId}`;
  288. utils.showLog("上报数据, url=", url);
  289. utils.commomHttpRequest(url, function (ret, data) {
  290. if (ret) {
  291. utils.showLog("数据上报成功!");
  292. } else {
  293. utils.showLog("数据上报失败!");
  294. }
  295. });
  296. }
  297. }
  298. _getShareInfo() {
  299. if (PlatUtils.IsQQ) {
  300. return {
  301. title: utils.config.otherconfig.shareTitle,
  302. imageUrl: utils.config.otherconfig.shareImgUrl
  303. };
  304. }
  305. return {};
  306. }
  307. public isOverMinVersion(minVersion: string) {
  308. let curVersion: string = this._sysInfo.SDKVersion;
  309. return this._compareVersion(curVersion, minVersion) >= 0;
  310. }
  311. _compareVersion(v1, v2) {
  312. if (!v1 || !v2) return -1;
  313. v1 = v1.split('.')
  314. v2 = v2.split('.')
  315. const len = Math.max(v1.length, v2.length)
  316. while (v1.length < len) {
  317. v1.push('0')
  318. }
  319. while (v2.length < len) {
  320. v2.push('0')
  321. }
  322. for (let i = 0; i < len; i++) {
  323. const num1 = parseInt(v1[i])
  324. const num2 = parseInt(v2[i])
  325. if (num1 > num2) {
  326. return 1
  327. } else if (num1 < num2) {
  328. return -1
  329. }
  330. }
  331. return 0
  332. }
  333. /**
  334. * 上报关卡数据
  335. * @param level 当前关卡ID
  336. * @param levelName 关卡名称
  337. * @param status 状态
  338. */
  339. public postLevel(level: string, status: LevelStatus, levelName?: string) {
  340. if (PlatUtils.IsQQ) {
  341. if (status == LevelStatus.GameWin) {
  342. if (this.ServerConfig.rankey) {
  343. //排行帮提交数据
  344. let postKey = this.ServerConfig.rankey ? this.ServerConfig.rankey : "ranklevel";
  345. let postValue = level;
  346. //@ts-ignore
  347. qq.setUserCloudStorage(
  348. {
  349. KVDataList: [
  350. { key: postKey, value: postValue }
  351. ],
  352. success: function (res) {
  353. utils.showLog('关卡记录成功');
  354. },
  355. fail: function (res) {
  356. utils.showLog('关卡记录失败');
  357. },
  358. complete: function (res) {
  359. utils.showLog('关卡记录调用完成');
  360. },
  361. })
  362. }
  363. let interval = this.ServerConfig.subscribe_interval;
  364. if (interval) {
  365. try {
  366. if (parseInt(level) % interval == 0) {
  367. // 长期订阅
  368. //@ts-ignore
  369. qq.subscribeAppMsg({
  370. subscribe: true,
  371. success(res) {
  372. utils.showLog("----添加订阅消息----成功", res);
  373. },
  374. fail(res) {
  375. utils.showLog("----添加订阅消息----失败", res);
  376. }
  377. });
  378. }
  379. } catch (error) {
  380. utils.showLog("----添加订阅消息----异常");
  381. }
  382. }
  383. }
  384. let method = "m=rlevel";
  385. let url: string = POST_ServerUrl + method + `&level_id=${level}&level_name=${encodeURI(levelName)}&status=${status}`;
  386. utils.commomHttpRequest(url, function (ret, data) {
  387. if (ret) {
  388. utils.showLog("关卡数据上报成功!");
  389. } else {
  390. utils.showLog("关卡数据上报失败!");
  391. }
  392. }.bind(this));
  393. }
  394. }
  395. /**
  396. * 上报自定义事件
  397. * @param level 当前关卡ID
  398. * @param levelName 关卡名称
  399. * @param status 状态
  400. */
  401. public sendEvent(eventName: string) {
  402. if (PlatUtils.IsQQ) {
  403. let method = "m=revent";
  404. let url: string = POST_ServerUrl + method + `&event=${encodeURI(eventName)}`;
  405. utils.commomHttpRequest(url, function (ret, data) {
  406. if (ret) {
  407. utils.showLog("上报自定义事件成功!");
  408. } else {
  409. utils.showLog("上报自定义事件失败!");
  410. }
  411. }.bind(this));
  412. }
  413. }
  414. /**
  415. * 弹出提示框
  416. * @param msg 消息
  417. */
  418. public showToast(msg: string) {
  419. if (PlatUtils.IsQQ) {
  420. //@ts-ignore
  421. qq.showToast({
  422. title: msg,
  423. icon: "none",
  424. duration: 2000
  425. })
  426. }
  427. }
  428. /**
  429. * 是否可以创建桌面图标, 当前平台是否支持创建快捷方式
  430. */
  431. public canCreateShortcut() {
  432. console.log("canCreateShortcut ", this.isOverMinVersion("1.7.1"));
  433. if (PlatUtils.IsQQ && PlatUtils.IsAndroid) {
  434. return this.isOverMinVersion("1.7.1");
  435. }
  436. return false;
  437. }
  438. /**
  439. * 创建桌面图标
  440. */
  441. public createShortcut(callback: Function) {
  442. let callbackFunc = callback;
  443. if (PlatUtils.IsQQ && this.canCreateShortcut()) {
  444. //@ts-ignore
  445. qq.saveAppToDesktop({
  446. success: () => {
  447. utils.showLog('桌面图标创建成功!');
  448. this._shortcutCreated = true;
  449. if (callbackFunc) {
  450. callbackFunc(true);
  451. }
  452. },
  453. fail: (err) => {
  454. utils.showLog('qq创建桌面失败err' + err);
  455. if (callbackFunc) {
  456. callbackFunc(false);
  457. }
  458. },
  459. complete: function () {
  460. }
  461. });
  462. } else {
  463. utils.showLog("当前平台版本不支持创建桌面");
  464. if (callbackFunc) {
  465. callbackFunc(false);
  466. }
  467. }
  468. }
  469. /**
  470. * 添加收藏
  471. * **/
  472. addFavorites() {
  473. utils.showLog('addFavorites >>>>');
  474. let fav = YZ_LocalStorage.getItem("qq_favorites");
  475. if ("1" == fav) {
  476. utils.showLog('had addToFavorites')
  477. return
  478. }
  479. let title = "好游戏哦";
  480. let img = "";
  481. if (utils.config.otherconfig) {
  482. if (utils.config.otherconfig.shareTitle) {
  483. title = utils.config.otherconfig.shareTitle
  484. }
  485. if (utils.config.otherconfig.shareImgUrl) {
  486. img = utils.config.otherconfig.shareImgUrl
  487. }
  488. }
  489. //@ts-ignore
  490. qq.addToFavorites({
  491. title: title,
  492. imageUrl: img,
  493. query: 'a=1&b=2',
  494. success: function (res) {
  495. utils.showLog('addToFavorites success', res)
  496. YZ_LocalStorage.setItem("qq_favorites", "1");
  497. },
  498. fail: function (err) {
  499. utils.showLog('addToFavorites fail', err)
  500. },
  501. complete: function (res) {
  502. utils.showLog('addToFavorites info', res)
  503. }
  504. })
  505. }
  506. /**
  507. * 添加普通彩签
  508. */
  509. addColorSign() {
  510. //@ts-ignore
  511. qq.addColorSign({
  512. success: function (res) {
  513. utils.showLog('addColorSign success', res)
  514. },
  515. fail: function (err) {
  516. utils.showLog('addColorSign fail', err)
  517. },
  518. complete: function (res) {
  519. utils.showLog('addColorSign info', res)
  520. }
  521. })
  522. }
  523. /**
  524. * 退出游戏
  525. */
  526. public GameExit() {
  527. if (PlatUtils.IsQQ) {
  528. utils.showLog("tool qq GameExit");
  529. try {
  530. //@ts-ignore
  531. qq.exitMiniProgram()
  532. } catch (error) {
  533. cc.log(error);
  534. }
  535. }
  536. }
  537. }