netUtils.ts 16 KB

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