netUtils.ts 14 KB

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