netUtils.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import notifyCenter from "./Comming/NotificationCenter";
  2. // import CryptoJS from "./encrypt/cryptojs";
  3. // import JSEncrypt from "./encrypt/jsencrypt";
  4. //通用工具函数类
  5. var utils = {
  6. version: "0.15",
  7. // baseUrl: "https://www.yuyekeji.cn/game/",
  8. // baseUrl: "http://127.0.0.1:26001/api_dapp/game/",
  9. // baseUrl: "https://www.yuyekeji.cn/api_dapp/game/",
  10. baseUrl: window['dappHost'] + '/api_dapp/game/',
  11. api: {
  12. //获取public 和 系统设置
  13. publicKeyAndSys: 'comUsers/publicKeyAndSys',
  14. // /**
  15. // * @deprecated 用loginTokenAndVerification 替代
  16. // */
  17. // loginToken: 'comUsers/loginToken',
  18. loginTokenAndVerification: 'comUsers/loginTokenAndVerification',
  19. //平台账户相关信息
  20. userInfo: 'comUsers/getUserInfo',
  21. userSnbInfo: 'comUsers/getUserSnb',
  22. //角色的信息
  23. playerPullInfo: 'comPlayers/playerPullInfo',
  24. //获取玩家属性
  25. playerAttribute: 'comPlayersAttri/getPlayerAttribute',
  26. /**
  27. * 获取是否租赁过的状态
  28. */
  29. playerExchangeState: 'comPlayers/getPlayerExchangeState',
  30. //获取游戏config土地列表
  31. landConfig: 'configLand/getList',
  32. //获取用户已经租赁的土地
  33. userLandList: 'comPlayerLand/getList', /*** disater dapp 调用,不用显示ui*/
  34. //获取用户土地信息和一个租赁状态
  35. userLandAndCanStealList: 'comPlayerLand/getCanStealDetailList', /*** disater 对方玩家,不用显示ui*/
  36. //获取用户可以偷取的列表信息
  37. canStealUserList: 'comPlayerLand/getCanStealUserList',
  38. /**
  39. * 新增灾难部分接口
  40. */
  41. //灾难接口
  42. disasterHistory: 'comPlayerLand/getDisasterHistory',
  43. //获取防护装备
  44. getDisasterProtectedMap: 'comPlayerLand/getDisasterMap',
  45. //获取土地信息
  46. landState: 'comPlayerLand/getState',
  47. //种植
  48. plant: 'comPlayerLand/plant', /*** disater 种植完后,直接处理一个初始灾难*/
  49. //种子
  50. mallSeed: 'comMallSeed/getMallSeed',
  51. /**
  52. * 用钻石兑换一包种子
  53. */
  54. exchangeSeeds: 'comMallSeed/exchangeSeeds',
  55. //仓库种子和果实
  56. getSeedAndFruit: 'comPlayerGoods/getSeedAndFruit',
  57. //背包的种子数量
  58. getSeedState: 'comPlayerGoods/getSeedState',
  59. //收取果实
  60. addFruit: 'comPlayerGoods/addFruit',
  61. //一键偷取全部果实
  62. stealAllFruit: 'comPlayerGoods/stealAllFruit',
  63. //单个收取
  64. stealFruit: 'comPlayerGoods/stealFruit',
  65. //出售果实
  66. saleFruit: 'comPlayerGoods/saleFruit',
  67. //赠送果实
  68. grantFruit: 'comPlayerGoods/grantFruit',
  69. //神农呗购买种子
  70. snbBuySeeds: 'comMallSeed/snbBuySeeds',
  71. //获取操作的snb日志
  72. snbList: 'comSnbTran/getList',
  73. //买狗和打狗棒
  74. addEquipment: 'comPlayerDog/addEquipment',
  75. addFood: 'comPlayerDog/addFood',
  76. getEquipmentByType: 'comPlayerDog/getEquipmentByType',
  77. getListEquipment: 'comPlayerDog/getListEquipment',
  78. //获取狗粮列表
  79. getMallFoodList: 'comMallFood/getMallFoodList',
  80. //是否显示狗
  81. setDogShowState: 'comPlayerDog/setDogShowState',
  82. //商城装备列表
  83. getMallEquipmentList: 'comMallOther/getMallEquipmentList',
  84. /**
  85. * 模块10 返还snb
  86. */
  87. //说明:返回当前userId是否在领取SNB名单中,如果在名单中通过计算可算出进度
  88. getCntToSnb: 'comCntToSnb/get',
  89. //说明:领取SNB接口,需要提前导入数据到com_cnt_to_snb表,点击领取按钮后,后端自动计算本次可领取的SNB数量,Status为0不可领取
  90. receiveCntToSnb: 'comCntToSnb/receive',
  91. /**
  92. * 审核snb
  93. */
  94. //获取申请的page
  95. getSnbApplyPage: 'comSnbApply/getPage',
  96. //提交申请
  97. applySnbToCnt: 'comSnbApply/applySnbToCnt',
  98. //校验申请
  99. checkApplySnbToCnt: 'comSnbApply/checkApplySnbToCnt',
  100. /**
  101. * 模块3:工具功能模块
  102. */
  103. getTools: 'land/tools',
  104. //使用工具
  105. postUseLuckyTools: 'land/tools',
  106. getLevel: 'land/level',
  107. //升级土地
  108. postLandLevelUp: 'land/level',
  109. //幸运值兑换snb
  110. luckToSnb: 'land/snb',
  111. /**
  112. * 牧场区域
  113. *
  114. */
  115. //获取租赁机会,以金币形式表现
  116. getAnimalTimes: 'comPlayerCultivate/getTimes',
  117. //解锁某个土地 【牧场养殖渔场】
  118. payAnimalLand:'comPlayerCultivate/payLand',
  119. //喂养土地上的动物
  120. buyAnimalFood:'comPlayerCultivate/buyAnimalFood',
  121. //修改土地倍数
  122. multipleAnimalLand:'comPlayerCultivate/multipleLand',
  123. //兑换种子
  124. playerScoreExchange: 'comPlayerScore/exchange',
  125. //获取符合条件的种子
  126. playerScoreSeeds:'comPlayerScore/getSeeds',
  127. },
  128. /** 登录获取的token */
  129. token: null,
  130. /** 后端RSA公钥 */
  131. javaPublicKey: null,
  132. /** api加密开关 */
  133. sysApiEncrypt: null,
  134. /** 设置token格式 */
  135. setToken(value) {
  136. // "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q"
  137. this.token = "Bearer " + value;
  138. },
  139. /**设置一个错误token测试 */
  140. onTestToken() {
  141. this.token = "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q";
  142. },
  143. setJavaPublicKeyAndSysApiEncrypt(javaPublicKey, sysApiEncrypt) {
  144. this.javaPublicKey = javaPublicKey;
  145. this.sysApiEncrypt = sysApiEncrypt;
  146. },
  147. get(url, params, callback) {
  148. let dataStr = '';
  149. Object.keys(params).forEach(key => {
  150. dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
  151. })
  152. if (dataStr !== '') {
  153. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  154. url = url + '?' + dataStr;
  155. }
  156. url = this.baseUrl + url;
  157. let xhr = cc.loader.getXMLHttpRequest();
  158. xhr.open("GET", url, true);
  159. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  160. if (this.token) {
  161. xhr.setRequestHeader("Authorization", this.token);
  162. }
  163. xhr.onreadystatechange = function () {
  164. if (xhr.readyState === 4) {
  165. let response = xhr.responseText;
  166. if (xhr.status >= 200 && xhr.status < 300) {
  167. // let aesKeyS = aesUtil.genKey();
  168. // let encryptS = aesUtil.encrypt(response, aesKeyS);
  169. // let aesKeyE = rsaUtil.encrypt(aesKeyS, sessionStorage.getItem('javaPublicKey')),//后端RSA公钥加密后的AES的key
  170. // console.log('aesKeyS:',aesKeyS);
  171. // console.log('encryptS:',encryptS);
  172. // data = aesUtil.decrypt(data.data.data, rsaUtil.decrypt(data.data.aesKey, window.jsPrivateKey));
  173. // todo 处理token过期操作?
  174. // 301,302,303,304
  175. let _response = JSON.parse(response);
  176. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  177. console.log("token异常" + _response.msg);
  178. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  179. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  180. let _pause = cc.instantiate(texture);
  181. let _uiCamera = cc.find("Canvas/UICamera");
  182. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  183. _pause.zIndex = 999;
  184. let DetailLabel = _pause.getChildByName('DetailLabel');
  185. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  186. setTimeout(() => {
  187. cc.game.pause();
  188. }, 60)
  189. });
  190. return;
  191. }
  192. if (404 === _response.code) {
  193. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  194. let _pause = cc.instantiate(texture);
  195. let _uiCamera = cc.find("Canvas/UICamera");
  196. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  197. _pause.zIndex = 999;
  198. let DetailLabel = _pause.getChildByName('DetailLabel');
  199. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  200. setTimeout(() => {
  201. cc.game.pause();
  202. }, 60)
  203. });
  204. return;
  205. }
  206. // let httpStatus = xhr.statusText;
  207. if (callback)
  208. callback(true, _response);
  209. notifyCenter.emit("netSuccess", _response);
  210. } else {
  211. console.error("访问:" + url + "失败!");
  212. let _response = null;
  213. if (typeof response == 'string' && !response) {
  214. _response = JSON.parse(response);
  215. }
  216. if (callback)
  217. callback(false, _response);
  218. notifyCenter.emit("netError", _response);
  219. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  220. window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  221. } else {
  222. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  223. let _pause = cc.instantiate(texture);
  224. let _uiCamera = cc.find("Canvas/UICamera");
  225. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  226. _pause.zIndex = 999;
  227. let DetailLabel = _pause.getChildByName('DetailLabel');
  228. DetailLabel.getComponent(cc.Label).string = "网络请求失败!";
  229. setTimeout(() => {
  230. _pause.destroy();
  231. }, 1000)
  232. });
  233. }
  234. }
  235. }
  236. };
  237. xhr.send();
  238. },
  239. //Post请求
  240. post(url, param, callback) {
  241. url = this.baseUrl + url;
  242. var xhr = cc.loader.getXMLHttpRequest();
  243. let dataStr = '';
  244. Object.keys(param).forEach(key => {
  245. dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
  246. })
  247. if (dataStr !== '') {
  248. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  249. }
  250. xhr.open("POST", url, true);
  251. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  252. if (this.token) {
  253. xhr.setRequestHeader("Authorization", this.token);
  254. }
  255. xhr.onreadystatechange = function () {
  256. if (xhr.readyState === 4) {
  257. let response = xhr.responseText;
  258. if (xhr.status >= 200 && xhr.status < 300) {
  259. let _response = JSON.parse(response);
  260. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  261. console.log("token异常" + _response.msg);
  262. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  263. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  264. let _pause = cc.instantiate(texture);
  265. let _uiCamera = cc.find("Canvas/UICamera");
  266. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  267. _pause.zIndex = 999;
  268. let DetailLabel = _pause.getChildByName('DetailLabel');
  269. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  270. setTimeout(() => {
  271. cc.game.pause();
  272. }, 60)
  273. });
  274. return;
  275. }
  276. if (404 === _response.code) {
  277. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  278. let _pause = cc.instantiate(texture);
  279. let _uiCamera = cc.find("Canvas/UICamera");
  280. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  281. _pause.zIndex = 999;
  282. let DetailLabel = _pause.getChildByName('DetailLabel');
  283. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  284. setTimeout(() => {
  285. cc.game.pause();
  286. }, 60)
  287. });
  288. return;
  289. }
  290. // let httpStatus = xhr.statusText;
  291. if (callback)
  292. callback(true, _response);
  293. notifyCenter.emit("netSuccess", _response);
  294. } else {
  295. console.error("访问:" + url + "失败!");
  296. let _response = null;
  297. if (typeof response == 'string' && !response) {
  298. _response = JSON.parse(response);
  299. }
  300. if (callback)
  301. callback(false, _response);
  302. notifyCenter.emit("netError", _response);
  303. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  304. window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  305. } else {
  306. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  307. let _pause = cc.instantiate(texture);
  308. let _uiCamera = cc.find("Canvas/UICamera");
  309. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  310. _pause.zIndex = 999;
  311. let DetailLabel = _pause.getChildByName('DetailLabel');
  312. DetailLabel.getComponent(cc.Label).string = "网络请求失败!";
  313. setTimeout(() => {
  314. _pause.destroy();
  315. }, 1000)
  316. });
  317. }
  318. }
  319. }
  320. };
  321. xhr.send(dataStr);
  322. },
  323. // getKey(){
  324. // let aesKey = aesUtil.genKey();
  325. // console.log('aesKey:',aesKey);
  326. // }
  327. init(id, callback: Function, target: any) {
  328. if (this.ws != null) return;
  329. // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
  330. // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
  331. console.log("utils.token:", utils.token);
  332. this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
  333. this.ws.onopen = (event: Event) => {
  334. callback.call(target, "登录成功");
  335. }
  336. this.ws.onmessage = (event: MessageEvent) => {
  337. callback.call(target, event.data);
  338. }
  339. this.ws.onerror = function (e) {
  340. console.error("WebSocket连接发生错误");
  341. };
  342. },
  343. sendMsg(data: string) {
  344. if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
  345. this.ws.send(data);
  346. }
  347. };
  348. /**
  349. * 加解密操作简单封装一下
  350. */
  351. // let aesUtil = {
  352. // //获取key,
  353. // genKey : function (length = 16) {
  354. // let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  355. // let str = "";
  356. // for (let i = 0; i < length; i++) {
  357. // str = str + random.charAt(Math.random() * random.length)
  358. // }
  359. // return str;
  360. // },
  361. // //加密
  362. // encrypt : function (plaintext,key) {
  363. // if (plaintext instanceof Object) {
  364. // //JSON.stringify
  365. // plaintext = JSON.stringify(plaintext)
  366. // }
  367. // let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  368. // return encrypted.toString();
  369. // },
  370. // //解密
  371. // decrypt : function (ciphertext,key) {
  372. // let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  373. // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
  374. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  375. // //JSON.parse
  376. // decString = JSON.parse(decString);
  377. // }
  378. // return decString;
  379. // }
  380. // };
  381. // let rsaUtil = {
  382. // //RSA 位数,这里要跟后端对应
  383. // bits: 1024,
  384. // //当前JSEncrypted对象
  385. // thisKeyPair: {},
  386. // //生成密钥对(公钥和私钥)
  387. // genKeyPair: function (bits = rsaUtil.bits) {
  388. // let genKeyPair = {};
  389. // rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});
  390. // //获取私钥
  391. // genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();
  392. // //获取公钥
  393. // genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();
  394. // return genKeyPair;
  395. // },
  396. // //公钥加密
  397. // encrypt: function (plaintext, publicKey) {
  398. // if (plaintext instanceof Object) {
  399. // //1、JSON.stringify
  400. // plaintext = JSON.stringify(plaintext)
  401. // }
  402. // publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
  403. // return rsaUtil.thisKeyPair.encrypt(plaintext);
  404. // },
  405. // //私钥解密
  406. // decrypt: function (ciphertext, privateKey) {
  407. // privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
  408. // let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
  409. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  410. // //JSON.parse
  411. // decString = JSON.parse(decString);
  412. // }
  413. // return decString;
  414. // }
  415. // };
  416. export { utils as default };