只是分享一下小程序支付功能的前端流程和代碼, 僅供參考(使用的是uni app)。
handleCreate () { /** 第一步:前台將商品數據發送到后台,后台創建訂單入庫並返回訂單id等信息 */ uni.request({ url: '/testApi/wxPay/insert', // 創建訂單接口 method: 'POST', data: { openId: '獲取到的該用戶的openid,必傳', number: '商品數量', goodsId: '商品id', goodsFee: '商品價格' }, success: res => { console.log('獲取數據成功') this.handlePayment(res) }, fail: err => { console.log(err) } }) }, handlePayment (res) { /** 第二步,根據后台返回的訂單id生成商戶訂單 */ uni.request({ url: '/testApi/wxPay/unifiedorder', // 生成訂單接口 method: 'POST', data: { openId: '獲取到的該用戶的openid,必傳', totalFee: res.paidAmount, // 商品支付價格 uid: res.uid // 后台生成的訂單id }, success: result => { /** 第三步,調用微信支付接口發起支付(我們后台返回的是JSON字符串,所以要轉為JSON對象) */ let param = JSON.parse(result); uni.requestPayment({ timeStamp: param.timeStamp, nonceStr: param.nonceStr, package: param.package, signType: param.signType, paySign: param.paySign, success: response => { console.log('支付成功') }, fail: err => { console.log(err) } }) }, fail: err => { console.log(err) } }) }