May 22, 2021 Mini Program Cloud Development Advanced
WeChat payment cloud call (cloud payment), can quickly call WeChat payment open capacity without access, developers do not need to care about certificates, signatures, do not need to rely on third-party modules, eliminate the risk of leakage of certificates, payments and other sensitive information; Simply bind the WeChat payment merchant number to the cloud development console of developer tool 1.02.2005111 (May 11, 2020), and you can access WeChat payment natively in the cloud development after the binding is complete.
To open WeChat payment cloud call, first of all, the small program has opened WeChat payment, and WeChat payment is not supported by personal small programs, the need for enterprise accounts, and secondly, the need for small programs have been bound to the merchant number. Once these two conditions are met, we can open in the Cloud Development Console (note the version of the developer tool) - Settings - Global Settings.
Click to add the merchant number after the account binding, this time bound WeChat payment merchant number administrator WeChat will receive a template message for authorization confirmation, click on the template message will pop up the service provider assistant program, confirm the authorization can be in the cloud development console to see the binding status is "bound", and JS API permissions will also show "authorized."
jsapi and api refund rights authorization, you need to go to WeChat Payment Merchant Platform - Product Center - My authorized products to confirm the authorization to complete the authorization before you can call WeChat payment related interface capabilities. If you don't see my licensed product in your product center, you can click on the link: Licensed product
Using WeChat Payment Cloud Calls to implement full payment functionality 3 generally 4 steps (some of the next steps in code writing are integrated):
wx.cloud.callFunction
call the cloud function (such as the cloud function named pay), and the product name, commodity prices and other information passed to the pay cloud function;
CloudPay.unifiedOrder()
in the pay cloud function, parameters include the received commodity information, the cloud function environment id, and the need to fill in the result notification callback function (such as the function named paynotice) to receive asynchronous payment results;
wx.cloud.callFunction
success callback function (that is, to get the object returned by the cloud
wx.requestPayment
to initiate payment, and the payment object (field) returned from the pay cloud function contains all the information (parameters) required for this interface;
We can call the pay cloud function by an event handler such as call PayPay when clicking on a button component on a small program's wxml page, such as the pay.wxml page:
<button bindtap ="callPay">发起支付</button>
Then enter the event handler callPay in the pay.js, the name of the called payment cloud function is pay (arbitrary name), note that the successful callback function is written as follows, here the payment process of the first and third steps together:
In
const payment = res.result.payment
wx.requestPayment({...payment})
change (for small white users only). Because there are a lot of small white users have no foundation, but weChat payment is more interested, so the content of this section, will introduce a little more trivial.
callPay(){
wx.cloud.callFunction({
name: 'pay', //云函数的名称,在后面我们会教大家怎么建
success: res => {
console.log(res)
const payment = res.result.payment
wx.requestPayment({
...payment,
success (res) {
console.log('支付成功', res) //为方便,只打印结果,如果要写支付成功之后的处理函数,写在这后面
},
fail (err) {
console.error('支付失败', err)
//支付失败之后的处理函数,写在这后面
}
})
},
fail: console.error,
})
},
Then in the cloud function root folder cloudfunctions right-click, select "New Nodejs cloud function", create a new cloud function pay, and then enter the following code in index.js, and then make some changes (note that the parameter name does not change, case should also be written as is, do not understand you copy):
body
for your business name (store name) - the class name of the sale of goods, the code has a reference;
outTradeNo
the merchant order number, 32 characters, can only be numbers, case letters - if you are in debugging learning, pay attention to change this every time, lest it be repeated;
subMchId
merchant ID or sub-merchant
ID,
fill
in
the cloud
development
console - settings
-
global settings - WeChat payment configuration in the merchant number can also;
totalFee
the amount paid, the unit is divided, fill in 100, is a dollar, note that this is a numerical format, do not write into a string format (do not add single quotes or double quotes);
envId
your result notification callback cloud function is located in the environment ID,
functionName
result notification cloud function name (customizable), you
can
see in the
cloud
development console - settings - environment settings, note is the environment
ID,
not the environment name, it is best to copy directly;
After modifying, click on index .js under the pay cloud function directory, and then right-click to select "Cloud function incremental upload: update file" or right-click cloud function root folder cloudfunctions, select "Upload and deploy: cloud installation dependency (do not upload Node_modules) "
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": "HackWeek案例-教学费用",
"outTradeNo" : "122775224070323234368128", //不能重复,否则报错
"spbillCreateIp" : "127.0.0.1", //就是这个值,不要改
"subMchId" : "1520057521", //你的商户ID或子商户ID
"totalFee" : 100, //单位为分
"envId": "xly-xrlur", //你的云开发环境ID
"functionName": "paysuc", //支付成功的回调云函数,先可以随便写,比如写paysuc,后面会教你怎么建
"nonceStr":"F8B31E62AD42045DFB4F2", //随便弄的32位字符串,建议自己生成
"tradeType":"JSAPI" //默认是JSAPI
})
return res
}
You can then click on the "Start Payment" button in the developer tool's simulator, and the payment QR code will pop up, and the scan code will pay, or you can use a preview or real-world debugging.
The outTradeNo here is generated by itself, we can use the timestamp
Date.now().toString()
or add the random numberDate.now().toString()+Math.floor(Math.random()*1000).toString()
while the nonceStr is a string of 32 bits or less, we can use the user's openid and timestamps are stitched together (you can also use other methods), such as the following user's openid-
then capital letters, and finally add the timestamp string"oUL-m5FuRmuVmxvbYOGuXbuEDsn8".replace('-','').toUpperCase()+Date.now().toString()
We can call
cloudPay.queryOrder()
in the cloud function to check the payment status of the order
cloudPay.refund()
initiate a refund of the order that has been paid successfully.
The following code is simply to query the order and request a refund simple demo, really want to use these interfaces in the actual development, are need to be combined with the cloud development database, especially when applying for refund development must be treated with caution.
Once you've created a new cloud function using the developer tool, and then entered the following code in index.js and deployed it to the cloud, you can query the order information by calling the cloud function:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async(event, context) => {
const res = await cloud.cloudPay.queryOrder({
"sub_mch_id":"1520057521",
//商户订单号,需是云支付成功交易的订单号
"out_trade_no":"122775224070323234368128",
//微信订单号可以不必写
// "transaction_id":"4200000530202005179572346100",
//任意的32位字符
"nonce_str":"C380BEC2BFD727A4B6845133519F3AD6"
})
return res
}
Use the developer tool to create a new refundorder cloud function, and then enter the following code in index.js, the amount of the refund is less than the amount of the transaction, you can achieve a partial refund;
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
})
exports.main = async(event, context) => {
const res = await cloud.cloudPay.refund({
"sub_mch_id":"1520057521",
"nonce_str":"5K8264ILTKCH16CQ2502SI8ZNMTM67VS",
"out_trade_no":"122775224070323234368128",//商户订单号,需是云支付成功交易的订单号
"out_refund_no":"122775224070323234368128001",//退款单号,可以自定义,建议与订单号相关联
"total_fee":100,
"refund_fee":20,
})
return res
}
In the cloud function that initiated the payment earlier, we wrote an
functionName
result to notify the cloud function paysuc that the paysuc cloud function will not be called until the order payment is successful. W
e can handle tasks in the payment success callback function, such as storing important information about order payment to a database, sending a successful payment subscription message to the user, and getting the user's Union ID, and so on. T
o handle these tasks, you first need to understand what data the paysuc cloud function will receive after the order payment is successful.
We can print the object of the paysuc cloud function, and we can learn that the object contains information similar to the following structure, which is the key to our task of handling the paysuc cloud function:
"appid": "wxd2********65e",
"bankType": "OTHERS",
"cashFee": 200,
"feeType": "CNY",
"isSubscribe": "N",
"mchId": "1800008281",
"nonceStr": "F8B31E62AD42045DFB4F2",
"openid": "oPoo44....t8gCOUKSncFI",
"outTradeNo": "1589720989221",
"resultCode": "SUCCESS",
"returnCode": "SUCCESS",
"subAppid": "wxda99a********57046",
"subIsSubscribe": "N",
"subMchId": "1520057521",
"subOpenid": "oUL********GuXbuEDsn8",
"timeEnd": "20200517211001",
"totalFee": 2,
"tradeType": "JSAPI",
"transactionId": "42000********178943055343",
"userInfo": {
"appId": "wxd********046",
"openId": "oUL-m5F********GuXbuEDsn8"
}
To send a subscription message, we first need to go to request a successful subscription message template for order payment, such as the template below, we need to pay attention to the specific format corresponding to each attribute in the subscription message, as well as the specific requirements of the format, such as the amount of payment and the format of the payment time:
商品名称{{thing6.DATA}}
支付金额{{amount7.DATA}}
订单号{{character_string9.DATA}}
支付时间{{date10.DATA}}
温馨提示{{thing5.DATA}}
To send a subscription message, you need to call the interface
wx.requestSubscribeMessage
user authorization and to have the appropriate number of authorizations, as we have learned earlier that the subscription message interface can only be recalled after the user clicks or initiates a payment callback, so we can call this interface directly in the callback function that initiated the payment above:
callPay(){
wx.cloud.callFunction({
name: 'pay', //云函数的名称,在后面我们会教大家怎么建
success: res => {
console.log(res)
const payment = res.result.payment
wx.requestPayment({
...payment,
success (res) {
console.log('支付成功', res) //为方便,只打印结果,如果要写支付成功之后的处理函数,写在这后面
this.subscribeMessage() //调用subscribeMessage()函数,如果你不是箭头函数,注意this指代的对象
},
})
},
})
},
subscribeMessage() {
wx.requestSubscribeMessage({
tmplIds: [
//订阅消息模板ID,一次可以写三个,可以是同款通知、到货通知、新品上新通知等,通常用户不会拒绝,多写几个就能获取更多授权
"p5ypZiN4TcZrzke4Q_MBB1qri33rb80z-tb16Sg-Kpg",
],
success(res) {
console.log("订阅消息API调用成功:",res)
},
fail(res) {
console.log("订阅消息API调用失败:",res)
}
})
},
Then write the following code in the index .js of the paysuc cloud function, all the parameters required to subscribe to the message are from the object, we just need to modify the format slightly.
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
exports.main = async (event, context) => {
const {cashFee,subOpenid,outTradeNo,timeEnd} = event
try {
const result = await cloud.openapi.subscribeMessage.send({
touser: subOpenid,
page: 'index',
templateId: "p5ypZiN4TcZrzke4Q_MBB1qri33rb80z-tb16Sg-Kpg",
data: {
"thing6": {
"value": '零基础小程序云开发训练营'
},
"amount7": {
"value": cashFee/100 +'元'
},
"character_string9": {
"value": outTradeNo
},
"date10": {
"value": timeEnd.slice(0,4)+'年'+timeEnd.slice(4,6)+'月'+timeEnd.slice(6,8)+'日'+' '+timeEnd.slice(8,10)+':'+timeEnd.slice(10,12)
},
"thing5": {
"value": "多谢您的支持哦~爱你哦~"
}
}
})
return result
} catch (err) {
console.log(err)
return err
}
}