1.概括
微信小程序云开发调用官方支付,需要两步:
1.根据信息获取支付凭证;2.使用支付凭证发起支付流程。
PS:
1.使用官方云支付,需要【非个人小程序账号】,并且【开通了支付功能(目前¥300)】,会得到一个【商户号】。
2.支付凭证是我自己起的名字,总之就是官方给你的支付信息,用于发起支付流程。
2.代码
2.1 html
ps:一个简单的按钮
<view class="action margin-0 flex-sub text-green "
bindtap="toValid" data-target="Image">
<text class="cuIcon-moneybag"></text>支付
</view>
2.2 js
PS:代码中有包含我自己的功能逻辑,即不是所有参数都是支付必须的;比如第一步获取支付凭证中订单号和金额是支付必须的,参考云函数所需参数即可。
//认证支付-1生成支付信息
toValid(e) {
let nonceStr = Math.random().toString(36).substr(2, 15);
let timeStamp = parseInt(Date.now() / 1000) + '';
let orderNum = "nyt" + nonceStr + timeStamp;//生成自定义订单号
this.setData({
['payInfo.orderNum'] : orderNum
})
wx.cloud.callFunction({
name: 'getXXXInfo',
data: {
action: "XXX",
orderNum: this.data.payInfo.orderNum,//自定义订单号
price: this.data.payInfo.price//支付金额,1=1分
},
success: res => {
console.log(res);
this.doPay(res.result,res.requestID);
},
fail: res => {
wx.showToast({
image: '/assets/images/warn.png',
title: '请求失败'
})
}
})
},
//认证支付-2根据支付信息发起支付
doPay(payData,payRequestId){
wx.requestPayment({
nonceStr: payData.nonceStr,
package: payData.package,
paySign: payData.paySign,
signType: payData.signType,
timeStamp: payData.timeStamp,
success: (res)=>{
//修改用户类型
this.setData({
['userInfo.userType']:'vip'
})
this.hideModal();
//更新用户类型
this.rf_updateUserInfo(this.data.userInfo,'userType');
},
fail: (res) =>{
wx.showToast({
image: "/assets/images/warn.png",
title: '支付失败',
})
},
complete: (res)=> {
console.log(res);
//记录支付详情
this.recordPay(payData, res.errMsg, payRequestId);;
}
})
},
//认证支付-3记录支付结果
recordPay(payData,result,payRequestId){
console.log(payRequestId);
//添加支付记录
collectionPay.add({
data:{
payRequestId: payRequestId,
payNo: payData.nonceStr,
payPackage: payData.package,
paySign: payData.paySign,
payTime: payData.timeStamp,
orderTime: db.serverDate(),
orderNum: this.data.payInfo.orderNum,
orderPrice: this.data.payInfo.price,
orderUser: this.data.hostInfo.userName,
orderOpenid: this.data.hostInfo._openid,
orderResult: result
},
success:(res=>{
console.log("添加支付记录");
}),
fail:console.error,
complete: (res =>{
//触发页面刷新加载
this.rf_bindPageData();
})
})
},
以上是小程序中的代码,其中第一步会调用云函数获取支付凭证。【云函数】如下:
//云函数js中-支付处理
async function doUserPay(event) {
const wxContext = cloud.getWXContext();
let orderNum = event.orderNum;
let price = event.price;
//3,初始化支付
const api = tenpay.init(payConfig);
// 订单信息放在了小程序中,也可以放在云函数
// const nonceStr = Math.random().toString(36).substr(2, 15);
// const timeStamp = parseInt(Date.now() / 1000) + '';
// const out_trade_no = "otn" + nonceStr + timeStamp;
let result = await api.getPayParams({
out_trade_no: orderNum,
body: '用户认证',
total_fee: price, //订单金额(分),
openid: wxContext.OPENID //付款用户的openid
});
return result;
}
3.结果截图
1.大概就是点击支付按钮,第一步获取支付凭证ok,第二步发起支付就会弹出微信支付输密码页面,输入密码就可以支付完成;
2.代码中有写打印信息console.log,下面是一个点击支付按钮-输入密码时直接取消支付的打印结果: