tyq-sdk.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. import { Game, game, sys } from "cc";
  2. import TyqEventMgr from "./tyq-event-mgr";
  3. import tyqSdkConfig from "./tyq-sdk-config";
  4. import { NetworkMgr } from "./weNetworkMgr";
  5. /**游戏数据 */
  6. export interface gameInfo {
  7. gameName: string,
  8. gameImg: string,
  9. gameTips: string,
  10. gameVideID: string,
  11. gameID: any
  12. }
  13. export enum EDartsType {
  14. grid = 1,
  15. interstitial,
  16. infoFlow,
  17. reward,
  18. }
  19. export enum EDartStatus {
  20. /**曝光 */
  21. exposure = 1,
  22. /**访问 */
  23. visit = 2,
  24. /**点击 */
  25. click = 3,
  26. }
  27. export interface jumpIconData {
  28. name: string,
  29. appid: string,
  30. imgUrl: string,
  31. weixin_ads_data: string,
  32. key: string,
  33. }
  34. /**SDK 类 */
  35. class tyqSdk {
  36. public static readonly _instance = new tyqSdk();
  37. /**开关对象合集 */
  38. private switch_info: any = {};
  39. /**总开关 1是开 0是关*/
  40. private master_switch: number = 0;
  41. /**用户唯一openID */
  42. private openid: string = ""
  43. /**游玩时间 */
  44. private _playTime: number = 0;
  45. /**观看视频时间 */
  46. private _videoTime: number = 0;
  47. //飞镖
  48. private reqDartAwardTime = 0;
  49. private dartDurTime = 30000;//飞镖请求最小间隔事件,防止重复请求
  50. private dartAwardFun: (config) => void = null;
  51. private _gameLevel: string = "";
  52. private item_openId = "tyq_item_openid";
  53. private item_watermark = "tyq_item_watermark_";
  54. private item_dartAwardConfig = "tyq_item_dartAward_config";
  55. private _watermark: string = "";
  56. private _onlineTime = 0;
  57. private _dartDatas = {};
  58. public weixin_ads_data: Array<Object>[][] = null;
  59. public wxGameIconData: Array<jumpIconData> = [];
  60. public tyqAdArr: number[] = [];
  61. constructor() {
  62. }
  63. /**初始化SDK,获取开关 只需传成功回调,因为成功失败都会进入场景*/
  64. public init(success?: Function) {
  65. //以上代码是游玩统计
  66. // this.LaunchOptionsSync = Toutiao.LaunchOptionsSync();
  67. // if (tyqSdkConfig.webTest) {
  68. // this.LaunchOptionsSync = {
  69. // scene_id: "990001",
  70. // query: {}
  71. // }
  72. // }
  73. this._watermark = sys.localStorage.getItem(this.item_watermark) || "";
  74. this.openid = this.initOpenId();
  75. var time = this.getTimeStamp(true);//获取到毫秒的时间戳,精确到毫秒
  76. let info = {
  77. appid: tyqSdkConfig.appId,
  78. nonce_str: this.randomStr(),
  79. time_stamp: time,
  80. app_version: tyqSdkConfig.app_version,
  81. }
  82. NetworkMgr.xhrPost("api/v1/switch_info", info, (cb: any) => {
  83. console.log(cb);
  84. if (cb.data) {
  85. this.switch_info = cb.data.switch_info;
  86. this.master_switch = cb.data.master_switch;
  87. if (cb.data.ads_data) {
  88. this._dartDatas = cb.data.ads_data;
  89. }
  90. }
  91. if (cb.data.weixin_ads_data) {
  92. this.weixin_ads_data = cb.data.weixin_ads_data;
  93. let count = 0;
  94. for (let key in this.weixin_ads_data) {
  95. let arr = [];
  96. console.log('key', key);
  97. if (typeof (key)) {
  98. for (let i = 0; i < this.weixin_ads_data[key].length; i++) {
  99. arr = [];
  100. for (let keys in this.weixin_ads_data[key][i]) {
  101. arr.push(this.weixin_ads_data[key][i][keys]);
  102. }
  103. var jumpIconData: jumpIconData = {
  104. name: arr[0],
  105. appid: arr[1],
  106. imgUrl: arr[2],
  107. weixin_ads_data: arr[3],
  108. key: key,
  109. }
  110. this.wxGameIconData.push(jumpIconData);
  111. }
  112. }
  113. }
  114. console.log("this.wxGameIconData", this.wxGameIconData);
  115. }
  116. if (success) {
  117. success();
  118. // this.login();
  119. return;
  120. }
  121. }, () => {
  122. if (success) {
  123. success();
  124. }
  125. });
  126. //开始统计玩家停留时间
  127. this._onlineTime = this.getTimeStamp();
  128. game.on(Game.EVENT_HIDE, () => {
  129. this.collectPlayeTime();
  130. });
  131. game.on(Game.EVENT_SHOW, () => {
  132. this._onlineTime = this.getTimeStamp();
  133. let nowTime = Date.now();
  134. if (nowTime - this.reqDartAwardTime >= this.dartDurTime) {
  135. this.reqDartAwardTime = Date.now();
  136. setTimeout(() => {
  137. this.reqDartAward();
  138. }, 200);
  139. }
  140. })
  141. }
  142. public wxIconData(): Array<jumpIconData> {
  143. return this.wxGameIconData;
  144. }
  145. public wxJumpData(): Array<Object> {
  146. return this.weixin_ads_data;
  147. }
  148. /**
  149. * 登录接口
  150. * 进入主界面后调用
  151. * @returns
  152. */
  153. public login() {
  154. if (!this.openid) {
  155. console.error("openId为空");
  156. return;
  157. }
  158. var time = this.getTimeStamp(true);//获取到毫秒的时间戳,精确到毫秒
  159. let info = {
  160. appid: tyqSdkConfig.appId,
  161. nonce_str: this.randomStr(),
  162. time_stamp: time,
  163. openid: this.openid,
  164. watermark: this._watermark,
  165. }
  166. NetworkMgr.xhrPost("api/v1/login", info, (res: any) => {
  167. console.log(res);
  168. TyqEventMgr.ins.onLogin(this.openid);
  169. if (res.data) {
  170. this._watermark = encodeURIComponent(res.data.watermark);
  171. sys.localStorage.setItem(this.item_watermark, this._watermark);
  172. }
  173. }, () => {
  174. console.error("登录失败,网络错误");
  175. });
  176. }
  177. /**
  178. * 实名认证接口
  179. * @param carId
  180. * @param realName
  181. * @param cb
  182. */
  183. public verifyRealName(carId: string, realName: string, cb: Function) {
  184. var time = this.getTimeStamp(true);//获取到毫秒的时间戳,精确到毫秒
  185. let data = {
  186. appid: tyqSdkConfig.appId,
  187. nonce_str: this.randomStr(),
  188. time_stamp: time,
  189. openid: this.openid,
  190. cardno: carId,
  191. name: realName
  192. }
  193. NetworkMgr.xhrPost("api/v1/idcard", data, cb);
  194. }
  195. /**直接获取开关值 */
  196. //mast 是否判断总开关
  197. public getSwitchValue(str: string, df?): any {
  198. if (this.master_switch == 0) {
  199. return 0;
  200. }
  201. if (!this.switch_info[str]) {//不存在这个开关
  202. console.log(str + "开关不存在");
  203. return df || 0;
  204. } else if (this.switch_info[str] == "0") {
  205. return 0;
  206. } else {
  207. return this.switch_info[str];
  208. }
  209. }
  210. /**
  211. * 概率开关值
  212. * @param str
  213. * @returns
  214. */
  215. public getConfigProbability(str: string) {
  216. let value = this.getSwitchValue(str);
  217. if (!value) {
  218. return false;
  219. }
  220. let rand = Math.random();
  221. if (rand < value) {
  222. return true;
  223. } else {
  224. return false;
  225. }
  226. }
  227. /**游戏开始时调用
  228. * @param level 关卡 如果是特殊关卡,传特殊关卡名称即可
  229. * @param inGameFun 真正开始游戏的方法
  230. */
  231. public startGame(level: any, inGameFun?: Function) {
  232. // this.outMain();
  233. // if (this.Physical <= 0 && this.getSwitchByName("mianPhysical")) {
  234. // this.showPhysicalPanel();
  235. // return;
  236. // }
  237. // if (typeof (level) == "number") {
  238. // this._gameLevel = level.toString();
  239. // } else {
  240. // this._gameLevel = level;
  241. // }
  242. this._gameLevel = level;
  243. this.collectLevelInfo();
  244. TyqEventMgr.getInstance().onStartGame(level);
  245. // this.hideMain();
  246. // if (this.tyq_exit) {
  247. // this.tyq_exit.active = false;
  248. // }
  249. // this.Physical = -1;
  250. // //游戏开始调用狂点宝箱 这里要区分套路版
  251. // if (!this.getSwitchInfoByName("crazyBox", this.levelCunt)) {
  252. // inGameFun();
  253. // this.screencap();
  254. // return;
  255. // }
  256. // this.loadPrefab("prefab/tyq_crazyBox", (node: Node) => {
  257. // if (this.canvasNode) {
  258. // node.setParent(this.canvasNode);
  259. // node.getComponent(tyq_crazyBox)!.inint(() => {
  260. // inGameFun();
  261. // this.screencap();
  262. // });
  263. // }
  264. // })
  265. }
  266. /**
  267. * 游戏结束时调用
  268. * @param gameType 过关状态,传win或者lose字符串,不是通关的游戏也传win
  269. * @param nextFun 进入下一关(或者结算界面)的方法传进来
  270. */
  271. public endGame(isWin: boolean, nextFun?: Function) {
  272. // this.stopScreencap();
  273. this.collectLevelInfo(isWin ? 2 : 3);
  274. TyqEventMgr.getInstance().onEndGame(isWin);
  275. // if (this.tyq_exit) {
  276. // this.tyq_exit.active = true;
  277. // }
  278. // if (!this.getSwitchInfoByName("endGameAD", this.levelCunt)) {
  279. // // this.loadPrefab("prefab/tyq_share", (node: Node) => {
  280. // // node.setParent(this.canvasNode);
  281. // // node.getComponent(tyq_share)!.init(() => {
  282. // // this.showLuckBox(gameType, nextFun);
  283. // // })
  284. // // });
  285. // } else {
  286. // this.showVideoAD("结束视频拉取", () => {
  287. // // this.loadPrefab("prefab/tyq_share", (node: Node) => {
  288. // // node.setParent(this.canvasNode);
  289. // // node.getComponent(tyq_share)!.init(() => {
  290. // // this.showLuckBox(gameType, nextFun);
  291. // // })
  292. // // })
  293. // }, () => {
  294. // // this.loadPrefab("prefab/tyq_share", (node: Node) => {
  295. // // node.setParent(this.canvasNode);
  296. // // node.getComponent(tyq_share)!.init(() => {
  297. // // this.showLuckBox(gameType, nextFun);
  298. // // })
  299. // // })
  300. // });
  301. // }
  302. // if (gameType == "win") {
  303. // this.addLevel();
  304. // }
  305. }
  306. /**
  307. * 收集用户点击跳转信息,关于跳转后台小游戏接口触活量统计
  308. * @param event 时间名称
  309. * @param weixin_ads_id 后台所对应图片展示位
  310. */
  311. public collectClickEventGame(event: string, weixin_ads_id: string) {
  312. if (!this.openid) {
  313. console.error("没有openid");
  314. return;
  315. }
  316. var time = this.getTimeStamp(true);
  317. let info = {
  318. appid: tyqSdkConfig.appId,
  319. nonce_str: this.randomStr(),
  320. time_stamp: time,
  321. openid: this.openid,
  322. event_id: event,
  323. watermark: this._watermark,
  324. weixin_ads_id: weixin_ads_id,
  325. }
  326. NetworkMgr.xhrPost("api/v1/collect_weixin_ads_jumb_ok_cb", info);
  327. }
  328. /**
  329. * 收集用户点击事件
  330. * @param event 时间名称
  331. */
  332. public collectClickEvent(event: string) {
  333. if (!this.openid) {
  334. console.error("没有openid");
  335. return;
  336. }
  337. var time = this.getTimeStamp(true);
  338. let info = {
  339. appid: tyqSdkConfig.appId,
  340. nonce_str: this.randomStr(),
  341. time_stamp: time,
  342. openid: this.openid,
  343. event_id: event,
  344. watermark: this._watermark,
  345. }
  346. NetworkMgr.xhrPost("api/v1/collect_click_event", info);
  347. }
  348. /**收集用户玩游戏停留时间 */
  349. private collectPlayeTime() {
  350. if (!this.openid) {
  351. console.error("没有openid");
  352. return;
  353. }
  354. var nowTime = this.getTimeStamp();
  355. let elapsed = nowTime - this._onlineTime;
  356. console.log("上传停留", elapsed);
  357. let info = {
  358. appid: tyqSdkConfig.appId,
  359. nonce_str: this.randomStr(),
  360. time_stamp: this.getTimeStamp(true),
  361. openid: this.openid,
  362. duration_time: elapsed,
  363. watermark: this._watermark,
  364. }
  365. NetworkMgr.xhrPost("api/v1/collect_open_game_play_time", info);
  366. }
  367. /**
  368. * 收集广告视频行为(已弃用)
  369. * @param status 广告状态。1 拉取成功(视频请求pv) 2 广告展示(视频曝光pv) 3 视频完整播放 4 视频中途关掉(这个要上传play_time)
  370. */
  371. public collectAdAction(status: number) {
  372. return;
  373. if (!this.openid) return;
  374. var time = this.getTimeStamp(true);
  375. let curTime = Number(time);
  376. if (status == 2) {//展示成功开始计算时间
  377. this._videoTime = curTime;
  378. } else if (status == 3) {//播放完整清楚时间
  379. this._videoTime = 0;
  380. } else if (status == 4) {//中途关掉
  381. this._videoTime = curTime - this._videoTime;
  382. }
  383. let info = {
  384. appid: tyqSdkConfig.appId,
  385. nonce_str: this.randomStr(),
  386. time_stamp: time,
  387. openid: this.openid,
  388. status: status,
  389. play_time: this._videoTime,
  390. }
  391. NetworkMgr.xhrPost("api/v1/collect_ad_action", info);
  392. }
  393. /**随机字符串*/
  394. private randomStr(strLen: number = 32) {
  395. let len = strLen;
  396. let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  397. let maxPos = $chars.length;
  398. let pwd = '';
  399. for (let idx = 0; idx < len; idx++) {
  400. pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  401. }
  402. return pwd;
  403. }
  404. /**openID初始化 */
  405. private initOpenId(): string {
  406. let isNew = false;
  407. let openId = sys.localStorage.getItem(this.item_openId);
  408. if (!openId) {
  409. isNew = true;
  410. openId = this.randOpenid();
  411. sys.localStorage.setItem(this.item_openId, openId);
  412. TyqEventMgr.ins.onRegister(openId);
  413. }
  414. console.log("openid=", openId);
  415. return openId;
  416. }
  417. private randOpenid() {
  418. // let openId = "";
  419. // var data = new Date();
  420. // const curTime = data.getFullYear().toString() + (data.getMonth() + 1).toString() + data.getDate().toString()//精确到日
  421. // let Hours = data.getHours().toString();
  422. // let Min = data.getMinutes().toString();
  423. // let Second = data.getSeconds().toString();
  424. // if (Hours.length == 1) {
  425. // Hours = "0" + Hours;
  426. // }
  427. // if (Min.length == 1) {
  428. // Min = "0" + Min;
  429. // }
  430. // if (Second.length == 1) {
  431. // Second = "0" + Second;
  432. // }
  433. // const randStr = this.randomStr(19);
  434. // openId = "tyq" + curTime + Hours + Min + Second + randStr;
  435. // return openId;
  436. var s = [], hexDigits = "0123456789abcdef";
  437. for (var i = 0; i < 40; i++) {
  438. s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  439. }
  440. s[14] = "4";
  441. s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
  442. s[8] = s[13] = s[18] = s[23] = s[28] = "-";
  443. return s.join("");
  444. }
  445. /**
  446. * 收集关卡游玩信息
  447. * @param stata 胜利或者失败
  448. */
  449. private collectLevelInfo(stata?: number) {
  450. if (!this.openid) return;
  451. var time = this.getTimeStamp(true);
  452. let curTime = this.getTimeStamp(false);
  453. if (stata) {//如果有状态 要计算游戏时间
  454. var play_time = curTime - this._playTime;
  455. this._playTime = 0;
  456. } else {
  457. var play_time = 0;
  458. this._playTime = curTime;
  459. }
  460. let info = {
  461. appid: tyqSdkConfig.appId,
  462. nonce_str: this.randomStr(),
  463. time_stamp: time,
  464. openid: this.openid,
  465. game_level: this._gameLevel,
  466. status: stata ? stata : 1,
  467. play_time: play_time,
  468. watermark: this._watermark,
  469. }
  470. NetworkMgr.xhrPost("api/v1/collect_user_play_game_level", info);
  471. }
  472. /**
  473. * 获取时间戳
  474. * @param second 传true 会返回精确到秒的时间戳 ,默认返回精确到毫秒的时间戳
  475. * @returns
  476. */
  477. private getTimeStamp(isSecond = false) {
  478. let time = Date.now();
  479. if (isSecond) {
  480. time = Math.floor(time / 1000);
  481. }
  482. return time;
  483. }
  484. /**
  485. * 发送广告事件(曝光点击等)
  486. * @param ads_id
  487. * @param status
  488. * @returns
  489. */
  490. public sendDartAdStatus(ads_id, status: EDartStatus) {
  491. if (!ads_id) {
  492. console.error("没有ads_id");
  493. return;
  494. }
  495. let info = {
  496. appid: tyqSdkConfig.appId,
  497. nonce_str: this.randomStr(),
  498. time_stamp: this.getTimeStamp(true),
  499. openid: this.openid,
  500. ads_id: ads_id,
  501. status: status,
  502. }
  503. NetworkMgr.xhrPost("api/v1/ads_collect_datas", info);
  504. }
  505. /**
  506. * 根据类型获取飞镖广告
  507. * @param type
  508. * @returns
  509. */
  510. public getDartAdByType(type) {
  511. let dartDatas = this._dartDatas[type];
  512. if (dartDatas && dartDatas.length > 0) {
  513. return dartDatas[Math.floor(Math.random() * dartDatas.length)];
  514. }
  515. return null;
  516. }
  517. //请求推广奖励(飞镖下载安装激活的奖励)
  518. private reqDartAward() {
  519. return;
  520. console.log("请求非标广告奖励");
  521. let info = {
  522. appid: tyqSdkConfig.appId,
  523. nonce_str: this.randomStr(),
  524. time_stamp: this.getTimeStamp(true),
  525. openid: this.openid,
  526. }
  527. NetworkMgr.xhrPost("api/v1/get_rewards", info, (res) => {
  528. console.log(res.errmsg)
  529. if (res.errcode == 0) {
  530. // isActive = true;
  531. if (this.dartAwardFun && typeof this.dartAwardFun == "function") {
  532. let config = sys.localStorage.getItem(this.item_dartAwardConfig);
  533. this.dartAwardFun(JSON.parse(config));
  534. }
  535. }
  536. });
  537. }
  538. //设置飞镖下载奖励
  539. public setReqAwardFun(fun: (config) => void) {
  540. this.dartAwardFun = fun;
  541. this.reqDartAward();
  542. }
  543. //
  544. public getNoRepetition() {
  545. if (!this.tyqAdArr) return;
  546. }
  547. }
  548. export const tyqSDK = tyqSdk._instance;
  549. (<any>window)["TyqSdk"] = tyqSdk._instance;