netUtils.ts 14 KB

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