Api.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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 (window.tt != undefined) {
  75. Api.ttGet(requestBody);
  76. } else if (CC_WECHATGAME) {
  77. Api.wxGet(requestBody);
  78. } else if (CC_QQPLAY) {
  79. Api.qqGet(requestBody);
  80. } else {
  81. Api.jsGet(requestBody);
  82. }
  83. }
  84. /**
  85. * post请求对外暴露的方法
  86. * @param {*} requestBody
  87. */
  88. static httpPost(requestBody) {
  89. if (window.tt != undefined) {
  90. requestBody.url = Api.requestUrl(requestBody.url);
  91. requestBody.data = Api.baseParam(requestBody.data);
  92. return Api.ttPost(requestBody);
  93. } else if (CC_WECHATGAME) {
  94. requestBody.url = Api.requestUrl(requestBody.url);
  95. requestBody.data = Api.baseParam(requestBody.data);
  96. return Api.wxPost(requestBody);
  97. } else if (CC_QQPLAY) {
  98. requestBody.url = Api.qqUrlHandle(requestBody.url);
  99. requestBody.url = Api.requestUrl(requestBody.url);
  100. return Api.qqPost(requestBody);
  101. } else {
  102. requestBody.url = Api.requestUrl(requestBody.url);
  103. requestBody.data = Api.baseParam(requestBody.data);
  104. return Api.jsPost(requestBody);
  105. }
  106. }
  107. /// 在最后一个/前面加上/qq
  108. static qqUrlHandle(url) {
  109. let urlArr = url.split('/');
  110. let newUrl = '';
  111. let arrLen = urlArr.length;
  112. for (let i = 0; i < arrLen; ++i) {
  113. /// 如果是到了最后一个
  114. if (i == arrLen - 1) {
  115. newUrl += '/qq';
  116. }
  117. if (i == 0) {
  118. continue;
  119. }
  120. newUrl += '/';
  121. newUrl += urlArr[i];
  122. }
  123. return newUrl;
  124. }
  125. static wxGet(requestBody) {
  126. let onSuccess = requestBody.success;
  127. let onFail = requestBody.fail;
  128. let onComplete = requestBody.complete;
  129. wx.request({
  130. url: requestBody.url,
  131. data: requestBody.data,
  132. method: requestBody.method === undefined ? 'GET' : 'POST',
  133. header: requestBody.header === undefined ? {} : requestBody.header,
  134. success: (res) => {
  135. //直接处理登录失效的逻辑
  136. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  137. GameGlobal.needLogin = true;
  138. cc.director.loadScene('login');
  139. return;
  140. }
  141. if (res.data.code === ResponseStateCode.OK) {
  142. if (onSuccess != undefined) {
  143. onSuccess(res.data.data);
  144. }
  145. } else {
  146. if (onFail != undefined) {
  147. onFail(res.data.code, res.data.msg);
  148. }
  149. }
  150. },
  151. fail: (res) => {
  152. console.log('wxGet fail: ' + res);
  153. if (onFail != undefined) {
  154. onFail(-1, res.errMsg);
  155. }
  156. },
  157. complete: onComplete,
  158. });
  159. }
  160. //头条
  161. static ttGet(requestBody) {
  162. let onSuccess = requestBody.success;
  163. let onFail = requestBody.fail;
  164. let onComplete = requestBody.complete;
  165. tt.request({
  166. url: requestBody.url,
  167. data: requestBody.data,
  168. method: requestBody.method === undefined ? 'GET' : 'POST',
  169. header: requestBody.header === undefined ? {} : requestBody.header,
  170. success: (res) => {
  171. //直接处理登录失效的逻辑
  172. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  173. GameGlobal.needLogin = true;
  174. cc.director.loadScene('login');
  175. return;
  176. }
  177. if (res.data.code === ResponseStateCode.OK) {
  178. if (onSuccess != undefined) {
  179. onSuccess(res.data.data);
  180. }
  181. } else {
  182. if (onFail != undefined) {
  183. onFail(res.data.code, res.data.msg);
  184. }
  185. }
  186. },
  187. fail: (res) => {
  188. console.log('wxGet fail: ' + res);
  189. if (onFail != undefined) {
  190. onFail(-1, res.errMsg);
  191. }
  192. },
  193. complete: onComplete,
  194. });
  195. }
  196. static wxPost(requestBody) {
  197. requestBody.header = {
  198. "Content-Type": "application/x-www-form-urlencoded"
  199. };
  200. requestBody.method = 'POST';
  201. Api.wxGet(requestBody);
  202. }
  203. static ttPost(requestBody) {
  204. requestBody.header = {
  205. "Content-Type": "application/x-www-form-urlencoded"
  206. };
  207. requestBody.method = 'POST';
  208. Api.ttGet(requestBody);
  209. }
  210. static qqGet(requestBody) {
  211. requestBody.header = {
  212. 'Referer': 'https://hudong.qq.com',
  213. 'User-Agent': 'brick-client',
  214. 'Content-Type': 'application/json'
  215. };
  216. let onSuccess = requestBody.success;
  217. let onFail = requestBody.fail;
  218. let data = requestBody.data;
  219. /// 如果是post方式
  220. if (data != undefined && requestBody.method == 'POST') {
  221. data = JSON.stringify(data);
  222. } else {
  223. data = '';
  224. }
  225. let method = requestBody.method === undefined ? 'GET' : 'POST';
  226. let url = requestBody.url;
  227. // let url = "https://test-api-taptap.duowan.com/room/reportGold1";
  228. BK.Http.request({
  229. url: url,
  230. body: data,
  231. method: method,
  232. headers: requestBody.header,
  233. success: (res) => {
  234. //直接处理登录失效的逻辑
  235. /// 如果请求成功
  236. if (res.statusCode === 200) {
  237. let bodyStr = res.text();
  238. let bodyObjct = JSON.parse(bodyStr);
  239. if (bodyObjct == undefined) {
  240. if (onFail != undefined) {
  241. onFail(res.statusCode, '请求失败');
  242. }
  243. return;
  244. }
  245. console.log('url :' + url, 'res: ' + res);
  246. if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) {
  247. GameGlobal.needLogin = true;
  248. cc.director.loadScene('login');
  249. return;
  250. }
  251. if (bodyObjct.code === ResponseStateCode.OK) {
  252. if (onSuccess != undefined) {
  253. onSuccess(bodyObjct.data);
  254. }
  255. } else {
  256. if (onFail != undefined) {
  257. onFail(bodyObjct.code, bodyObjct.msg);
  258. // GameGlobal.commonAlert.showCommonErrorAlert('url' + url + ' login error code: ' + errCode + 'login error msg: ' + errMsg);
  259. }
  260. }
  261. } else {
  262. console.log('response error statusCode' + res.statusCode);
  263. if (onFail != undefined) {
  264. onFail(res.statusCode, '请求失败');
  265. }
  266. }
  267. },
  268. fail: (res) => {
  269. console.log('qqGet fail: ' + res, 'url : ' + url, 'res : ' + res);
  270. if (onFail != undefined) {
  271. onFail(-1, res.msg);
  272. }
  273. },
  274. });
  275. }
  276. static qqPost(requestBody) {
  277. requestBody.method = 'POST';
  278. /// 添加post公共参数
  279. requestBody.url = Api.urlEncode(requestBody.url, Api.baseParam({}));
  280. Api.qqGet(requestBody);
  281. }
  282. static jsGet(requestBody) {
  283. let url = requestBody.url;
  284. let data = requestBody.data;
  285. url = url + "?";
  286. for (var key in data) {
  287. url = url + key + '=' + data[key] + '&';
  288. }
  289. url = url.substr(0, url.length - 1)
  290. var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
  291. xhr.open("GET", url, true);
  292. xhr.send();
  293. }
  294. static jsPost(requestBody) {
  295. let data = requestBody.data;
  296. var xhr = Api.jsBaseRequest(requestBody.success, requestBody.fail, requestBody.complete);
  297. xhr.open("POST", requestBody.url, true);
  298. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  299. let formData = new String();
  300. for (var key in data) {
  301. formData = formData + key + '=' + data[key] + "&";
  302. }
  303. xhr.send(formData.substr(0, formData.length - 1));
  304. }
  305. static jsBaseRequest(onSuccess, onFail, onComplete) {
  306. var xhr = new XMLHttpRequest();
  307. xhr.onreadystatechange = () => {
  308. if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
  309. // console.log('response:' + xhr.responseText);
  310. var response = JSON.parse(xhr.responseText);
  311. if (response.code == ResponseStateCode.OK) {
  312. if (onSuccess != undefined) {
  313. onSuccess(response.data, response.msg);
  314. }
  315. } else {
  316. if (onFail != undefined) {
  317. onFail(response.code, response.msg)
  318. }
  319. }
  320. if (onComplete != undefined) {
  321. onComplete();
  322. }
  323. }
  324. };
  325. return xhr;
  326. }
  327. /**
  328. * get请求对外暴露的方法
  329. * @param {*} requestBody
  330. */
  331. static httpGetPromise(url, data) {
  332. url = Api.requestUrl(url);
  333. data = Api.baseParam(data);
  334. if (window.tt != undefined) {
  335. return Api.ttGetP(url, data);
  336. }else if (CC_WECHATGAME) {
  337. return Api.wxGetP(url, data);
  338. } else if (CC_QQPLAY) {
  339. return Api.qqGetP(url, data);
  340. } else {
  341. return Api.jsGetP(url, data);
  342. }
  343. }
  344. /**
  345. * post请求对外暴露的方法
  346. * @param {*} requestBody
  347. */
  348. static httpPostPromise(url, data) {
  349. url = Api.requestUrl(url);
  350. data = Api.baseParam(data);
  351. if (window.tt != undefined) {
  352. return Api.ttPostP(url, data);
  353. } if (CC_WECHATGAME) {
  354. return Api.wxPostP(url, data);
  355. } else if (CC_QQPLAY) {
  356. return Api.qqPostP(url, data);
  357. } else {
  358. return Api.jsPostP(url, data);
  359. }
  360. }
  361. static wxGetP(url, data) {
  362. return Api.wxRequestPromise(url, data, 'GET');
  363. }
  364. static wxPostP(url, data) {
  365. let header = {
  366. "Content-Type": "application/x-www-form-urlencoded"
  367. };
  368. return Api.wxRequestPromise(url, data, 'POST', header);
  369. }
  370. static wxRequestPromise(url, data, method, header) {
  371. return new Promise((resolve, reject) => {
  372. wx.request({
  373. url: url,
  374. data: data,
  375. method: method,
  376. headers: header === undefined ? {} : header,
  377. success: (res) => {
  378. //直接处理登录失效的逻辑
  379. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  380. GameGlobal.needLogin = true;
  381. cc.director.loadScene('login');
  382. reject(res.data);
  383. }
  384. if (res.data.code === ResponseStateCode.OK) {
  385. resolve(res.data);
  386. } else {
  387. reject(res.data);
  388. }
  389. },
  390. fail: (res) => {
  391. reject({
  392. code: -1,
  393. msg: '微信登录接口调用失败'
  394. });
  395. },
  396. complete: {},
  397. });
  398. });
  399. }
  400. //头条
  401. static ttGetP(url, data) {
  402. return Api.ttRequestPromise(url, data, 'GET');
  403. }
  404. static ttPostP(url, data) {
  405. let header = {
  406. "Content-Type": "application/x-www-form-urlencoded"
  407. };
  408. return Api.ttRequestPromise(url, data, 'POST', header);
  409. }
  410. static ttRequestPromise(url, data, method, header) {
  411. return new Promise((resolve, reject) => {
  412. tt.request({
  413. url: url,
  414. data: data,
  415. method: method,
  416. headers: header === undefined ? {} : header,
  417. success: (res) => {
  418. //直接处理登录失效的逻辑
  419. if (res.data.code === ResponseStateCode.LOGIN_INVALIDATE) {
  420. GameGlobal.needLogin = true;
  421. cc.director.loadScene('login');
  422. reject(res.data);
  423. }
  424. if (res.data.code === ResponseStateCode.OK) {
  425. resolve(res.data);
  426. } else {
  427. reject(res.data);
  428. }
  429. },
  430. fail: (res) => {
  431. reject({
  432. code: -1,
  433. msg: '头条登录接口调用失败'
  434. });
  435. },
  436. complete: {},
  437. });
  438. });
  439. }
  440. //QQ
  441. static qqGetP(url, data) {
  442. url = Api.urlEncode(url, data);
  443. return Api.qqRequestPromise(url, '', 'GET');
  444. }
  445. static qqPostP(url, data) {
  446. if (data != null || data != undefined) {
  447. data = JSON.stringify(data);
  448. }
  449. return Api.qqRequestPromise(url, data, 'POST');
  450. }
  451. static qqRequestPromise(url, data, method) {
  452. return new Promise((resolve, reject) => {
  453. BK.Http.request({
  454. url: url,
  455. body: data,
  456. method: method,
  457. headers: {
  458. 'Content-Type': 'application/json'
  459. },
  460. success: (res) => {
  461. /// 如果请求成功
  462. console.log('url :' + url, 'res: ' + res);
  463. if (res.statusCode === 200) {
  464. let bodyStr = res.text();
  465. let bodyObjct = JSON.parse(bodyStr);
  466. if (bodyObjct.code === ResponseStateCode.LOGIN_INVALIDATE) {
  467. GameGlobal.needLogin = true;
  468. cc.director.loadScene('login');
  469. return;
  470. }
  471. if (bodyObjct.code === ResponseStateCode.OK) {
  472. resolve(bodyObjct);
  473. } else {
  474. reject({
  475. code: bodyObjct.code,
  476. msg: bodyObjct.msg
  477. });
  478. }
  479. } else {
  480. console.log('response error statusCode' + res.statusCode);
  481. reject({
  482. code: res.statusCode,
  483. msg: 'qq登录接口调用失败'
  484. });
  485. }
  486. },
  487. fail: (res) => {
  488. console.log('url :' + url, 'res: ' + res);
  489. reject({
  490. code: -1,
  491. msg: 'qq登录接口调用失败'
  492. });
  493. },
  494. // complete: {},
  495. });
  496. });
  497. }
  498. static jsGetP(url, data) {
  499. return new Promise((resolve, reject) => {
  500. url = url + "?";
  501. for (var key in data) {
  502. url = url + key + '=' + data[key] + '&';
  503. }
  504. url = url.substr(0, url.length - 1);
  505. var xhr = Api.jsBaseRequestP(resolve, reject);
  506. xhr.open("GET", url, true);
  507. xhr.send();
  508. });
  509. }
  510. static jsPostP(url, data) {
  511. return new Promise((resolve, reject) => {
  512. var xhr = Api.jsBaseRequestP(resolve, reject);
  513. xhr.open("POST", url, true);
  514. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  515. let formData = new String();
  516. for (var key in data) {
  517. formData = formData + key + '=' + data[key] + "&";
  518. }
  519. xhr.send(formData.substr(0, formData.length - 1));
  520. });
  521. }
  522. static jsBaseRequestP(resolve, reject) {
  523. var xhr = new XMLHttpRequest();
  524. xhr.onreadystatechange = () => {
  525. if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
  526. // console.log('response:' + xhr.responseText);
  527. var response = JSON.parse(xhr.responseText);
  528. if (response.code == ResponseStateCode.OK) {
  529. resolve(response);
  530. } else {
  531. reject(response);
  532. }
  533. }
  534. };
  535. return xhr;
  536. }
  537. /**
  538. * 将每个接口都需要的公用参数都放到这里
  539. * @param target [Object] 请求参数
  540. */
  541. static baseParam(target) {
  542. if (target === undefined) {
  543. target = {};
  544. }
  545. target.thirdType = 1;
  546. target.channel = GameGlobal.channel;
  547. target.ver = GameGlobal.ver;
  548. target.os = GameGlobal.os;
  549. target.uid = GameGlobal.user ? GameGlobal.user.uid : '';
  550. target.token = GameGlobal.user ? GameGlobal.user.token : '';
  551. return target;
  552. }
  553. /**
  554. * 自动拼接请求接口
  555. * @param targetUrl [string] 请求接口
  556. */
  557. static requestUrl(targetUrl) {
  558. var host = GameGlobal.debug ? 'https://test-api-taptap.duowan.com' : 'https://api-taptap.duowan.com';
  559. if (CC_QQPLAY) {
  560. host = GameGlobal.debug ? 'https://test-api-taptap.duowan.com' : 'https://qq-api-taptap.duowan.com';
  561. }
  562. // let host = GameGlobal.debug ? 'http://172.16.15.196:8888' : 'https://api-allstar.duowan.com';
  563. // let host = 'https://new-api-taptap.duowan.com';
  564. return host + targetUrl;
  565. }
  566. static setRequestBody(url, data, success, fail) {
  567. let requestBody = {
  568. url: url,
  569. data: data,
  570. success: success,
  571. fail: fail,
  572. complete: () => {
  573. }
  574. };
  575. return requestBody;
  576. }
  577. /// 将data对象拼接到url上做参数
  578. static urlEncode(url, data) {
  579. if(typeof(url) == 'undefined' || url == null || url == '') {
  580. return '';
  581. }
  582. if(typeof(data) == 'undefined' || data == null || typeof(data) != 'object') {
  583. return '';
  584. }
  585. url += (url.indexOf("?") != -1) ? "" : "?";
  586. for(var k in data) {
  587. url += ((url.indexOf("=") != -1) ? "&" : "") + k + "=" + encodeURI(data[k]);
  588. }
  589. return url;
  590. }
  591. }
  592. module.exports = Api;