富贵资源网 Design By www.hznty.com

微信小程序 支付功能(前端)的实现

只提供微信小程序端代码:


var app = getApp();
Page({
  data: {},
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    var that = this
    //登陆获取code
    wx.login({
      success: function (res) {
        console.log(res.code)
        //获取openid
        that.getOpenId(res.code)
      }
    });
  },
  getOpenId: function (code) {
    var that = this;
    wx.request({
      url: "https://api.weixin.qq.com/sns/jscode2session" + 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
      }
    })
  }
})

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com