netUtils.ts 17 KB

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