netUtils.ts 16 KB

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