netUtils.ts 13 KB

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