http.js 11 KB

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