netUtils.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. notifyCenter.emit("netSuccess", _response);
  139. callback(true, _response);
  140. } else {
  141. callback(false, response);
  142. notifyCenter.emit("netError", JSON.parse(response));
  143. }
  144. }
  145. };
  146. xhr.send();
  147. },
  148. //Post请求
  149. post(url, param, callback) {
  150. url = this.baseUrl + url;
  151. var xhr = cc.loader.getXMLHttpRequest();
  152. let dataStr = '';
  153. Object.keys(param).forEach(key => {
  154. dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
  155. })
  156. if (dataStr !== '') {
  157. dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
  158. }
  159. xhr.open("POST", url, true);
  160. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  161. if (this.token) {
  162. xhr.setRequestHeader("Authorization", this.token);
  163. }
  164. xhr.onreadystatechange = function () {
  165. if (xhr.readyState === 4) {
  166. let response = xhr.responseText;
  167. if (xhr.status >= 200 && xhr.status < 300) {
  168. let _response = JSON.parse(response);
  169. if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
  170. console.log("token异常" + _response.msg);
  171. //这里要处理重新登录请求了,让用户刷新浏览器重新登录
  172. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  173. let _pause = cc.instantiate(texture);
  174. let _uiCamera = cc.find("Canvas/UICamera");
  175. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  176. _pause.zIndex = 999;
  177. let DetailLabel = _pause.getChildByName('DetailLabel');
  178. DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
  179. setTimeout(() => {
  180. cc.game.pause();
  181. }, 60)
  182. });
  183. return;
  184. }
  185. if (404 === _response.code) {
  186. cc.loader.loadRes("prefab/gameToast", (err, texture) => {
  187. let _pause = cc.instantiate(texture);
  188. let _uiCamera = cc.find("Canvas/UICamera");
  189. _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
  190. _pause.zIndex = 999;
  191. let DetailLabel = _pause.getChildByName('DetailLabel');
  192. DetailLabel.getComponent(cc.Label).string = _response.data.msg;
  193. setTimeout(() => {
  194. cc.game.pause();
  195. }, 60)
  196. });
  197. return;
  198. }
  199. // let httpStatus = xhr.statusText;
  200. notifyCenter.emit("netSuccess", _response);
  201. callback(true, _response);
  202. } else {
  203. callback(false, response);
  204. notifyCenter.emit("netError", JSON.parse(response));
  205. }
  206. }
  207. };
  208. xhr.send(dataStr);
  209. },
  210. // getKey(){
  211. // let aesKey = aesUtil.genKey();
  212. // console.log('aesKey:',aesKey);
  213. // }
  214. init(id, callback: Function, target: any) {
  215. if (this.ws != null) return;
  216. // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
  217. // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
  218. console.log("utils.token:", utils.token);
  219. this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
  220. this.ws.onopen = (event: Event) => {
  221. callback.call(target, "登录成功");
  222. }
  223. this.ws.onmessage = (event: MessageEvent) => {
  224. callback.call(target, event.data);
  225. }
  226. this.ws.onerror = function (e) {
  227. console.error("WebSocket连接发生错误");
  228. };
  229. },
  230. sendMsg(data: string) {
  231. if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
  232. this.ws.send(data);
  233. }
  234. };
  235. /**
  236. * 加解密操作简单封装一下
  237. */
  238. // let aesUtil = {
  239. // //获取key,
  240. // genKey : function (length = 16) {
  241. // let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  242. // let str = "";
  243. // for (let i = 0; i < length; i++) {
  244. // str = str + random.charAt(Math.random() * random.length)
  245. // }
  246. // return str;
  247. // },
  248. // //加密
  249. // encrypt : function (plaintext,key) {
  250. // if (plaintext instanceof Object) {
  251. // //JSON.stringify
  252. // plaintext = JSON.stringify(plaintext)
  253. // }
  254. // let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  255. // return encrypted.toString();
  256. // },
  257. // //解密
  258. // decrypt : function (ciphertext,key) {
  259. // let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
  260. // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
  261. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  262. // //JSON.parse
  263. // decString = JSON.parse(decString);
  264. // }
  265. // return decString;
  266. // }
  267. // };
  268. // let rsaUtil = {
  269. // //RSA 位数,这里要跟后端对应
  270. // bits: 1024,
  271. // //当前JSEncrypted对象
  272. // thisKeyPair: {},
  273. // //生成密钥对(公钥和私钥)
  274. // genKeyPair: function (bits = rsaUtil.bits) {
  275. // let genKeyPair = {};
  276. // rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});
  277. // //获取私钥
  278. // genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();
  279. // //获取公钥
  280. // genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();
  281. // return genKeyPair;
  282. // },
  283. // //公钥加密
  284. // encrypt: function (plaintext, publicKey) {
  285. // if (plaintext instanceof Object) {
  286. // //1、JSON.stringify
  287. // plaintext = JSON.stringify(plaintext)
  288. // }
  289. // publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
  290. // return rsaUtil.thisKeyPair.encrypt(plaintext);
  291. // },
  292. // //私钥解密
  293. // decrypt: function (ciphertext, privateKey) {
  294. // privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
  295. // let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
  296. // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
  297. // //JSON.parse
  298. // decString = JSON.parse(decString);
  299. // }
  300. // return decString;
  301. // }
  302. // };
  303. export { utils as default };