netUtils.ts 18 KB

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