前提是已经有了微信支付账号。
第一步 先申请一个微信小程序
获取appid 这个小程序需要做企业资质的微信认证
点击进去填写APPID
微信支付商家助手会给微信支付商家的管理员发信息,获得管理员授权
第二步:
微信小程序申请云开发, 这个目前已经收费, 第一月免费, 后面19.9 一个月
1: 建立一个云函数makeorder.js, 填写好你的微信支付商户号和云开发的id
// 云函数代码
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
const res = await cloud.cloudPay.unifiedOrder({
"body": event.goodName, //商品名称或商品描述
"outTradeNo": "25019011234" + new Date().getTime(), //订单号
"spbillCreateIp": "127.0.0.1",
"subMchId": "xxxxx", //****** 微信支付商户号
"totalFee": event.totalFee * 100, //支付的金额,单位分
"envId": "xxxxxx",//云开发id
"functionName": "payCallBack" //支付成功的回调
})
return res
}
2: 建立一个云函数 paycallback
// 云函数 payCallback
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
//订单号 event.outTradeNo
return await cloud.database().collection('order').doc(event.outTradeNo).update({
data: {
status: 1
}
}).then(res => {
return res
}).catch(res => {
return res
})
}
3:在云开发后台中的其他设置中添加商户号并获得授权
3: 在微信小程序里面添加点击事件并绑定如下操作
wx.cloud.callFunction({
name: 'makeorder',
data: {
goodName: goodName,
totalFee: goodPrice
},
success: res => {
console.log("获取支付参数成功", res)
const payment = res.result.payment
//调起支付
wx.requestPayment({
...payment,
success(res) {
console.log('支付成功', res)
//xxxxx 你的业务逻辑,如记账等
},
fail(err) {
console.error('支付失败', err)
}
})
},
fail: res => {
console.log("获取支付参数失败", res)
},
})
}
总结: 自己留着备忘