云开发做微信支付爽的不要不要的:D
云开发做微信支付,一行代码搞定,爽的不要不要的,云函数一句代码:
const cloud = require('wx-server-sdk')
cloud.init()
exports.main = async (event, context) => {
return await cloud.cloudPay.unifiedOrder(event.payData)
}
小程序端的代码也很简单:
let payData = {
"functionName":payConfig.payCallBack,
"envId": payConfig.envId,
"subMchId" : payConfig.subMchId,
"nonceStr":comm.randomString(),
"body" : app.globalData.mpName,
"outTradeNo" : order._id,
"totalFee" : order.sumFee,
"spbillCreateIp" : "127.0.0.1",//这个就这样写,可以通过
"tradeType":"JSAPI",
}
wx.cloud.callFunction({
name: 'payOrder',
data: {
payData,
},
success: res => {
const payment = res.result.payment
wx.requestPayment({
...payment,
success(res) {
console.log('支付成功', res)
order.status=2
that.setData({
order,
})
},
fail(err) {
console.error('支付失败', err)
}
})
},
fail: console.error,
})
再把最复杂的微信统一支付的回调函数payCallBack(名字自己随便起)搞定,就万事大吉了:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
const collOrder = db.collection('order')
const collUser = db.collection('user')
const collSysconf = db.collection('sysconf')
exports.main = async (event, context) => {
let status
let id = event.outTradeNo
let order = (await collOrder.doc(id).field({
status: true,
sumFee: true,
levelObj: true
}).get()).data
let errmsg=''
let ownerOpenid = event.userInfo.openId
if(!ownerOpenid){
errmsg = '没有操作人的openid'
}
if (!errmsg&&'status' in order) {
/**
最复杂的业务逻辑代码
*/
} else {
if(!errmsg){
errmsg = '订单找不到了'
}
}
if (errmsg) {
return '有错误发生:' + errmsg
} else {
await collOrder.doc(id).update({
data: {
status: 2,
},
})
return {
"errcode": 0
}
}
}