const ResponseStateCode = require('../utils/GameEnum').ResponseStateCode; var Promise = require('../lib/es6-promise').Promise; class Api { static createImageFromUrl(avatarUrl, success, fail) { if (avatarUrl) { var index = avatarUrl.indexOf('https:'); var httpIndex = avatarUrl.indexOf('http:'); if (index === 0 || httpIndex === 0) { //以'https:'开头 } else { avatarUrl = 'https:' + avatarUrl; } if (window.wx != undefined) { try { let image = wx.createImage(); image.onload = () => { try { let texture = new cc.Texture2D(); texture.initWithElement(image); texture.handleLoadedTexture(); success(new cc.SpriteFrame(texture)) } catch (e) { cc.log(e); cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => { success(spriteFrame); }); } }; image.src = avatarUrl; } catch (e) { cc.log(e); cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => { success(spriteFrame); }); } } else { cc.loader.load({ url: avatarUrl, type: 'jpg' }, (err, texture) => { if (err === undefined || err === null) { success(new cc.SpriteFrame(texture)); } else { cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => { success(spriteFrame); }); } }); } } else { cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => { success(spriteFrame); }); } } /** * get请求对外暴露的方法 * @param {object} requestBody 请求body * @param {string} requestBody.url 请求地址 * @param {object} requestBody.data 请求发送的data * @param {function} requestBody.success 请求成功的回调 * @param {function} requestBody.fail 请求失败的回调 */ static httpGet(requestBody) { /// 如果是qq游戏那么做特殊处理 requestBody.data = Api.baseParam(requestBody.data); requestBody.url = Api.requestUrl(requestBody.url); if (CC_QQPLAY) { /// 如果是get方式那么转变url if (requestBody.method == undefined || requestBody.method == 'GET') { // 将data对象直接拼接到url后面做参数 requestBody.url = Api.urlEncode(requestBody.url, requestBody.data); } } if (window.tt != undefined) { Api.ttGet(requestBody); } else if (CC_WECHATGAME) { Api.wxGet(requestBody); } else if (CC_QQPLAY) { Api.qqGet(requestBody); } else { Api.jsGet(requestBody); } } /** * post请求对外暴露的方法 * @param {*} requestBody */ static httpPost(requestBody) { if (window.tt != undefined) { requestBody.url = Api.requestUrl(requestBody.url); requestBody.data = Api.baseParam(requestBody.data); return Api.ttPost(requestBody); } else if (CC_WECHATGAME) { requestBody.url = Api.requestUrl(requestBody.url); requestBody.data = Api.baseParam(requestBody.data); return Api.wxPost(requestBody); } else if (CC_QQPLAY) { requestBody.url = Api.qqUrlHandle(requestBody.url); requestBody.url = Api.requestUrl(requestBody.url); return Api.qqPost(requestBody); } else { requestBody.url = Api.requestUrl(requestBody.url); requestBody.data = Api.baseParam(requestBody.data); return Api.jsPost(requestBody); } } /// 在最后一个/前面加上/qq static qqUrlHandle(url) { let urlArr = url.split('/'); let newUrl = ''; let arrLen = urlArr.length; for (let i = 0; i < arrLen; ++i) { /// 如果是到了最后一个 if (i == arrLen - 1) { newUrl += '/qq'; } if (i == 0) { continue; } newUrl += '/'; newUrl += urlArr[i]; } return newUrl; } static wxGet(requestBody) { let onSuccess = requestBody.success; let onFail = requestBody.fail; let onComplete = requestBody.complete; wx.request({ url: requestBody.url, data: requestBody.data, method: requestBody.method === undefined ? 'GET' : 'POST', header: requestBody.header === undefined ? {} : requestBody.header, success: (res) => { //直接处理登录失效的逻辑 if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); return; } if (res.data.code === ResponseStateCode.OK) { if (onSuccess != undefined) { onSuccess(res.data.data); } } else { if (onFail != undefined) { onFail(res.data.code, res.data.msg); } } }, fail: (res) => { console.log('wxGet fail: ' + res); if (onFail != undefined) { onFail(-1, res.errMsg); } }, complete: onComplete, }); } //头条 static ttGet(requestBody) { let onSuccess = requestBody.success; let onFail = requestBody.fail; let onComplete = requestBody.complete; tt.request({ url: requestBody.url, data: requestBody.data, method: requestBody.method === undefined ? 'GET' : 'POST', header: requestBody.header === undefined ? {} : requestBody.header, success: (res) => { //直接处理登录失效的逻辑 if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); return; } if (res.data.code === ResponseStateCode.OK) { if (onSuccess != undefined) { onSuccess(res.data.data); } } else { if (onFail != undefined) { onFail(res.data.code, res.data.msg); } } }, fail: (res) => { console.log('wxGet fail: ' + res); if (onFail != undefined) { onFail(-1, res.errMsg); } }, complete: onComplete, }); } static wxPost(requestBody) { requestBody.header = { "Content-Type": "application/x-www-form-urlencoded" }; requestBody.method = 'POST'; Api.wxGet(requestBody); } static ttPost(requestBody) { requestBody.header = { "Content-Type": "application/x-www-form-urlencoded" }; requestBody.method = 'POST'; Api.ttGet(requestBody); } static qqGet(requestBody) { requestBody.header = { 'Referer': 'https://hudong.qq.com', 'User-Agent': 'brick-client', 'Content-Type': 'application/json' }; let onSuccess = requestBody.success; let onFail = requestBody.fail; let data = requestBody.data; /// 如果是post方式 if (data != undefined && requestBody.method == 'POST') { data = JSON.stringify(data); } else { data = ''; } let method = requestBody.method === undefined ? 'GET' : 'POST'; let url = requestBody.url; // let url = "https://test-api-taptap.duowan.com/room/reportGold1"; BK.Http.request({ url: url, body: data, method: method, headers: requestBody.header, success: (res) => { //直接处理登录失效的逻辑 /// 如果请求成功 if (res.statusCode === 200) { let bodyStr = res.text(); let bodyObjct = JSON.parse(bodyStr); if (bodyObjct == undefined) { if (onFail != undefined) { onFail(res.statusCode, '请求失败'); } return; } console.log('url :' + url, 'res: ' + res); if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); return; } if (bodyObjct.code === ResponseStateCode.OK) { if (onSuccess != undefined) { onSuccess(bodyObjct.data); } } else { if (onFail != undefined) { onFail(bodyObjct.code, bodyObjct.msg); // GameGlobal.commonAlert.showCommonErrorAlert('url' + url + ' login error code: ' + errCode + 'login error msg: ' + errMsg); } } } else { console.log('response error statusCode' + res.statusCode); if (onFail != undefined) { onFail(res.statusCode, '请求失败'); } } }, fail: (res) => { console.log('qqGet fail: ' + res, 'url : ' + url, 'res : ' + res); if (onFail != undefined) { onFail(-1, res.msg); } }, }); } static qqPost(requestBody) { requestBody.method = 'POST'; /// 添加post公共参数 requestBody.url = Api.urlEncode(requestBody.url, Api.baseParam({})); Api.qqGet(requestBody); } static jsGet(requestBody) { let url = requestBody.url; let data = requestBody.data; url = url + "?"; for (var key in data) { url = url + key + '=' + data[key] + '&'; } url = url.substr(0, url.length - 1) var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete); xhr.open("GET", url, true); xhr.send(); } static jsPost(requestBody) { let data = requestBody.data; var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete); xhr.open("POST", requestBody.url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); let formData = new String(); for (var key in data) { formData = formData + key + '=' + data[key] + "&"; } xhr.send(formData.substr(0, formData.length - 1)); } static jsBaseRequest(onSuccess, onFail, onComplete) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) { // console.log('response:' + xhr.responseText); var response = JSON.parse(xhr.responseText); if (response.code == ResponseStateCode.OK) { if (onSuccess != undefined) { onSuccess(response.data, response.msg); } } else { if (onFail != undefined) { onFail(response.code, response.msg) } } if (onComplete != undefined) { onComplete(); } } }; return xhr; } /** * get请求对外暴露的方法 * @param {*} requestBody */ static httpGetPromise(url, data) { url = Api.requestUrl(url); data = Api.baseParam(data); if (window.tt != undefined) { return Api.ttGetP(url, data); }else if (CC_WECHATGAME) { return Api.wxGetP(url, data); } else if (CC_QQPLAY) { return Api.qqGetP(url, data); } else { return Api.jsGetP(url, data); } } /** * post请求对外暴露的方法 * @param {*} requestBody */ static httpPostPromise(url, data) { url = Api.requestUrl(url); data = Api.baseParam(data); if (window.tt != undefined) { return Api.ttPostP(url, data); } if (CC_WECHATGAME) { return Api.wxPostP(url, data); } else if (CC_QQPLAY) { return Api.qqPostP(url, data); } else { return Api.jsPostP(url, data); } } static wxGetP(url, data) { return Api.wxRequestPromise(url, data, 'GET'); } static wxPostP(url, data) { let header = { "Content-Type": "application/x-www-form-urlencoded" }; return Api.wxRequestPromise(url, data, 'POST', header); } static wxRequestPromise(url, data, method, header) { return new Promise((resolve, reject) => { wx.request({ url: url, data: data, method: method, headers: header === undefined ? {} : header, success: (res) => { //直接处理登录失效的逻辑 if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); reject(res.data); } if (res.data.code === ResponseStateCode.OK) { resolve(res.data); } else { reject(res.data); } }, fail: (res) => { reject({ code: -1, msg: '微信登录接口调用失败' }); }, complete: {}, }); }); } //头条 static ttGetP(url, data) { return Api.ttRequestPromise(url, data, 'GET'); } static ttPostP(url, data) { let header = { "Content-Type": "application/x-www-form-urlencoded" }; return Api.ttRequestPromise(url, data, 'POST', header); } static ttRequestPromise(url, data, method, header) { return new Promise((resolve, reject) => { tt.request({ url: url, data: data, method: method, headers: header === undefined ? {} : header, success: (res) => { //直接处理登录失效的逻辑 if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); reject(res.data); } if (res.data.code === ResponseStateCode.OK) { resolve(res.data); } else { reject(res.data); } }, fail: (res) => { reject({ code: -1, msg: '头条登录接口调用失败' }); }, complete: {}, }); }); } //QQ static qqGetP(url, data) { url = Api.urlEncode(url, data); return Api.qqRequestPromise(url, '', 'GET'); } static qqPostP(url, data) { if (data != null || data != undefined) { data = JSON.stringify(data); } return Api.qqRequestPromise(url, data, 'POST'); } static qqRequestPromise(url, data, method) { return new Promise((resolve, reject) => { BK.Http.request({ url: url, body: data, method: method, headers: { 'Content-Type': 'application/json' }, success: (res) => { /// 如果请求成功 console.log('url :' + url, 'res: ' + res); if (res.statusCode === 200) { let bodyStr = res.text(); let bodyObjct = JSON.parse(bodyStr); if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) { GameGlobal.needLogin = true; cc.director.loadScene('login'); return; } if (bodyObjct.code === ResponseStateCode.OK) { resolve(bodyObjct); } else { reject({ code: bodyObjct.code, msg: bodyObjct.msg }); } } else { console.log('response error statusCode' + res.statusCode); reject({ code: res.statusCode, msg: 'qq登录接口调用失败' }); } }, fail: (res) => { console.log('url :' + url, 'res: ' + res); reject({ code: -1, msg: 'qq登录接口调用失败' }); }, // complete: {}, }); }); } static jsGetP(url, data) { return new Promise((resolve, reject) => { url = url + "?"; for (var key in data) { url = url + key + '=' + data[key] + '&'; } url = url.substr(0, url.length - 1); var xhr = Api.jsBaseRequestP(resolve, reject); xhr.open("GET", url, true); xhr.send(); }); } static jsPostP(url, data) { return new Promise((resolve, reject) => { var xhr = Api.jsBaseRequestP(resolve, reject); xhr.open("POST", url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); let formData = new String(); for (var key in data) { formData = formData + key + '=' + data[key] + "&"; } xhr.send(formData.substr(0, formData.length - 1)); }); } static jsBaseRequestP(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) { // console.log('response:' + xhr.responseText); var response = JSON.parse(xhr.responseText); if (response.code == ResponseStateCode.OK) { resolve(response); } else { reject(response); } } }; return xhr; } /** * 将每个接口都需要的公用参数都放到这里 * @param target [Object] 请求参数 */ static baseParam(target) { if (target === undefined) { target = {}; } target.thirdType = 1; target.channel = GameGlobal.channel; target.ver = GameGlobal.ver; target.os = GameGlobal.os; target.uid = GameGlobal.user ? GameGlobal.user.uid : ''; target.token = GameGlobal.user ? GameGlobal.user.token : ''; return target; } /** * 自动拼接请求接口 * @param targetUrl [string] 请求接口 */ static requestUrl(targetUrl) { var host = GameGlobal.debug ? 'https://test-api-taptap.duowan.com' : 'https://api-taptap.duowan.com'; if (CC_QQPLAY) { host = GameGlobal.debug ? 'https://test-api-taptap.duowan.com' : 'https://qq-api-taptap.duowan.com'; } // let host = GameGlobal.debug ? 'http://172.16.15.196:8888' : 'https://api-allstar.duowan.com'; // let host = 'https://new-api-taptap.duowan.com'; return host + targetUrl; } static setRequestBody(url, data, success, fail) { let requestBody = { url: url, data: data, success: success, fail: fail, complete: () => { } }; return requestBody; } /// 将data对象拼接到url上做参数 static urlEncode(url, data) { if(typeof(url) == 'undefined' || url == null || url == '') { return ''; } if(typeof(data) == 'undefined' || data == null || typeof(data) != 'object') { return ''; } url += (url.indexOf("?") != -1) ? "" : "?"; for(var k in data) { url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(data[k]); } return url; } } module.exports = Api;