Let’s first look at the flow chart given by wechat official:
In this picture, developers only need to focus on the applets and cloud functions; The cloud function does a lot of parameter processing, so we don’t need to pay attention to the certificate, signature, etc., just need to call the corresponding function. Here is a general description of the payment process:
1. The small program project should have a cloud development environment. Before using cloud capabilities, complete the initialization of cloud capabilities, that is, configure them in app.js under the root directory;
Wx.cloud. init({env: 'environment ID ', traceUser: true,})Copy the code
Two, to bind the small program and merchant number, and then add the merchant number in the cloud console, after adding, need to be super administrator in wechat Pay merchant assistant public account authorization, the first time may not be so fast to receive authorization information; The refund right needs to be confirmed and authorized in the products authorized by the merchant number platform;
3. Right-click the cloudFunctions of the project and create a new Node.js cloudfunction (a single cloudfunction and a result callback cloudfunction). After creating the cloudfunction, upload and deploy the cloudfunction.
Write the order function: order by cloudpay.unifiedOrder (). Note that some parameters are not required to be filled in. You can refer to the case given by wechat official.
exports.main = async (event, context) => { const res = await cloud.cloudPay.unifiedOrder({ "body" : "Description", "outTradeNo" : "1217752501201407033233368018", "spbillCreateIp" : "127.0.0.1", "subMchId" : "merchants", "totalFee" : 1, "envId" : "id" cloud environment, / / "functionName" : "pay_cb / / callback function results cloud"})}Copy the code
You don’t need to pass random numbers, signatures, and so on. Note that the name of the callback function and the environment ID. Event is the parameter passed to the cloud function by the client.
Writing method of client:
Wx.cloud.callfunction ({name: 'function name ',// order cloud function data: {// pass data //... }, success: res => {const payment = res.result.payment wx.requestPayment({// payment API... payment, success (res) { console.log('pay success', res) }, fail (err) { console.error('pay fail', err) } }) }, fail: console.error, })Copy the code
Callback result function must pay attention to return parameters to the wechat server, otherwise it will always callback;
If (event.resultCode == 'SUCCESS'){// Submit data successfully according to the business results in result_code, inform the server // update the data in the cloud database const res = {errcode:0,errmsg: ""} return res}Copy the code
So the whole payment process is finished; Compared with the traditional way of payment, it is much simpler and more secure. If you have a merchant number, you can write a demo to try!