netUtils.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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',
  36. //获取用户土地信息和一个租赁状态
  37. userLandAndCanStealList: 'comPlayerLand/getCanStealDetailList',
  38. //获取用户可以偷取的列表信息
  39. canStealUserList: 'comPlayerLand/getCanStealUserList',
  40. /**
  41. * 新增灾难部分接口
  42. */
  43. //灾难接口
  44. disasterHistory:'comPlayerLand/getDisasterHistory',
  45. //获取土地信息
  46. landState: 'comPlayerLand/getState',
  47. //种植
  48. plant: 'comPlayerLand/plant',
  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. /** 登录获取的token */
  100. token: null,
  101. /** 后端RSA公钥 */
  102. javaPublicKey: null,
  103. /** api加密开关 */
  104. sysApiEncrypt: null,
  105. /** 设置token格式 */
  106. setToken(value) {
  107. // "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q"
  108. this.token = "Bearer " + value;
  109. },
  110. /**设置一个错误token测试 */
  111. onTestToken() {
  112. this.token = "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q";
  113. },
  114. setJavaPublicKeyAndSysApiEncrypt(javaPublicKey, sysApiEncrypt) {
  115. this.javaPublicKey = javaPublicKey;
  116. this.sysApiEncrypt = sysApiEncrypt;
  117. },
  118. get(url, params, callback) {
  119. let dataStr = '';
  120. Object.keys(params).forEach(key => {
  121. dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
  122. })
  123. if (dataStr !== '') {
  124. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  125. url = url + '?' + dataStr;
  126. }
  127. url = this.baseUrl + url;
  128. let xhr = cc.loader.getXMLHttpRequest();
  129. xhr.open("GET", url, true);
  130. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  131. if (this.token) {
  132. xhr.setRequestHeader("Authorization", this.token);
  133. }
  134. xhr.onreadystatechange = function () {
  135. if (xhr.readyState === 4) {
  136. let response = xhr.responseText;
  137. if (xhr.status >= 200 && xhr.status < 300) {
  138. // let aesKeyS = aesUtil.genKey();
  139. // let encryptS = aesUtil.encrypt(response, aesKeyS);
  140. // let aesKeyE = rsaUtil.encrypt(aesKeyS, sessionStorage.getItem('javaPublicKey')),//后端RSA公钥加密后的AES的key
  141. // console.log('aesKeyS:',aesKeyS);
  142. // console.log('encryptS:',encryptS);
  143. // data = aesUtil.decrypt(data.data.data, rsaUtil.decrypt(data.data.aesKey, window.jsPrivateKey));
  144. // todo 处理token过期操作?
  145. // 301,302,303,304
  146. let _response = JSON.parse(response);
  147. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  148. console.log("token异常" + _response.msg);
  149. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  150. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  151. let _pause = cc.instantiate(texture);
  152. let _uiCamera = cc.find("Canvas/UICamera");
  153. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  154. _pause.zIndex = 999;
  155. let DetailLabel = _pause.getChildByName('DetailLabel');
  156. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  157. setTimeout(() => {
  158. cc.game.pause();
  159. }, 60)
  160. });
  161. return;
  162. }
  163. if (404 === _response.code) {
  164. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  165. let _pause = cc.instantiate(texture);
  166. let _uiCamera = cc.find("Canvas/UICamera");
  167. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  168. _pause.zIndex = 999;
  169. let DetailLabel = _pause.getChildByName('DetailLabel');
  170. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  171. setTimeout(() => {
  172. cc.game.pause();
  173. }, 60)
  174. });
  175. return;
  176. }
  177. // let httpStatus = xhr.statusText;
  178. if (callback)
  179. callback(true, _response);
  180. notifyCenter.emit("netSuccess", _response);
  181. } else {
  182. console.error("访问:" + url + "失败!");
  183. let _response = null;
  184. if (typeof response == 'string' && !response) {
  185. _response = JSON.parse(response);
  186. }
  187. if (callback)
  188. callback(false, _response);
  189. notifyCenter.emit("netError", _response);
  190. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  191. window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  192. } else {
  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 = "网络请求失败!";
  200. setTimeout(() => {
  201. _pause.destroy();
  202. }, 1000)
  203. });
  204. }
  205. }
  206. }
  207. };
  208. xhr.send();
  209. },
  210. //Post请求
  211. post(url, param, callback) {
  212. url = this.baseUrl + url;
  213. var xhr = cc.loader.getXMLHttpRequest();
  214. let dataStr = '';
  215. Object.keys(param).forEach(key => {
  216. dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
  217. })
  218. if (dataStr !== '') {
  219. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  220. }
  221. xhr.open("POST", url, true);
  222. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  223. if (this.token) {
  224. xhr.setRequestHeader("Authorization", this.token);
  225. }
  226. xhr.onreadystatechange = function () {
  227. if (xhr.readyState === 4) {
  228. let response = xhr.responseText;
  229. if (xhr.status >= 200 && xhr.status < 300) {
  230. let _response = JSON.parse(response);
  231. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  232. console.log("token异常" + _response.msg);
  233. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  234. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  235. let _pause = cc.instantiate(texture);
  236. let _uiCamera = cc.find("Canvas/UICamera");
  237. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  238. _pause.zIndex = 999;
  239. let DetailLabel = _pause.getChildByName('DetailLabel');
  240. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  241. setTimeout(() => {
  242. cc.game.pause();
  243. }, 60)
  244. });
  245. return;
  246. }
  247. if (404 === _response.code) {
  248. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  249. let _pause = cc.instantiate(texture);
  250. let _uiCamera = cc.find("Canvas/UICamera");
  251. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  252. _pause.zIndex = 999;
  253. let DetailLabel = _pause.getChildByName('DetailLabel');
  254. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  255. setTimeout(() => {
  256. cc.game.pause();
  257. }, 60)
  258. });
  259. return;
  260. }
  261. // let httpStatus = xhr.statusText;
  262. if (callback)
  263. callback(true, _response);
  264. notifyCenter.emit("netSuccess", _response);
  265. } else {
  266. console.error("访问:" + url + "失败!");
  267. let _response = null;
  268. if (typeof response == 'string' && !response) {
  269. _response = JSON.parse(response);
  270. }
  271. if (callback)
  272. callback(false, _response);
  273. notifyCenter.emit("netError", _response);
  274. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  275. window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  276. } else {
  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 = "网络请求失败!";
  284. setTimeout(() => {
  285. _pause.destroy();
  286. }, 1000)
  287. });
  288. }
  289. }
  290. }
  291. };
  292. xhr.send(dataStr);
  293. },
  294. // getKey(){
  295. // let aesKey = aesUtil.genKey();
  296. // console.log('aesKey:',aesKey);
  297. // }
  298. init(id, callback: Function, target: any) {
  299. if (this.ws != null) return;
  300. // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
  301. // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
  302. console.log("utils.token:", utils.token);
  303. this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
  304. this.ws.onopen = (event: Event) => {
  305. callback.call(target, "登录成功");
  306. }
  307. this.ws.onmessage = (event: MessageEvent) => {
  308. callback.call(target, event.data);
  309. }
  310. this.ws.onerror = function (e) {
  311. console.error("WebSocket连接发生错误");
  312. };
  313. },
  314. sendMsg(data: string) {
  315. if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
  316. this.ws.send(data);
  317. }
  318. };
  319. /**
  320. * 加解密操作简单封装一下
  321. */
  322. // let aesUtil = {
  323. // //获取key,
  324. // genKey : function (length = 16) {
  325. // let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  326. // let str = "";
  327. // for (let i = 0; i < length; i++) {
  328. // str = str + random.charAt(Math.random() * random.length)
  329. // }
  330. // return str;
  331. // },
  332. // //加密
  333. // encrypt : function (plaintext,key) {
  334. // if (plaintext instanceof Object) {
  335. // //JSON.stringify
  336. // plaintext = JSON.stringify(plaintext)
  337. // }
  338. // let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  339. // return encrypted.toString();
  340. // },
  341. // //解密
  342. // decrypt : function (ciphertext,key) {
  343. // let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  344. // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
  345. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  346. // //JSON.parse
  347. // decString = JSON.parse(decString);
  348. // }
  349. // return decString;
  350. // }
  351. // };
  352. // let rsaUtil = {
  353. // //RSA 位数,这里要跟后端对应
  354. // bits: 1024,
  355. // //当前JSEncrypted对象
  356. // thisKeyPair: {},
  357. // //生成密钥对(公钥和私钥)
  358. // genKeyPair: function (bits = rsaUtil.bits) {
  359. // let genKeyPair = {};
  360. // rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});
  361. // //获取私钥
  362. // genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();
  363. // //获取公钥
  364. // genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();
  365. // return genKeyPair;
  366. // },
  367. // //公钥加密
  368. // encrypt: function (plaintext, publicKey) {
  369. // if (plaintext instanceof Object) {
  370. // //1、JSON.stringify
  371. // plaintext = JSON.stringify(plaintext)
  372. // }
  373. // publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
  374. // return rsaUtil.thisKeyPair.encrypt(plaintext);
  375. // },
  376. // //私钥解密
  377. // decrypt: function (ciphertext, privateKey) {
  378. // privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
  379. // let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
  380. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  381. // //JSON.parse
  382. // decString = JSON.parse(decString);
  383. // }
  384. // return decString;
  385. // }
  386. // };
  387. export { utils as default };