# **微信小程序支付**
![](https://box.kancloud.cn/dc9401489e0dc2cf9f70c956726335b6_974x666.png)
进入小程序,下单,请求下单支付,调用小程序登录API来获取Openid(https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html#wxloginobject)
,生成商户订单,这些都是在小程序端完成的业务。
代码部分如下:
~~~
wxpay: function () {
var that = this
wx.login({
success: function (res) {
console.log("RRRRR", res.code)//getOpenId
//获取getOpenId
that.getOpenId(res.code)
}
});
},
getOpenId: function (code) {
var that = this;
wx.request({
url: `${app.globalData.API_URL}/order`,
data: {},
method: 'post',
success: function (res) {
console.log('order_id')
console.log(res.data)
that.generateOrder(res.data.order_id)
},
fail: function () {
// fail
},
complete: function () {
// complete
}
})
},
/**生成商户订单 */
generateOrder: function (order_id) {
var that = this
//统一支付
wx.request({
url: `${app.globalData.DOMAIN}/mpbase/wxapp/wxpay/mp_id/d8d49a5800362843f29833e03038a72a/id/` + order_id,
method: 'post',
data: {},
success: function (res) {
console.log(res)
var pay = res.data
//发起支付
var timeStamp = pay[0].timeStamp;
console.log("timeStamp:" + timeStamp)
var packages = pay[0].package;
console.log("package:" + packages)
var paySign = pay[0].paySign;
console.log("paySign:" + paySign)
var nonceStr = pay[0].nonceStr;
console.log("nonceStr:" + 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
console.log("支付")
console.log(res)
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
console.log("支付失败")
console.log(res)
wx.showModal({ title: '提示', content: '支付失败', })
return
},
complete: function () {
// complete
console.log("pay complete")
}
})
},
~~~