netUtils.ts 16 KB

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