目錄
支付流程
-
點擊
去結算
時,,前端判斷是否登錄【未登錄跳轉到登錄頁】,登錄發送code到服務端,服務端使用code發送請求去獲取openId;並返回userId/openId存儲在storage; -
點擊
去支付
時,前端發送請求【訂單詳細,openId】,服務器用openId去統一下單,下單成功後,獲取prePay_id,返回前端 -
前端拿到 prePay_id 調起支付
具體實現
一、前端調用登錄獲取code
wx.login({
success: function(res){
if(res.code){
// 發起請求
wx.request({
url: 'http://test.com/login',
data: {
code: res.code
},
success(result) {
console.log(result.openId)
wx.setStorage('openId', result.openId)
}
})
} else {
// 登錄失敗
}
}
})
二、服務端接收code,服務端調用微信api獲取openId
GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
三、前端點擊去支付時
前端點擊去支付時,提交【openId,訂單明細】到服務端進行下單
// 提交訂單
commitOrder() {
let that = this
if (!this.isLogin) {
this.toLogin()
} else if (!this.currentAddress.addressId) {
wx.showToast({
title: '請先選擇地址',
icon: 'none',
duration: 1500,
success() {
// 選擇地址
}
})
} else if(this.isLogin && this.currentAddress.addressId)
let details = [];
(this.shopCartList).map(g => {
details.push({
goodsId: g.goodsId,
goodsNum: g.cartGoodNum,
goodsPrice: g.goodsPrice
})
})
let openId = wx.getStorageSync('openId')
Api.creatOrder({
query: {
addressId: this.currentAddress.addressId,
openId: openId,
appId: '',
details: details,
goodsMoney: this.totalMoney,
orderNote: this.orderNote
}
}).then(res => {
if (res.data.code == '0') {
this.toPay({
timeStamp: res.data.data.timeStamp.toString(),
nonceStr: res.data.data.nonceStr,
package: res.data.data.package,
signType: res.data.data.signType,
paySign: res.data.data.sign,
orderId: res.data.data.orderId,
})
}
})
} else {}
},
四、服務端請求微信統一下單接口
服務端請求微信統一下單接口,下單成功獲取到prePay_id值,返回前端
文檔-https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1
商戶在小程序中先調用該接口(https://api.mch.weixin.qq.com/pay/unifiedorder)在微信支付服務後臺生成預支付交易單,返回正確的預支付交易後,前端調起支付。
五、前端獲取到prePay_id 調起支付
pay: function (param) {
wx.requestPayment({
timeStamp: param.timeStamp,
nonceStr: param.nonceStr,
package: param.package,
signType: param.signType,
paySign: param.paySign,
success: function (res) {
// success
console.log(res)
wx.navigateBack({
delta: 1, // 回退前 delta(默認爲1) 頁面
success: function (res) {
console.log(res)
},
fail: function () {
// fail
},
complete: function () {
// complete
// 不論成功失敗都跳轉到訂單頁面,後臺去查詢支付結果
wx.switchTab({
url: 'order',
success: function (res) {
}
})
}
})
}
})
}
六、注意
不能通過 wx.requestPayment 的success回調判斷支付成功
支付完不點完成不操作不進成功