In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares with you is about how WeChat Mini Programs realizes cloud payment. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
I. Preface
Students who have played with WeChat Mini Programs Cloud Development basically know that WeChat Mini Programs Cloud Development currently supports cloud payment.
So what is the whole payment process supported by the ability of cloud payment?
For example: what the logical processing of users should be before, during and after payment, and how to design it will be more safe and reduce the probability of error.
Then this paper mainly introduces the use of cloud payment and how to design the order system and payment process under cloud payment.
By the way: WeChat Pay function only supports enterprise subject invocation.
Second, train of thought analysis
The calling process of cloud payment is roughly divided into the following four steps:
1. Obtain the parameters of exemption from authentication
After passing basic parameters such as amount and commodity information on Mini Program, call the cloud function to obtain the authentication-free parameters.
2. Pass the authentication-free parameter to the payment API of Mini Program.
SCF returns an authentication-free parameter, which is used as an input parameter for payment API on Mini Program.
3. User payment
WeChat Pay is transferred to the user to pay / cancel payment.
4. Cloud function specified in Wechat callback
Call back this cloud function after the payment is successful.
If the user cancels the payment, this cloud function will not be called back.
Then, according to the above four steps, we can analyze when the order is created and when the payment status of the order has changed.
The order should be created by inserting information such as the order number into the database after obtaining the authentication-free parameters in the first step.
At this time, the payment status of the order should be pending payment.
At the same time, we can also know that the change of the payment status of the order should be made in the fourth step. If the payment is successful, change the payment status of the order to the payment success.
Links to relevant official documents:
Cloud payment documents
Cloud payment callback document
The Mini Program end calls up the payment API document
Third, cloud pay small case 1. Cloud function 1-1. Get the authentication-free parameter cloud function (wxPay)
This cloud function is mainly used to obtain the parameters required to pay for API, and to create an order and insert it into the database.
Screenshot of the result of successfully calling the sample
Implementation code
/ / Cloud function entry file const cloud = require ('wx-server-sdk') cloud.init ({env: cloud.DYNAMIC_CURRENT_ENV}) const db = cloud.database () exports.main = async (event) = > {const wxContent = cloud.getWXContext () / / openid const openid = wxContent.OPENID const appid = wxContent.APPID const totalFee = event.totalFee / / payment amount (in minutes) const body = event.body / / Commodity name Const outTradeNo = createOutTradeNo () / order number / / get the authentication-free payment parameter const payMent = await cloud.cloudPay.unifiedOrder ({"body": body "outTradeNo": outTradeNo, "spbillCreateIp": "127.0.0.1", "subMchId": "merchant number", / / merchant number "totalFee": totalFee, "envId": "corresponding cloud environment id" / / Cloud environment id "functionName": "payCallBack" / / payment callback cloud function}) / / create order const nowTime = new Date (). GetTime () const orderObj = {_ openid: openid, appid: appid, outTradeNo: outTradeNo, totalFee: totalFee * 0.01, payStatus: 'wait', createTime: nowTime, updateTime: nowTime, deleteTime: null } await addOrder (orderObj) return payMent} / * * create a random unique order number (32 bits) * / const createOutTradeNo = () = > {let outTradeNo = new Date () .getTime () / get the current 13-bit timestamp let numStr = '0123456789' Let randomStr ='; for (let I = (32-13); I > 0;-- I) {randomStr + = numStr [Math.floor (Math.random () * numStr.length)] } outTradeNo + = randomStr return outTradeNo} / * * create an order into the database * / const addOrder = async (orderObj) = > {return await db.collection ('order') .add ({data: orderObj}) .then (res = > {console.log ("create order success = >", res, orderObj)}) .catch (err = > {console.log ("create order exception = >", err, orderObj)})} 1-2. Payment callback cloud function (payCallBack)
After the payment is successful, the Wechat server will call this cloud function and bring along the payer's order number, openid, appid and other information.
Developers can use this to determine which order is currently being called back.
Callback document
Sample screenshot of successful callback result
Implementation code
/ / Cloud function entry file const cloud = require ('wx-server-sdk') cloud.init ({env: cloud.DYNAMIC_CURRENT_ENV}) const db = cloud.database () / / Cloud function entry function exports.main = async (event) = > {console.log ("callback returned object = >" Event) / / judgment condition if (event.returnCode = = 'SUCCESS') {if (event.resultCode = =' SUCCESS') {/ / query condition const whereObj = {appid: event.subAppid, / / Mini Program's APPID _ openid: event.subOpenid, / / Mini Program user's openid outTradeNo: event.outTradeNo / / order number of merchant number} / / Update object const updateObj = {transactionId: event.transactionId, / / order number totalFee: event.totalFee * 0.01of WeChat party, / / amount received by WeChat party timeEnd: event.timeEnd, / / payment end time payStatus: 'success' UpdateTime: new Date () .getTime ()} / / Update order await updateOrder (whereObj, updateObj)}} / / return protocol and input agreement of payment callback (this structure must be returned See the document) return {errcode: 0, errmsg: event.resultCode}} / * * Update the payment status of the order * / const updateOrder = async (whereObj, updateObj) = > {return await db.collection ('order') .where (whereObj) .update ({data: updateObj})} 2. Mini program side (js code) / / pages/wxPay/wxPay.jsPage (initial data of {/ * page * / data: {}, / * Life cycle function-listen page load * / onLoad () {}, / * Life cycle function-listen page display * / onShow () {} / * * pay click monitoring * / async payTap () {const totalFee = 2 const body = 'payment test' wx.showLoading ({title: 'adjust WeChat Pay', mask: true}) / / get the payment exemption parameter const payMentRes = await this.getPayMent (totalFee, body) wx.hideLoading ({success: (res) = > {}) }) / / Mini Program payment API const payRes = await this.wxPay (payMentRes.result.payment) / / return result print console.log (payRes)}, / * Mini Program payment API * @ param {object} payment payment exemption parameters * / wxPay (payment) {return new Promise ((resolve, rejects) = > {wx.requestPayment ({... payment) Success (res) {resolve ({status: 'success', res: res})}, fail (err) {resolve ({status:' fail', res: err})} / * * obtain payment exemption parameter * @ param {number} totalFee payment amount in * @ param {string} body Product name * / getPayMent (totalFee, body) {return new Promise ((resolve, rejects) = > {wx.cloud.callFunction ({name: 'wxPay', data: {totalFee, body}) Success (res) {resolve (res)}, fail (err) {resolve (err)},}) 3. Payment result
Client end
Merchant end
4. Code directory structure
4. Why do you write like this
Perhaps some students have also used Wechat cloud payment capability, but have not used the above-mentioned payment callback cloud function.
But it is also possible to get the result of the user's payment.
The figure below is as follows
In fact, the payment API (wx.requestPayment ()) on the side of the mini program can also return the current payment result. You can indeed use the results of this callback to determine whether the payment was successful or not.
In that case, why bother to write a payment callback cloud function to get the payment result?
Seeing here also shows that you have seen the whole implementation process, and if you have any questions about why you want to achieve it in this way, you should be able to find some answers for yourself.
Apart from the minor problems related to development specification and optimization, I will talk about a very fatal reason here.
WeChat Mini Programs pay API (wx.requestPayment ()) has a fatal problem on the IOS side.
When the user pays, he will go to the following page.
When the user does not click the finish button, WeChat Mini Programs's payment API (wx.requestPayment ()) callback will not be triggered.
In other words, Mini Program itself can not get the user's payment results.
If the user exits Wechat directly, Mini Program will be destroyed. At this point, how to change the status of the order?
Tips: this problem doesn't happen on the Android side. Students who are interested can practice the following by themselves.
Thank you for reading! This is the end of the article on "how to realize Cloud payment by WeChat Mini Programs". I hope the above content can be of some help to you, so that you can learn more knowledge. If you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.