123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261 |
- var config = require("config.js");
- //统一的网络请求方法
- function request(params, isGetTonken) {
- // 全局变量
- var globalData = getApp().globalData;
- // 如果正在进行登陆,就将非登陆请求放在队列中等待登陆完毕后进行调用
- if (!isGetTonken && globalData.isLanding) {
- globalData.requestQueue.push(params);
- console.log('ceshi');
- return;
- }
- wx.request({
- url: config.domain + params.url, //接口请求地址
- data: params.data,
- timeout:10000,
- header: {
- // 'content-type': params.method == "GET" ? 'application/x-www-form-urlencoded' : 'application/json;charset=utf-8',
- 'Authorization': params.login ? undefined : wx.getStorageSync('token') || wx.getStorageSync('tempToken')
- },
- method: params.method == undefined ? "POST" : params.method,
- dataType: 'json',
- responseType: params.responseType == undefined ? 'text' : params.responseType,
- success: function (res) {
- console.log(`接口地址${config.domain + params.url}:成功返回`,res);
- if (res.statusCode == 200) {
- //如果有定义了params.callBack,则调用 params.callBack(res.data)
- if (params.callBack) {
- params.callBack(res.data);
- }
- } else if (res.statusCode == 500) {
- wx.hideLoading()
- setTimeout(() => {
- wx.showToast({
- title: res.data || res.data.message,
- icon: "none"
- })
- }, 1)
- } else if (res.statusCode == 401) {
- if (!params.dontTrunLogin) {
- if (!wx.getStorageSync('token')) {
- // 添加到请求队列
- globalData.requestQueue.push(params);
- // 是否正在登陆
- if (!globalData.isLanding) {
- globalData.isLanding = true
- //重新获取token,再次请求接口
- getToken();
- }
- } else {
- wx.removeStorageSync('token')
- wx.removeStorageSync('loginResult')
- wx.hideLoading();
- wx.showModal({
- title: '提示',
- content: '登录已过期,请重新登录~',
- showCancel: false,
- success: modalRes => {
- if (modalRes.confirm) {
- wx.redirectTo({
- url: '/pages/login/login',
- })
- }
- }
- })
- }
- }
- } else if (res.statusCode == 400 && params.errCallBack) {
- if (params.errCallBack) {
- params.errCallBack(res);
- }
- if (!globalData.isLanding) {
- wx.hideLoading();
- }
- } else if (res.statusCode == 400 && !params.errCallBack) {
- wx.hideLoading()
- setTimeout(() => {
- wx.showToast({
- title: res.data,
- icon: "none"
- })
- }, 1)
- } else {
- //如果有定义了params.errCallBack,则调用 params.errCallBack(res.data)
- if (params.errCallBack) {
- params.errCallBack(res);
- }
- if (!globalData.isLanding) {
- wx.hideLoading();
- }
- }
- },
- fail: function (err) {
- console.warn(`接口地址${config.domain + params.url}:报错返回`,res);
- wx.hideLoading();
- setTimeout(() => {
- wx.showToast({
- title: err.message || "服务器出了点小差",
- icon: "none"
- });
- }, 1)
- },
- complete: function (res) {
- console.log(`接口地址${config.domain + params.url}:完成`,res,params.data);
- }
- })
- }
- //上传文件统一接口
- function upload(params) {
- wx.uploadFile({
- url: config.domain + params.url,
- filePath: params.filePath,
- name: params.name,
- header: {
- 'Content-Type': 'multipart/form-data',
- 'Authorization': params.login ? undefined : wx.getStorageSync('token')
- },
- dataType: 'json',
- responseType: params.responseType == undefined ? 'json' : params.responseType,
- success: function (res) {
- console.log(res);
- //console.log(res);
- if (res.statusCode == 200) {
- //如果有定义了params.callBack,则调用 params.callBack(res.data)
- if (params.callBack) {
- params.callBack(res.data);
- }
- } else {
- wx.showToast({
- title: res.message || "服务器出了点小差",
- icon: "none"
- });
- }
- },
- fail: function (err) {
- wx.hideLoading();
- }
- })
- }
- //通过code获取token,并保存到缓存
- var getToken = function (fn) {
- wx.login({
- success: res => {
- // 发送 res.code 到后台换取 openId, sessionKey, unionId
- console.log(res);
- request({
- login: true,
- url: '/appLogin',
- data: {
- principal: res.code,
- appType: 1
- },
- callBack: result => {
- loginSuccess(result, fn)
- }
- }, true)
- }
- })
- }
- function loginSuccess(result, fn) {
- // 保存登陆信息
- wx.setStorageSync('loginResult', result)
- // 没有获取到用户昵称,说明服务器没有保存用户的昵称,也就是用户授权的信息并没有传到服务器
- if (!result.pic) {
- updateUserInfo();
- }
- if (!result.enabled) {
- wx.showModal({
- showCancel: false,
- title: '提示',
- content: '您已被禁用,不能购买,请联系客服'
- })
- wx.setStorageSync('token', '');
- } else {
- wx.setStorageSync('token', 'bearer' + result.access_token); //把token存入缓存,请求接口数据时要用
- }
- var globalData = getApp().globalData;
- globalData.isLanding = false;
- while (globalData.requestQueue.length) {
- request(globalData.requestQueue.pop());
- }
- if (fn) {
- fn()
- }
- }
- // 更新用户头像昵称
- function updateUserInfo() {
- wx.getUserInfo({
- success: (res) => {
- var userInfo = JSON.parse(res.rawData)
- request({
- url: "/p/user/setUserInfo",
- method: "PUT",
- data: {
- avatarUrl: userInfo.avatarUrl,
- nickName: userInfo.nickName
- }
- });
- }
- })
- }
- //获取购物车商品数量
- function getCartCount() {
- var params = {
- url: "/p/shopCart/prodCount",
- method: "GET",
- dontTrunLogin: true,
- data: {},
- callBack: function (res) {
- if (res > 0) {
- wx.setTabBarBadge({
- index: 1,
- text: res + "",
- })
- var app = getApp();
- app.globalData.totalCartCount = res;
- } else {
- wx.removeTabBarBadge({
- index: 2
- })
- var app = getApp();
- app.globalData.totalCartCount = 0;
- }
- }
- };
- request(params);
- }
- // 查看是否授权
- function isUserAuthInfo() {
- // 查看是否授权
- wx.getSetting({
- success(res) {
- if (res.authSetting['scope.userInfo']) {
- // 已经授权,可以直接调用 getUserInfo 获取头像昵称
- wx.getUserInfo({
- success: function (res) {
- console.log(res.userInfo)
- }
- })
- }
- }
- })
- }
- exports.getToken = getToken;
- exports.request = request;
- exports.getCartCount = getCartCount;
- exports.updateUserInfo = updateUserInfo;
- exports.upload = upload;
- exports.loginSuccess = loginSuccess;
|