微信小程序请求封装

1.请求封装

class request {
  constructor() {
    this._header = {}
  }

  /**
   * 设置统一的异常处理
   */
  setErrorHandler(handler) {
    this._errorHandler = handler;
  }

  /**
   * GET类型的网络请求
   */
  getRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'GET')
  }

  /**
   * DELETE类型的网络请求
   */
  deleteRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'DELETE')
  }

  /**
   * PUT类型的网络请求
   */
  putRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'PUT')
  }

  /**
   * POST类型的网络请求
   */
  postRequest(url, data, header = this._header) {
    return this.requestAll(url, data, header, 'POST')
  }

  /**
   * 网络请求
   */
  requestAll(url, data, header, method) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: url,
        data: data,
        header: header,
        method: method,
        success: (res => {
          if (res.statusCode === 200) {
            //200: 服务端业务处理正常结束
            resolve(res)
          } else {
            //其它错误,提示用户错误信息
            if (this._errorHandler != null) {
              //如果有统一的异常处理,就先调用统一异常处理函数对异常进行处理
              this._errorHandler(res)
            }
            reject(res)
          }
        }),
        fail: (res => {
          if (this._errorHandler != null) {
            this._errorHandler(res)
          }
          reject(res)
        })
      })
    })
  }
}

export default request

2.使用请求

import request from './request.js'
class agriknow {
  constructor() {
    this._baseUrl = 'http://www.****.com/account-service/api/',
    this._defaultHeader = {
        'content-Type': 'application/x-www-form-urlencoded'
      }
    this._defaultData = {
      systemType: "00",
      systemVersion: "iOS12.1"
    }
    this._request = new request
    this._request.setErrorHandler(this.errorHander)
  }

  /**
   * 统一的异常处理方法
   */
  errorHander(res) {
    console.error(res)
  }

  /**
   * 注册
   */
  setAndUpdatePwd(data) {
    return this._request.postRequest(this._baseUrl + 'user/{version}/setAndUpdatePwd', Object.assign(data, this._defaultData)).then(res => res.data)
  }
}
export default agriknow

3.设置全局

在app.js里引入

import agriknow from './apis/agriknow.js'

//app.js
App({
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 是否存在sessionId
    const sessionId =  wx.getStorageSync('sessionId') || []

    // 登录
    wx.login({
      success: res => {
        var code = res.code;
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // if (code) {
        //   console.log('获取用户登录凭证:' + code);
        // } else {
        //   console.log('获取用户登录态失败:' + res.errMsg);
        // }
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo

              // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
    onLoad: function (options) {
    debugger
        // 页面初始化 options为页面跳转所带来的参数
        var that = this
        //登陆获取code
        wx.login({
            success: function (res) {
                console.log(res.code)
                //获取openid
                that.getOpenId(res.code)
            }
        });
    },
    getOpenId: function (code) {
    debugger
        var that = this;
        wx.request({
            url: "https://api.weixin.qq.com/sns/jscode2session?appid=小程序appid&secret=小程序应用密钥&js_code=" + code + "&grant_type=authorization_code",
            data: {},
            method: 'GET',
            success: function (res) {
                that.generateOrder(res.data.openid)
            },
            fail: function () {
                // fail
            },
            complete: function () {
                // complete
            }
        })
    },
    /**生成商户订单 */
    generateOrder: function (openid) {
        var that = this
        //统一支付
        wx.request({
            url: '后台路径',
            method: 'GET',
            data: {
                gfee: '商品价钱',
                gname: '商品名称',
                openId:openid
                //(商品价钱和商品名称根据自身需要是否传值,openid为必传)
    },
        success: function (res) {
            var pay = res.data
            //发起支付
            var timeStamp = pay[0].timeStamp;
            var packages = pay[0].package;
            var paySign = pay[0].paySign;
            var nonceStr = pay[0].nonceStr;
            var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
            that.pay(param)
        },
    })
    },
  /* 支付   */
    pay: function (param) {
        console.log("支付")
        console.log(param)
        wx.requestPayment({
            timeStamp: param.timeStamp,
            nonceStr: param.nonceStr,
            package: param.package,
            signType: param.signType,
            paySign: param.paySign,
            success: function (res) {
                // success
                wx.navigateBack({
                    delta: 1, // 回退前 delta(默认为1) 页面
                    success: function (res) {
                        wx.showToast({
                            title: '支付成功',
                            icon: 'success',
                            duration: 2000
                        })
                    },
                    fail: function () {
                        // fail
                    },
                    complete: function () {
                        // complete
                    }
                })
            },
            fail: function (res) {
                // fail
            },
            complete: function () {
                // complete
            }
        })
    },
  globalData: {
    userInfo: null,
    // 客服电话
    phoneNumber: '4006301238'
  },
  agriknow:new agriknow()
})

你可能感兴趣的:(微信小程序请求封装)