netUtils.ts 16 KB

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