云函数
安装 tenpay模块
/cloud/pay/index.js
//云开发实现支付
const cloud = require("wx-server-sdk")
cloud.init()
//1.引入支付的三方依赖
const tenpay = require('tenpay')
//2. 配置支付信息
const config = {
appid: '你的小程序appid',
mchid: '你的微信商户号',
partnerKey: '微信支付安全密钥',
notify_url: '支付回调网址,这里可以先随意填一个网址',
spbill_create_ip: '127.0.0.1'
}
exports.main = async(event,context) => {
const wxContext = cloud.getWXContext()
let {
orderid,
money
} = event;
// 3. 初始化支付
const api = tenpay.init(config);
let result = await api.getPayParams({
out_trade_no: orderid,
body: '商品简单描述',
total_fee: money, //订单金额(分),
openid: wxContext.OPENID //付款用户的openid
})
return result;
}
小程序端
wxml
<form bindsubmit="formSubmit">
<view class="section">
<input name="orderid" placeholder="please input here" value="111111111112"/>
</view>
<view class="section">
<input name="money" placeholder="please input here" value="12"/>
</view>
<view class="btn-area">
<button formType="submit">Submit</button>
</view>
</form>
js
Page({
formSubmit: function (e) {
let formData = e.detail.value
console.log('form发生了submit事件,携带数据为:', formData)
wx.cloud.callFunction({
name: 'pay',
data: {
orderid: "" + formData.orderid,
money: formData.money
},
success: res => {
console.log('提交成功', res.result);
this.pay(res.result)
},
fail: res => {
console.log('提交失败', res);
}
})
},
//实现小程序支付
pay(payData) {
//官方标准的支付方法
wx.requestPayment({
timeStamp: payData.timeStamp,
nonceStr: payData.nonceStr,
package: payData.package, //统一下单接口返回的prepay_id 格式如:prepay_id= ***
signType: 'MD5',
paySign: payData.paySign, //签名
success(res) {
console.log('支付成功', res);
},
fail(res) {
console.log('支付失败', res);
},
complete(res) {
console.log('支付完成', res);
},
})
}
})