http.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. var config = require("./config.js"); //统一的网络请求方法
  2. var util = require("./util.js")
  3. import {
  4. AppType
  5. } from './constant.js'
  6. function request(params, isGetTonken) {
  7. // 全局变量
  8. var globalData = getApp().globalData; // 如果正在进行登陆,就将非登陆请求放在队列中等待登陆完毕后进行调用
  9. // if (!isGetTonken && globalData.isLanding) {
  10. // globalData.requestQueue.push(params);
  11. // return;
  12. // }
  13. if (Object.prototype.toString.call(params.data) == '[object Array]') {
  14. params.data = JSON.stringify(params.data);
  15. } else if (Object.prototype.toString.call(params.data) == '[object Number]') {
  16. params.data = params.data + '';
  17. }
  18. var needToken = false
  19. // if (params.url.indexOf("/p/") == 0 || params.url.indexOf("/user/registerOrBindUser") == 0) {
  20. // needToken = true
  21. // }
  22. wx.request({
  23. // url: config.domain + params.url,
  24. url: (params.domain ? params.domain : config.domain) + params.url,
  25. //接口请求地址
  26. data: params.data,
  27. header: {
  28. // 'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
  29. // 'Authorization': params.login ? undefined : uni.getStorageSync('token')
  30. 'Authorization': uni.getStorageSync('token') ,
  31. },
  32. method: params.method == undefined ? "POST" : params.method,
  33. dataType: 'json',
  34. responseType: params.responseType == undefined ? 'text' : params.responseType,
  35. success: function (res) {
  36. const responseData = res.data
  37. // 00000 请求成功
  38. if (responseData.code === '00000') {
  39. if (params.callBack) {
  40. params.callBack(responseData.data);
  41. }
  42. return
  43. }
  44. // A00004 未授权
  45. if (responseData.code === 'A00004') {
  46. uni.removeStorageSync('loginResult');
  47. uni.removeStorageSync('token');
  48. // #ifdef H5
  49. const ua = navigator.userAgent.toLowerCase();
  50. if (ua.search(/MicroMessenger/i) > -1) uni.setStorageSync('appType', AppType.MP)
  51. // #endif
  52. uni.hideLoading();
  53. if (!params.dontTrunLogin) {
  54. if (uni.getStorageSync('hadLogin')) {
  55. uni.showModal({
  56. title: "提示",
  57. content: "登录已过期",
  58. cancelText: "取消",
  59. confirmText: "确定",
  60. success: res => {
  61. if (res.confirm) {
  62. // 跳转登录页面
  63. var url = ''
  64. // #ifdef H5 || MP-WEIXIN
  65. if (uni.getStorageSync('appType') == AppType.MP || uni.getStorageSync('appType') == AppType.MINI) {
  66. url = '/pages/login/login'
  67. } else {
  68. url = '/pages/accountLogin/accountLogin'
  69. }
  70. // #endif
  71. // #ifdef APP-PLUS
  72. var url = '/pages/accountLogin/accountLogin'
  73. // #endif
  74. uni.navigateTo({
  75. url: url
  76. })
  77. } else {
  78. uni.switchTab({
  79. url: '/pages/index/index'
  80. })
  81. }
  82. }
  83. })
  84. } else {
  85. uni.showModal({
  86. title: "提示",
  87. content: "登录已过期",
  88. cancelText: "取消",
  89. confirmText: "确定",
  90. success: res => {
  91. if (res.confirm) {
  92. // 跳转登录页面
  93. // #ifdef H5
  94. uni.navigateTo({
  95. url: uni.getStorageSync('appType') == AppType.MP ? '/pages/login/login' : '/pages/accountLogin/accountLogin'
  96. })
  97. // #endif
  98. // #ifdef MP-WEIXIN
  99. uni.navigateTo({
  100. url: '/pages/login/login'
  101. })
  102. // #endif
  103. } else {
  104. uni.switchTab({
  105. url: '/pages/index/index'
  106. })
  107. }
  108. }
  109. })
  110. // // 跳转登录页面
  111. // // #ifdef H5
  112. // uni.navigateTo({
  113. // url: uni.getStorageSync('appType') == AppType.MP ? '/pages/login/login' : '/pages/accountLogin/accountLogin'
  114. // })
  115. // // #endif
  116. // // #ifdef MP-WEIXIN
  117. // uni.navigateTo({
  118. // url: '/pages/login/login'
  119. // })
  120. // // #endif
  121. }
  122. }
  123. return
  124. }
  125. // A00005 服务器出了点小差
  126. if (responseData.code === 'A00005') {
  127. console.error('============== 请求异常 ==============')
  128. console.log('接口: ', params.url)
  129. console.log('异常信息: ', responseData)
  130. console.error('============== 请求异常 ==============')
  131. if (params.errCallBack) {
  132. params.errCallBack(responseData)
  133. return
  134. }
  135. uni.showToast({
  136. title: '服务器出了点小差~',
  137. icon: 'none'
  138. })
  139. }
  140. // A00001 用于直接显示提示用户的错误,内容由输入内容决定
  141. if (responseData.code === 'A00001') {
  142. if (params.errCallBack) {
  143. params.errCallBack(responseData)
  144. return
  145. }
  146. uni.showToast({
  147. title: responseData.msg || 'Error',
  148. icon: 'none'
  149. })
  150. return
  151. }
  152. // 其他异常
  153. if (responseData.code !== '00000') {
  154. // console.log('params', params)
  155. if (params.errCallBack) {
  156. params.errCallBack(responseData)
  157. } else {
  158. console.log(`接口: ${params.url}`)
  159. console.log(`返回信息: `, res)
  160. }
  161. }
  162. if (!globalData.isLanding) {
  163. wx.hideLoading();
  164. }
  165. },
  166. fail: function (err) {
  167. uni.hideLoading();
  168. if (err.errMsg == 'request:fail abort') {
  169. console.log('请求被取消啦~')
  170. return
  171. }
  172. setTimeout(() => {
  173. uni.showToast({
  174. // zheli
  175. title: "服务器出了点小差",
  176. icon: "none"
  177. });
  178. }, 1);
  179. }
  180. });
  181. } //通过code获取token,并保存到缓存
  182. var getToken = function () {
  183. // uni.login({
  184. // success: res => {
  185. // // 发送 res.code 到后台换取 openId, sessionKey, unionId
  186. // request({
  187. // login: true,
  188. // url: '/login?grant_type=mini_app',
  189. // data: {
  190. // principal: res.code
  191. // },
  192. // callBack: result => {
  193. // // 没有获取到用户昵称,说明服务器没有保存用户的昵称,也就是用户授权的信息并没有传到服务器
  194. // if (!result.nickName) {
  195. // updateUserInfo();
  196. // }
  197. // if (result.userStutas == 0) {
  198. // uni.showModal({
  199. // showCancel: false,
  200. // title: '提示',
  201. // content: '您已被禁用,不能购买,请联系客服'
  202. // });
  203. // uni.setStorageSync('token', '');
  204. // } else {
  205. // uni.setStorageSync('token', 'bearer' + result.access_token); //把token存入缓存,请求接口数据时要用
  206. // }
  207. // var globalData = getApp().globalData;
  208. // globalData.isLanding = false;
  209. // while (globalData.requestQueue.length) {
  210. // request(globalData.requestQueue.pop());
  211. // }
  212. // }
  213. // }, true);
  214. // }
  215. // });
  216. }; // 更新用户头像昵称
  217. /**
  218. * 微信公众号登录
  219. * @param {Object} fn 登录成功回调
  220. * @param {String} code 微信授权返回的code, 用于登录
  221. */
  222. var mpLogin = function (fn, code) {
  223. // 发送 res.code 到后台换取 openId, sessionKey, unionId
  224. request({
  225. login: true,
  226. url: '/appLogin',
  227. data: {
  228. principal: code,
  229. appType: AppType.MP, // 登录类型
  230. },
  231. callBack: result => {
  232. loginSuccess(result, fn)
  233. }
  234. }, true);
  235. };
  236. var getToken = function (fn) {
  237. };
  238. /**
  239. * 登录成功后执行
  240. * @param {Object} result 登录成功返回的数据
  241. * @param {Object} fn 登录成功后的回调
  242. */
  243. function loginSuccess (result, fn) {
  244. // if (!result.enabled) {
  245. // uni.showModal({
  246. // showCancel: false,
  247. // title: "提示",
  248. // content: "您已被禁用,不能购买,请联系客服",
  249. // cancelText: "取消",
  250. // confirmText: "确定",
  251. // success: function (res) {
  252. // if (res.confirm) {
  253. // wx.switchTab({
  254. // url: '/pages/index/index'
  255. // });
  256. // }
  257. // }
  258. // })
  259. // wx.setStorageSync('token', '');
  260. // return
  261. // }
  262. // 保存登陆信息
  263. wx.setStorageSync('loginResult', result)
  264. // 保存成功登录标识,token过期判断
  265. wx.setStorageSync('hadLogin', true)
  266. // 没有获取到用户昵称,说明服务器没有保存用户的昵称,也就是用户授权的信息并没有传到服务器
  267. // if (!result.pic) {
  268. // updateUserInfo();
  269. // }
  270. const expiresTimeStamp = result.expiresIn * 1000 / 2 + new Date().getTime()
  271. // 缓存token的过期时间
  272. uni.setStorageSync('expiresTimeStamp', expiresTimeStamp)
  273. wx.setStorageSync('token', result.accessToken); //把token存入缓存,请求接口数据时要用
  274. // const routeUrlAfterLogin = uni.getStorageSync('routeUrlAfterLogin')
  275. // const pages = getCurrentPages()
  276. // if (pages.length === 1) {
  277. // uni.reLaunch({
  278. // url: routeUrlAfterLogin
  279. // })
  280. // uni.removeStorageSync('routeUrlAfterLogin')
  281. // return
  282. // }
  283. // const prevPage = pages[pages.length - 2]
  284. // if (!prevPage) {
  285. // wx.switchTab({
  286. // url: '/pages/index/index'
  287. // });
  288. // return
  289. // }
  290. // // 判断上一页面是否为tabbar页面 (首页和分类页无需登录接口)
  291. // const isTabbar = prevPage.route === 'pages/user/user' || prevPage.route === 'pages/basket/basket'
  292. // if (isTabbar) {
  293. // wx.switchTab({
  294. // url: '/' + prevPage.route
  295. // });
  296. // } else {
  297. // // 非tabbar页面
  298. // let backDelata = 0
  299. // pages.forEach((page, index) => {
  300. // if (page.$page.fullPath === routeUrlAfterLogin) {
  301. // backDelata = pages.length - index - 1
  302. // }
  303. // })
  304. // if (backDelata) {
  305. // uni.navigateBack({
  306. // delta: backDelata
  307. // })
  308. // } else {
  309. // wx.switchTab({
  310. // url: '/pages/index/index'
  311. // });
  312. // }
  313. // }
  314. if (fn) {
  315. fn()
  316. }
  317. };
  318. function updateUserInfo() {
  319. uni.getUserInfo({
  320. success: res => {
  321. var userInfo = JSON.parse(res.rawData);
  322. request({
  323. url: "/p/user/setUserInfo",
  324. method: "PUT",
  325. data: {
  326. avatarUrl: userInfo.avatarUrl,
  327. nickName: userInfo.nickName
  328. }
  329. });
  330. }
  331. });
  332. }
  333. function isUserAuthInfo () {
  334. // 查看是否授权
  335. wx.getSetting({
  336. success (res) {
  337. if (res.authSetting['scope.userInfo']) {
  338. // 已经授权,可以直接调用 getUserInfo 获取头像昵称
  339. wx.getUserInfo({
  340. success: function (res) {
  341. console.log(res.userInfo);
  342. }
  343. });
  344. }
  345. }
  346. });
  347. }
  348. function mpAuthLogin (page, needCode) {
  349. // 在微信环境打开,请求公众号网页登陆
  350. var redirectUrl = null;
  351. if (!page) {
  352. redirectUrl = window.location.href
  353. } else {
  354. var {
  355. protocol,
  356. host,
  357. pathname,
  358. hash
  359. } = window.location
  360. var redirectUrl = `${protocol}//${host}` + page
  361. }
  362. var scope = 'snsapi_userinfo'
  363. window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + config.mpAppId +
  364. '&redirect_uri=' +
  365. encodeURIComponent(redirectUrl) + '&response_type=code&scope=' + scope + '&state=' + (needCode ? 'needCode' :
  366. 'unNeedCode') +
  367. '#wechat_redirect'
  368. }
  369. /**
  370. * 获取购物车商品数量
  371. */
  372. function getCartCount () {
  373. if (!uni.getStorageSync('token')) {
  374. // wx.removeTabBarBadge({
  375. // index: 2
  376. // });
  377. util.removeTabBadge()
  378. return
  379. }
  380. var params = {
  381. url: "/p/shopCart/prodCount",
  382. method: "GET",
  383. dontTrunLogin: true,
  384. data: {},
  385. callBack: function (res) {
  386. if (res > 0) {
  387. wx.setTabBarBadge({
  388. index: 2,
  389. text: res + ""
  390. });
  391. var app = getApp().globalData;
  392. getApp().globalData.totalCartCount = res;
  393. } else {
  394. wx.removeTabBarBadge({
  395. index: 2
  396. });
  397. var app = getApp().globalData;
  398. getApp().globalData.totalCartCount = 0;
  399. }
  400. }
  401. };
  402. request(params);
  403. }
  404. exports.getToken = getToken;
  405. exports.request = request;
  406. exports.getCartCount = getCartCount;
  407. exports.updateUserInfo = updateUserInfo;
  408. exports.mpAuthLogin = mpAuthLogin;
  409. exports.loginSuccess = loginSuccess;
  410. exports.mpLogin = mpLogin;