| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- import notifyCenter from "./Comming/NotificationCenter";
- // import CryptoJS from "./encrypt/cryptojs";
- // import JSEncrypt from "./encrypt/jsencrypt";
- //通用工具函数类
- var utils = {
- version: "0.15",
- // baseUrl: "https://www.yuyekeji.cn/game/",
- // baseUrl: "http://127.0.0.1:26001/api_dapp/game/",
- // baseUrl: "https://www.yuyekeji.cn/api_dapp/game/",
- baseUrl: window['dappHost'] + '/api_dapp/game/',
- api: {
- //获取public 和 系统设置
- publicKeyAndSys: 'comUsers/publicKeyAndSys',
- // /**
- // * @deprecated 用loginTokenAndVerification 替代
- // */
- // loginToken: 'comUsers/loginToken',
- loginTokenAndVerification: 'comUsers/loginTokenAndVerification',
- //平台账户相关信息
- userInfo: 'comUsers/getUserInfo',
- userSnbInfo: 'comUsers/getUserSnb',
- //角色的信息
- playerPullInfo: 'comPlayers/playerPullInfo',
- //获取玩家属性
- playerAttribute: 'comPlayersAttri/getPlayerAttribute',
- /**
- * 获取是否租赁过的状态
- */
- playerExchangeState: 'comPlayers/getPlayerExchangeState',
- //获取游戏config土地列表
- landConfig: 'configLand/getList',
- //获取用户已经租赁的土地
- userLandList: 'comPlayerLand/getList', /*** disater dapp 调用,不用显示ui*/
- //获取用户土地信息和一个租赁状态
- userLandAndCanStealList: 'comPlayerLand/getCanStealDetailList', /*** disater 对方玩家,不用显示ui*/
- //获取用户可以偷取的列表信息
- canStealUserList: 'comPlayerLand/getCanStealUserList',
- /**
- * 新增灾难部分接口
- */
- //灾难接口
- disasterHistory: 'comPlayerLand/getDisasterHistory',
- //获取防护装备
- getDisasterProtectedMap: 'comPlayerLand/getDisasterMap',
- //获取土地信息
- landState: 'comPlayerLand/getState',
- //种植
- plant: 'comPlayerLand/plant', /*** disater 种植完后,直接处理一个初始灾难*/
- //种子
- mallSeed: 'comMallSeed/getMallSeed',
- /**
- * 用钻石兑换一包种子
- */
- exchangeSeeds: 'comMallSeed/exchangeSeeds',
- //仓库种子和果实
- getSeedAndFruit: 'comPlayerGoods/getSeedAndFruit',
- //背包的种子数量
- getSeedState: 'comPlayerGoods/getSeedState',
- //收取果实
- addFruit: 'comPlayerGoods/addFruit',
- //一键偷取全部果实
- stealAllFruit: 'comPlayerGoods/stealAllFruit',
- //单个收取
- stealFruit: 'comPlayerGoods/stealFruit',
- //出售果实
- saleFruit: 'comPlayerGoods/saleFruit',
- //赠送果实
- grantFruit: 'comPlayerGoods/grantFruit',
- //神农呗购买种子
- snbBuySeeds: 'comMallSeed/snbBuySeeds',
- //获取操作的snb日志
- snbList: 'comSnbTran/getList',
- //买狗和打狗棒
- addEquipment: 'comPlayerDog/addEquipment',
- addFood: 'comPlayerDog/addFood',
- getEquipmentByType: 'comPlayerDog/getEquipmentByType',
- getListEquipment: 'comPlayerDog/getListEquipment',
- //获取狗粮列表
- getMallFoodList: 'comMallFood/getMallFoodList',
- //是否显示狗
- setDogShowState: 'comPlayerDog/setDogShowState',
- //商城装备列表
- getMallEquipmentList: 'comMallOther/getMallEquipmentList',
- /**
- * 模块10 返还snb
- */
- //说明:返回当前userId是否在领取SNB名单中,如果在名单中通过计算可算出进度
- getCntToSnb: 'comCntToSnb/get',
- //说明:领取SNB接口,需要提前导入数据到com_cnt_to_snb表,点击领取按钮后,后端自动计算本次可领取的SNB数量,Status为0不可领取
- receiveCntToSnb: 'comCntToSnb/receive',
- /**
- * 审核snb
- */
- //获取申请的page
- getSnbApplyPage: 'comSnbApply/getPage',
- //提交申请
- applySnbToCnt: 'comSnbApply/applySnbToCnt',
- //校验申请
- checkApplySnbToCnt: 'comSnbApply/checkApplySnbToCnt',
- /**
- * 模块3:工具功能模块
- */
- getTools: 'land/tools',
- //使用工具
- postUseLuckyTools: 'land/tools',
- getLevel: 'land/level',
- //升级土地
- postLandLevelUp: 'land/level',
- //幸运值兑换snb
- luckToSnb: 'land/snb',
- /**
- * 牧场区域
- *
- */
- //获取租赁机会,以金币形式表现
- getAnimalTimes: 'comPlayerCultivate/getTimes',
- //解锁某个土地 【牧场养殖渔场】
- payAnimalLand:'comPlayerCultivate/payLand',
- //喂养土地上的动物
- buyAnimalFood:'comPlayerCultivate/buyAnimalFood',
- //修改土地倍数
- multipleAnimalLand:'comPlayerCultivate/multipleLand',
- //兑换种子
- playerScoreExchange: 'comPlayerScore/exchange',
- //获取符合条件的种子
- playerScoreSeeds:'comPlayerScore/getSeeds',
- },
- /** 登录获取的token */
- token: null,
- /** 后端RSA公钥 */
- javaPublicKey: null,
- /** api加密开关 */
- sysApiEncrypt: null,
- /** 设置token格式 */
- setToken(value) {
- // "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q"
- this.token = "Bearer " + value;
- },
- /**设置一个错误token测试 */
- onTestToken() {
- this.token = "Bearer " + "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMDAyIiwiZXhwIjoxNjQyNDUyNjU2LCJpYXQiOjE2NDI0NDU0NTZ9.Wr-u0KIa94_-yJjf28sj2znLmU_NwHpFaAaE_5rQLdUkYQGAHn-kMq2fdQHk_XwMrG71A2vzgz6BCmJtI8cL9Q";
- },
- setJavaPublicKeyAndSysApiEncrypt(javaPublicKey, sysApiEncrypt) {
- this.javaPublicKey = javaPublicKey;
- this.sysApiEncrypt = sysApiEncrypt;
- },
- get(url, params, callback) {
- let dataStr = '';
- Object.keys(params).forEach(key => {
- dataStr += key + '=' + encodeURIComponent(params[key]) + '&';
- })
- if (dataStr !== '') {
- dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
- url = url + '?' + dataStr;
- }
- url = this.baseUrl + url;
- let xhr = cc.loader.getXMLHttpRequest();
- xhr.open("GET", url, true);
- xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
- if (this.token) {
- xhr.setRequestHeader("Authorization", this.token);
- }
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- let response = xhr.responseText;
- if (xhr.status >= 200 && xhr.status < 300) {
- // let aesKeyS = aesUtil.genKey();
- // let encryptS = aesUtil.encrypt(response, aesKeyS);
- // let aesKeyE = rsaUtil.encrypt(aesKeyS, sessionStorage.getItem('javaPublicKey')),//后端RSA公钥加密后的AES的key
- // console.log('aesKeyS:',aesKeyS);
- // console.log('encryptS:',encryptS);
- // data = aesUtil.decrypt(data.data.data, rsaUtil.decrypt(data.data.aesKey, window.jsPrivateKey));
- // todo 处理token过期操作?
- // 301,302,303,304
- let _response = JSON.parse(response);
- if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
- console.log("token异常" + _response.msg);
- //这里要处理重新登录请求了,让用户刷新浏览器重新登录
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
- setTimeout(() => {
- cc.game.pause();
- }, 60)
- });
- return;
- }
- if (404 === _response.code) {
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = _response.data.msg;
- setTimeout(() => {
- cc.game.pause();
- }, 60)
- });
- return;
- }
- // let httpStatus = xhr.statusText;
- if (callback)
- callback(true, _response);
- notifyCenter.emit("netSuccess", _response);
- } else {
- console.error("访问:" + url + "失败!");
- let _response = null;
- if (typeof response == 'string' && !response) {
- _response = JSON.parse(response);
- }
- if (callback)
- callback(false, _response);
- notifyCenter.emit("netError", _response);
- if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
- window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
- } else {
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = "网络请求失败!";
- setTimeout(() => {
- _pause.destroy();
- }, 1000)
- });
- }
- }
- }
- };
- xhr.send();
- },
- //Post请求
- post(url, param, callback) {
- url = this.baseUrl + url;
- var xhr = cc.loader.getXMLHttpRequest();
- let dataStr = '';
- Object.keys(param).forEach(key => {
- dataStr += key + '=' + encodeURIComponent(param[key]) + '&';
- })
- if (dataStr !== '') {
- dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
- }
- xhr.open("POST", url, true);
- xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- if (this.token) {
- xhr.setRequestHeader("Authorization", this.token);
- }
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4) {
- let response = xhr.responseText;
- if (xhr.status >= 200 && xhr.status < 300) {
- let _response = JSON.parse(response);
- if (301 === _response.code || 302 === _response.code || 303 === _response.code || 304 === _response.code) {
- console.log("token异常" + _response.msg);
- //这里要处理重新登录请求了,让用户刷新浏览器重新登录
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = "游戏登录失效,请重新刷新页面登录!";
- setTimeout(() => {
- cc.game.pause();
- }, 60)
- });
- return;
- }
- if (404 === _response.code) {
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = _response.data.msg;
- setTimeout(() => {
- cc.game.pause();
- }, 60)
- });
- return;
- }
- // let httpStatus = xhr.statusText;
- if (callback)
- callback(true, _response);
- notifyCenter.emit("netSuccess", _response);
- } else {
- console.error("访问:" + url + "失败!");
- let _response = null;
- if (typeof response == 'string' && !response) {
- _response = JSON.parse(response);
- }
- if (callback)
- callback(false, _response);
- notifyCenter.emit("netError", _response);
- if (window['GlobalD'].GameData && window['GlobalD'].GameData.getToast()) {
- window['GlobalD'].GameData.showToast(cc.find("Canvas/UICamera"), "网络请求失败!", 1);
- } else {
- cc.loader.loadRes("prefab/gameToast", (err, texture) => {
- let _pause = cc.instantiate(texture);
- let _uiCamera = cc.find("Canvas/UICamera");
- _pause.parent = _uiCamera ? _uiCamera : cc.find("Canvas");
- _pause.zIndex = 999;
- let DetailLabel = _pause.getChildByName('DetailLabel');
- DetailLabel.getComponent(cc.Label).string = "网络请求失败!";
- setTimeout(() => {
- _pause.destroy();
- }, 1000)
- });
- }
- }
- }
- };
- xhr.send(dataStr);
- },
- // getKey(){
- // let aesKey = aesUtil.genKey();
- // console.log('aesKey:',aesKey);
- // }
- init(id, callback: Function, target: any) {
- if (this.ws != null) return;
- // https://www.yuyekeji.cn/api_dapp/index 192.168.0.106:26001
- // wss://www.yuyekeji.cn/api_dapp/websocket/dappBack/
- console.log("utils.token:", utils.token);
- this.ws = new WebSocket(window['dappWss'] + id, ["11"]);
- this.ws.onopen = (event: Event) => {
- callback.call(target, "登录成功");
- }
- this.ws.onmessage = (event: MessageEvent) => {
- callback.call(target, event.data);
- }
- this.ws.onerror = function (e) {
- console.error("WebSocket连接发生错误");
- };
- },
- sendMsg(data: string) {
- if (this.ws != null && this.ws.readyState != WebSocket.OPEN) return;
- this.ws.send(data);
- }
- };
- /**
- * 加解密操作简单封装一下
- */
- // let aesUtil = {
- // //获取key,
- // genKey : function (length = 16) {
- // let random = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
- // let str = "";
- // for (let i = 0; i < length; i++) {
- // str = str + random.charAt(Math.random() * random.length)
- // }
- // return str;
- // },
- // //加密
- // encrypt : function (plaintext,key) {
- // if (plaintext instanceof Object) {
- // //JSON.stringify
- // plaintext = JSON.stringify(plaintext)
- // }
- // let encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(plaintext), CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
- // return encrypted.toString();
- // },
- // //解密
- // decrypt : function (ciphertext,key) {
- // let decrypt = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(key), {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
- // let decString = CryptoJS.enc.Utf8.stringify(decrypt).toString();
- // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
- // //JSON.parse
- // decString = JSON.parse(decString);
- // }
- // return decString;
- // }
- // };
- // let rsaUtil = {
- // //RSA 位数,这里要跟后端对应
- // bits: 1024,
- // //当前JSEncrypted对象
- // thisKeyPair: {},
- // //生成密钥对(公钥和私钥)
- // genKeyPair: function (bits = rsaUtil.bits) {
- // let genKeyPair = {};
- // rsaUtil.thisKeyPair = new JSEncrypt({default_key_size: bits});
- // //获取私钥
- // genKeyPair.privateKey = rsaUtil.thisKeyPair.getPrivateKey();
- // //获取公钥
- // genKeyPair.publicKey = rsaUtil.thisKeyPair.getPublicKey();
- // return genKeyPair;
- // },
- // //公钥加密
- // encrypt: function (plaintext, publicKey) {
- // if (plaintext instanceof Object) {
- // //1、JSON.stringify
- // plaintext = JSON.stringify(plaintext)
- // }
- // publicKey && rsaUtil.thisKeyPair.setPublicKey(publicKey);
- // return rsaUtil.thisKeyPair.encrypt(plaintext);
- // },
- // //私钥解密
- // decrypt: function (ciphertext, privateKey) {
- // privateKey && rsaUtil.thisKeyPair.setPrivateKey(privateKey);
- // let decString = rsaUtil.thisKeyPair.decrypt(ciphertext);
- // if(decString.charAt(0) === "{" || decString.charAt(0) === "[" ){
- // //JSON.parse
- // decString = JSON.parse(decString);
- // }
- // return decString;
- // }
- // };
- export { utils as default };
|