Api.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. const ResponseStateCode = require('../utils/GameEnum').ResponseStateCode;
  2. var Promise = require('../lib/es6-promise').Promise;
  3. class Api {
  4. static createImageFromUrl(avatarUrl, success, fail) {
  5. if (avatarUrl) {
  6. var index = avatarUrl.indexOf('https:');
  7. var httpIndex = avatarUrl.indexOf('http:');
  8. if (index === 0 || httpIndex === 0) {
  9. //以'https:'开头
  10. } else {
  11. avatarUrl = 'https:' + avatarUrl;
  12. }
  13. if (window.wx != undefined) {
  14. try {
  15. let image = wx.createImage();
  16. image.onload = () => {
  17. try {
  18. let texture = new cc.Texture2D();
  19. texture.initWithElement(image);
  20. texture.handleLoadedTexture();
  21. success(new cc.SpriteFrame(texture))
  22. } catch (e) {
  23. cc.log(e);
  24. cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => {
  25. success(spriteFrame);
  26. });
  27. }
  28. };
  29. image.src = avatarUrl;
  30. } catch (e) {
  31. cc.log(e);
  32. cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => {
  33. success(spriteFrame);
  34. });
  35. }
  36. } else {
  37. cc.loader.load({
  38. url: avatarUrl, type: 'jpg'
  39. }, (err, texture) => {
  40. if (err === undefined || err === null) {
  41. success(new cc.SpriteFrame(texture));
  42. } else {
  43. cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => {
  44. success(spriteFrame);
  45. });
  46. }
  47. });
  48. }
  49. } else {
  50. cc.loader.loadRes('./textures/common/default_avatar', cc.SpriteFrame, (err, spriteFrame) => {
  51. success(spriteFrame);
  52. });
  53. }
  54. }
  55. /**
  56. * get请求对外暴露的方法
  57. * @param {object} requestBody 请求body
  58. * @param {string} requestBody.url 请求地址
  59. * @param {object} requestBody.data 请求发送的data
  60. * @param {function} requestBody.success 请求成功的回调
  61. * @param {function} requestBody.fail 请求失败的回调
  62. */
  63. static httpGet(requestBody) {
  64. /// 如果是qq游戏那么做特殊处理
  65. requestBody.data = Api.baseParam(requestBody.data);
  66. requestBody.url = Api.requestUrl(requestBody.url);
  67. if (CC_QQPLAY) {
  68. /// 如果是get方式那么转变url
  69. if (requestBody.method == undefined || requestBody.method == 'GET') {
  70. // 将data对象直接拼接到url后面做参数
  71. requestBody.url = Api.urlEncode(requestBody.url, requestBody.data);
  72. }
  73. }
  74. if (CC_WECHATGAME) {
  75. Api.wxGet(requestBody);
  76. } else if (CC_QQPLAY) {
  77. Api.qqGet(requestBody);
  78. } else {
  79. Api.jsGet(requestBody);
  80. }
  81. }
  82. /**
  83. * post请求对外暴露的方法
  84. * @param {*} requestBody
  85. */
  86. static httpPost(requestBody) {
  87. if (CC_WECHATGAME) {
  88. requestBody.url = Api.requestUrl(requestBody.url);
  89. requestBody.data = Api.baseParam(requestBody.data);
  90. return Api.wxPost(requestBody);
  91. } else if (CC_QQPLAY) {
  92. requestBody.url = Api.qqUrlHandle(requestBody.url);
  93. requestBody.url = Api.requestUrl(requestBody.url);
  94. return Api.qqPost(requestBody);
  95. } else {
  96. requestBody.url = Api.requestUrl(requestBody.url);
  97. requestBody.data = Api.baseParam(requestBody.data);
  98. return Api.jsPost(requestBody);
  99. }
  100. }
  101. /// 在最后一个/前面加上/qq
  102. static qqUrlHandle(url) {
  103. let urlArr = url.split('/');
  104. let newUrl = '';
  105. let arrLen = urlArr.length;
  106. for (let i = 0; i < arrLen; ++i) {
  107. /// 如果是到了最后一个
  108. if (i == arrLen - 1) {
  109. newUrl += '/qq';
  110. }
  111. if (i == 0) {
  112. continue;
  113. }
  114. newUrl += '/';
  115. newUrl += urlArr[i];
  116. }
  117. return newUrl;
  118. }
  119. static wxGet(requestBody) {
  120. let onSuccess = requestBody.success;
  121. let onFail = requestBody.fail;
  122. let onComplete = requestBody.complete;
  123. wx.request({
  124. url: requestBody.url,
  125. data: requestBody.data,
  126. method: requestBody.method === undefined ? 'GET' : 'POST',
  127. header: requestBody.header === undefined ? {} : requestBody.header,
  128. success: (res) => {
  129. //直接处理登录失效的逻辑
  130. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  131. GameGlobal.needLogin = true;
  132. cc.director.loadScene('login');
  133. return;
  134. }
  135. if (res.data.code === ResponseStateCode.OK) {
  136. if (onSuccess != undefined) {
  137. onSuccess(res.data.data);
  138. }
  139. } else {
  140. if (onFail != undefined) {
  141. onFail(res.data.code, res.data.msg);
  142. }
  143. }
  144. },
  145. fail: (res) => {
  146. console.log('wxGet fail: ' + res);
  147. if (onFail != undefined) {
  148. onFail(-1, res.errMsg);
  149. }
  150. },
  151. complete: onComplete,
  152. });
  153. }
  154. static wxPost(requestBody) {
  155. requestBody.header = {
  156. "Content-Type": "application/x-www-form-urlencoded"
  157. };
  158. requestBody.method = 'POST';
  159. Api.wxGet(requestBody);
  160. }
  161. static qqGet(requestBody) {
  162. requestBody.header = {
  163. 'Referer': 'https://hudong.qq.com',
  164. 'User-Agent': 'brick-client',
  165. 'Content-Type': 'application/json'
  166. };
  167. let onSuccess = requestBody.success;
  168. let onFail = requestBody.fail;
  169. let data = requestBody.data;
  170. /// 如果是post方式
  171. if (data != undefined && requestBody.method == 'POST') {
  172. data = JSON.stringify(data);
  173. } else {
  174. data = '';
  175. }
  176. let method = requestBody.method === undefined ? 'GET' : 'POST';
  177. let url = requestBody.url;
  178. // let url = "https://test-api-taptap.duowan.com/room/reportGold1";
  179. BK.Http.request({
  180. url: url,
  181. body: data,
  182. method: method,
  183. headers: requestBody.header,
  184. success: (res) => {
  185. //直接处理登录失效的逻辑
  186. /// 如果请求成功
  187. if (res.statusCode === 200) {
  188. let bodyStr = res.text();
  189. let bodyObjct = JSON.parse(bodyStr);
  190. if (bodyObjct == undefined) {
  191. if (onFail != undefined) {
  192. onFail(res.statusCode, '请求失败');
  193. }
  194. return;
  195. }
  196. console.log('url :' + url, 'res: ' + res);
  197. if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) {
  198. GameGlobal.needLogin = true;
  199. cc.director.loadScene('login');
  200. return;
  201. }
  202. if (bodyObjct.code === ResponseStateCode.OK) {
  203. if (onSuccess != undefined) {
  204. onSuccess(bodyObjct.data);
  205. }
  206. } else {
  207. if (onFail != undefined) {
  208. onFail(bodyObjct.code, bodyObjct.msg);
  209. // GameGlobal.commonAlert.showCommonErrorAlert('url' + url + ' login error code: ' + errCode + 'login error msg: ' + errMsg);
  210. }
  211. }
  212. } else {
  213. console.log('response error statusCode' + res.statusCode);
  214. if (onFail != undefined) {
  215. onFail(res.statusCode, '请求失败');
  216. }
  217. }
  218. },
  219. fail: (res) => {
  220. console.log('qqGet fail: ' + res, 'url : ' + url, 'res : ' + res);
  221. if (onFail != undefined) {
  222. onFail(-1, res.msg);
  223. }
  224. },
  225. });
  226. }
  227. static qqPost(requestBody) {
  228. requestBody.method = 'POST';
  229. /// 添加post公共参数
  230. requestBody.url = Api.urlEncode(requestBody.url, Api.baseParam({}));
  231. Api.qqGet(requestBody);
  232. }
  233. static jsGet(requestBody) {
  234. let url = requestBody.url;
  235. let data = requestBody.data;
  236. url = url + "?";
  237. for (var key in data) {
  238. url = url + key + '=' + data[key] + '&';
  239. }
  240. url = url.substr(0, url.length - 1)
  241. var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
  242. xhr.open("GET", url, true);
  243. xhr.send();
  244. }
  245. static jsPost(requestBody) {
  246. let data = requestBody.data;
  247. var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
  248. xhr.open("POST", requestBody.url, true);
  249. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  250. let formData = new String();
  251. for (var key in data) {
  252. formData = formData + key + '=' + data[key] + "&";
  253. }
  254. xhr.send(formData.substr(0, formData.length - 1));
  255. }
  256. static jsBaseRequest(onSuccess, onFail, onComplete) {
  257. var xhr = new XMLHttpRequest();
  258. xhr.onreadystatechange = () => {
  259. if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
  260. // console.log('response:' + xhr.responseText);
  261. var response = JSON.parse(xhr.responseText);
  262. if (response.code == ResponseStateCode.OK) {
  263. if (onSuccess != undefined) {
  264. onSuccess(response.data, response.msg);
  265. }
  266. } else {
  267. if (onFail != undefined) {
  268. onFail(response.code, response.msg)
  269. }
  270. }
  271. if (onComplete != undefined) {
  272. onComplete();
  273. }
  274. }
  275. };
  276. return xhr;
  277. }
  278. /**
  279. * get请求对外暴露的方法
  280. * @param {*} requestBody
  281. */
  282. static httpGetPromise(url, data) {
  283. url = Api.requestUrl(url);
  284. data = Api.baseParam(data);
  285. if (CC_WECHATGAME) {
  286. return Api.wxGetP(url, data);
  287. } else if (CC_QQPLAY) {
  288. return Api.qqGetP(url, data);
  289. } else {
  290. return Api.jsGetP(url, data);
  291. }
  292. }
  293. /**
  294. * post请求对外暴露的方法
  295. * @param {*} requestBody
  296. */
  297. static httpPostPromise(url, data) {
  298. url = Api.requestUrl(url);
  299. data = Api.baseParam(data);
  300. if (CC_WECHATGAME) {
  301. return Api.wxPostP(url, data);
  302. } else if (CC_QQPLAY) {
  303. return Api.qqPostP(url, data);
  304. } else {
  305. return Api.jsPostP(url, data);
  306. }
  307. }
  308. static wxGetP(url, data) {
  309. return Api.wxRequestPromise(url, data, 'GET');
  310. }
  311. static wxPostP(url, data) {
  312. let header = {
  313. "Content-Type": "application/x-www-form-urlencoded"
  314. };
  315. return Api.wxRequestPromise(url, data, 'POST', header);
  316. }
  317. static wxRequestPromise(url, data, method, header) {
  318. return new Promise((resolve, reject) => {
  319. wx.request({
  320. url: url,
  321. data: data,
  322. method: method,
  323. headers: header === undefined ? {} : header,
  324. success: (res) => {
  325. //直接处理登录失效的逻辑
  326. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  327. GameGlobal.needLogin = true;
  328. cc.director.loadScene('login');
  329. reject(res.data);
  330. }
  331. if (res.data.code === ResponseStateCode.OK) {
  332. resolve(res.data);
  333. } else {
  334. reject(res.data);
  335. }
  336. },
  337. fail: (res) => {
  338. reject({
  339. code: -1,
  340. msg: '微信登录接口调用失败'
  341. });
  342. },
  343. complete: {},
  344. });
  345. });
  346. }
  347. static qqGetP(url, data) {
  348. url = Api.urlEncode(url, data);
  349. return Api.qqRequestPromise(url, '', 'GET');
  350. }
  351. static qqPostP(url, data) {
  352. if (data != null || data != undefined) {
  353. data = JSON.stringify(data);
  354. }
  355. return Api.qqRequestPromise(url, data, 'POST');
  356. }
  357. static qqRequestPromise(url, data, method) {
  358. return new Promise((resolve, reject) => {
  359. BK.Http.request({
  360. url: url,
  361. body: data,
  362. method: method,
  363. headers: {
  364. 'Content-Type': 'application/json'
  365. },
  366. success: (res) => {
  367. /// 如果请求成功
  368. console.log('url :' + url, 'res: ' + res);
  369. if (res.statusCode === 200) {
  370. let bodyStr = res.text();
  371. let bodyObjct = JSON.parse(bodyStr);
  372. if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) {
  373. GameGlobal.needLogin = true;
  374. cc.director.loadScene('login');
  375. return;
  376. }
  377. if (bodyObjct.code === ResponseStateCode.OK) {
  378. resolve(bodyObjct);
  379. } else {
  380. reject({
  381. code: bodyObjct.code,
  382. msg: bodyObjct.msg
  383. });
  384. }
  385. } else {
  386. console.log('response error statusCode' + res.statusCode);
  387. reject({
  388. code: res.statusCode,
  389. msg: 'qq登录接口调用失败'
  390. });
  391. }
  392. },
  393. fail: (res) => {
  394. console.log('url :' + url, 'res: ' + res);
  395. reject({
  396. code: -1,
  397. msg: 'qq登录接口调用失败'
  398. });
  399. },
  400. // complete: {},
  401. });
  402. });
  403. }
  404. static jsGetP(url, data) {
  405. return new Promise((resolve, reject) => {
  406. url = url + "?";
  407. for (var key in data) {
  408. url = url + key + '=' + data[key] + '&';
  409. }
  410. url = url.substr(0, url.length - 1);
  411. var xhr = Api.jsBaseRequestP(resolve, reject);
  412. xhr.open("GET", url, true);
  413. xhr.send();
  414. });
  415. }
  416. static jsPostP(url, data) {
  417. return new Promise((resolve, reject) => {
  418. var xhr = Api.jsBaseRequestP(resolve, reject);
  419. xhr.open("POST", url, true);
  420. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  421. let formData = new String();
  422. for (var key in data) {
  423. formData = formData + key + '=' + data[key] + "&";
  424. }
  425. xhr.send(formData.substr(0, formData.length - 1));
  426. });
  427. }
  428. static jsBaseRequestP(resolve, reject) {
  429. var xhr = new XMLHttpRequest();
  430. xhr.onreadystatechange = () => {
  431. if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
  432. // console.log('response:' + xhr.responseText);
  433. var response = JSON.parse(xhr.responseText);
  434. if (response.code == ResponseStateCode.OK) {
  435. resolve(response);
  436. } else {
  437. reject(response);
  438. }
  439. }
  440. };
  441. return xhr;
  442. }
  443. /**
  444. * 将每个接口都需要的公用参数都放到这里
  445. * @param target [Object] 请求参数
  446. */
  447. static baseParam(target) {
  448. if (target === undefined) {
  449. target = {};
  450. }
  451. target.thirdType = 1;
  452. target.channel = GameGlobal.channel;
  453. target.ver = GameGlobal.ver;
  454. target.os = GameGlobal.os;
  455. target.uid = GameGlobal.user ? GameGlobal.user.uid : '';
  456. target.token = GameGlobal.user ? GameGlobal.user.token : '';
  457. return target;
  458. }
  459. /**
  460. * 自动拼接请求接口
  461. * @param targetUrl [string] 请求接口
  462. */
  463. static requestUrl(targetUrl) {
  464. let host = GameGlobal.debug ? 'https://test-api-taptap.duowan.com' : 'https://api-taptap.duowan.com';
  465. // let host = GameGlobal.debug ? 'http://172.16.15.196:8888' : 'https://api-allstar.duowan.com';
  466. // let host = 'https://new-api-taptap.duowan.com';
  467. return host + targetUrl;
  468. }
  469. static setRequestBody(url, data, success, fail) {
  470. let requestBody = {
  471. url: url,
  472. data: data,
  473. success: success,
  474. fail: fail,
  475. complete: () => {
  476. }
  477. };
  478. return requestBody;
  479. }
  480. /// 将data对象拼接到url上做参数
  481. static urlEncode(url, data) {
  482. if(typeof(url) == 'undefined' || url == null || url == '') {
  483. return '';
  484. }
  485. if(typeof(data) == 'undefined' || data == null || typeof(data) != 'object') {
  486. return '';
  487. }
  488. url += (url.indexOf("?") != -1) ? "" : "?";
  489. for(var k in data) {
  490. url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(data[k]);
  491. }
  492. return url;
  493. }
  494. }
  495. module.exports = Api;