netUtils.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. landState: 'comPlayerLand/getState',
  42. //种植
  43. plant: 'comPlayerLand/plant',
  44. //种子
  45. mallSeed: 'comMallSeed/getMallSeed',
  46. /**
  47. * 用钻石兑换一包种子
  48. */
  49. exchangeSeeds: 'comMallSeed/exchangeSeeds',
  50. //仓库种子和果实
  51. getSeedAndFruit: 'comPlayerGoods/getSeedAndFruit',
  52. //背包的种子数量
  53. getSeedState: 'comPlayerGoods/getSeedState',
  54. //收取果实
  55. addFruit: 'comPlayerGoods/addFruit',
  56. //一键偷取全部果实
  57. stealAllFruit: 'comPlayerGoods/stealAllFruit',
  58. //单个收取
  59. stealFruit:'comPlayerGoods/stealFruit',
  60. //出售果实
  61. saleFruit: 'comPlayerGoods/saleFruit',
  62. //赠送果实
  63. grantFruit: 'comPlayerGoods/grantFruit',
  64. //神农呗购买种子
  65. snbBuySeeds: 'comMallSeed/snbBuySeeds',
  66. //获取操作的snb日志
  67. snbList: 'comSnbTran/getList',
  68. //买狗和打狗棒
  69. addEquipment:'comPlayerDog/addEquipment',
  70. addFood:'comPlayerDog/addFood',
  71. getEquipmentByType:'comPlayerDog/getEquipmentByType',
  72. getListEquipment:'comPlayerDog/getListEquipment',
  73. },
  74. /** 登录获取的token */
  75. token: null,
  76. /** 后端RSA公钥 */
  77. javaPublicKey: null,
  78. /** api加密开关 */
  79. sysApiEncrypt: null,
  80. /** 设置token格式 */
  81. setToken(value) {
  82. // "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q"
  83. this.token = "Bearer " + value;
  84. },
  85. /**设置一个错误token测试 */
  86. onTestToken() {
  87. this.token = "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q";
  88. },
  89. setJavaPublicKeyAndSysApiEncrypt(javaPublicKey, sysApiEncrypt) {
  90. this.javaPublicKey = javaPublicKey;
  91. this.sysApiEncrypt = sysApiEncrypt;
  92. },
  93. get(url, params, callback) {
  94. let dataStr = '';
  95. Object.keys(params).forEach(key => {
  96. dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
  97. })
  98. if (dataStr !== '') {
  99. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  100. url = url + '?' + dataStr;
  101. }
  102. url = this.baseUrl + url;
  103. let xhr = cc.loader.getXMLHttpRequest();
  104. xhr.open("GET", url, true);
  105. xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  106. if (this.token) {
  107. xhr.setRequestHeader("Authorization", this.token);
  108. }
  109. xhr.onreadystatechange = function () {
  110. if (xhr.readyState === 4) {
  111. let response = xhr.responseText;
  112. if (xhr.status >= 200 && xhr.status < 300) {
  113. // let aesKeyS = aesUtil.genKey();
  114. // let encryptS = aesUtil.encrypt(response, aesKeyS);
  115. // let aesKeyE = rsaUtil.encrypt(aesKeyS, sessionStorage.getItem('javaPublicKey')),//后端RSA公钥加密后的AES的key
  116. // console.log('aesKeyS:',aesKeyS);
  117. // console.log('encryptS:',encryptS);
  118. // data = aesUtil.decrypt(data.data.data, rsaUtil.decrypt(data.data.aesKey, window.jsPrivateKey));
  119. // todo 处理token过期操作?
  120. // 301,302,303,304
  121. let _response = JSON.parse(response);
  122. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  123. console.log("token异常" + _response.msg);
  124. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  125. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  126. let _pause = cc.instantiate(texture);
  127. let _uiCamera = cc.find("Canvas/UICamera");
  128. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  129. _pause.zIndex = 999;
  130. let DetailLabel = _pause.getChildByName('DetailLabel');
  131. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  132. setTimeout(() => {
  133. cc.game.pause();
  134. }, 60)
  135. });
  136. return;
  137. }
  138. if (404 === _response.code) {
  139. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  140. let _pause = cc.instantiate(texture);
  141. let _uiCamera = cc.find("Canvas/UICamera");
  142. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  143. _pause.zIndex = 999;
  144. let DetailLabel = _pause.getChildByName('DetailLabel');
  145. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  146. setTimeout(() => {
  147. cc.game.pause();
  148. }, 60)
  149. });
  150. return;
  151. }
  152. // let httpStatus = xhr.statusText;
  153. if (callback)
  154. callback(true, _response);
  155. notifyCenter.emit("netSuccess", _response);
  156. } else {
  157. console.error("访问:" + url + "失败!");
  158. let _response = null;
  159. if (typeof response.value == 'string' && !response.value) {
  160. _response = JSON.parse(response);
  161. }
  162. if (callback)
  163. callback(false, _response);
  164. notifyCenter.emit("netError", _response);
  165. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  166. GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  167. } else {
  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 = "网络请求失败!";
  175. setTimeout(() => {
  176. _pause.destroy();
  177. }, 1000)
  178. });
  179. }
  180. }
  181. }
  182. };
  183. xhr.send();
  184. },
  185. //Post请求
  186. post(url, param, callback) {
  187. url = this.baseUrl + url;
  188. var xhr = cc.loader.getXMLHttpRequest();
  189. let dataStr = '';
  190. Object.keys(param).forEach(key => {
  191. dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
  192. })
  193. if (dataStr !== '') {
  194. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  195. }
  196. xhr.open("POST", url, true);
  197. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  198. if (this.token) {
  199. xhr.setRequestHeader("Authorization", this.token);
  200. }
  201. xhr.onreadystatechange = function () {
  202. if (xhr.readyState === 4) {
  203. let response = xhr.responseText;
  204. if (xhr.status >= 200 && xhr.status < 300) {
  205. let _response = JSON.parse(response);
  206. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  207. console.log("token异常" + _response.msg);
  208. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  209. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  210. let _pause = cc.instantiate(texture);
  211. let _uiCamera = cc.find("Canvas/UICamera");
  212. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  213. _pause.zIndex = 999;
  214. let DetailLabel = _pause.getChildByName('DetailLabel');
  215. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  216. setTimeout(() => {
  217. cc.game.pause();
  218. }, 60)
  219. });
  220. return;
  221. }
  222. if (404 === _response.code) {
  223. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  224. let _pause = cc.instantiate(texture);
  225. let _uiCamera = cc.find("Canvas/UICamera");
  226. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  227. _pause.zIndex = 999;
  228. let DetailLabel = _pause.getChildByName('DetailLabel');
  229. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  230. setTimeout(() => {
  231. cc.game.pause();
  232. }, 60)
  233. });
  234. return;
  235. }
  236. // let httpStatus = xhr.statusText;
  237. if (callback)
  238. callback(true, _response);
  239. notifyCenter.emit("netSuccess", _response);
  240. } else {
  241. console.error("访问:" + url + "失败!");
  242. let _response = null;
  243. if (typeof response.value == 'string' && !response.value) {
  244. _response = JSON.parse(response);
  245. }
  246. if (callback)
  247. callback(false, _response);
  248. notifyCenter.emit("netError", _response);
  249. if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
  250. GlobalD.GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
  251. } else {
  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 = "网络请求失败!";
  259. setTimeout(() => {
  260. _pause.destroy();
  261. }, 1000)
  262. });
  263. }
  264. }
  265. }
  266. };
  267. xhr.send(dataStr);
  268. },
  269. // getKey(){
  270. // let aesKey = aesUtil.genKey();
  271. // console.log('aesKey:',aesKey);
  272. // }
  273. init(id, callback: Function, target: any) {
  274. if (this.ws != null) return;
  275. // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
  276. // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
  277. console.log("utils.token:", utils.token);
  278. this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
  279. this.ws.onopen = (event: Event) => {
  280. callback.call(target, "登录成功");
  281. }
  282. this.ws.onmessage = (event: MessageEvent) => {
  283. callback.call(target, event.data);
  284. }
  285. this.ws.onerror = function (e) {
  286. console.error("WebSocket连接发生错误");
  287. };
  288. },
  289. sendMsg(data: string) {
  290. if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
  291. this.ws.send(data);
  292. }
  293. };
  294. /**
  295. * 加解密操作简单封装一下
  296. */
  297. // let aesUtil = {
  298. // //获取key,
  299. // genKey : function (length = 16) {
  300. // let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  301. // let str = "";
  302. // for (let i = 0; i < length; i++) {
  303. // str = str + random.charAt(Math.random() * random.length)
  304. // }
  305. // return str;
  306. // },
  307. // //加密
  308. // encrypt : function (plaintext,key) {
  309. // if (plaintext instanceof Object) {
  310. // //JSON.stringify
  311. // plaintext = JSON.stringify(plaintext)
  312. // }
  313. // let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  314. // return encrypted.toString();
  315. // },
  316. // //解密
  317. // decrypt : function (ciphertext,key) {
  318. // let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  319. // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
  320. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  321. // //JSON.parse
  322. // decString = JSON.parse(decString);
  323. // }
  324. // return decString;
  325. // }
  326. // };
  327. // let rsaUtil = {
  328. // //RSA 位数,这里要跟后端对应
  329. // bits: 1024,
  330. // //当前JSEncrypted对象
  331. // thisKeyPair: {},
  332. // //生成密钥对(公钥和私钥)
  333. // genKeyPair: function (bits = rsaUtil.bits) {
  334. // let genKeyPair = {};
  335. // rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});
  336. // //获取私钥
  337. // genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();
  338. // //获取公钥
  339. // genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();
  340. // return genKeyPair;
  341. // },
  342. // //公钥加密
  343. // encrypt: function (plaintext, publicKey) {
  344. // if (plaintext instanceof Object) {
  345. // //1、JSON.stringify
  346. // plaintext = JSON.stringify(plaintext)
  347. // }
  348. // publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
  349. // return rsaUtil.thisKeyPair.encrypt(plaintext);
  350. // },
  351. // //私钥解密
  352. // decrypt: function (ciphertext, privateKey) {
  353. // privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
  354. // let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
  355. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  356. // //JSON.parse
  357. // decString = JSON.parse(decString);
  358. // }
  359. // return decString;
  360. // }
  361. // };
  362. export { utils as default };