The development of micro channel small program, micro channel payment is often used, we simply comb the operation process and steps

First look at the development of the WeChat payment document: pay.weixin.qq.com/wiki/doc/ap…

Except for the swept payment scenario, the merchant system first invokes the unified ordering interface to generate the pre-payment transaction order in the background of wechat Payment service, and then returns the correct pre-payment transaction session id, and then generates the transaction string to initiate payment in different scenarios such as sweep code, JSAPI, APP and small program. For the specific API interface, please refer to “API List “.

1, the first step is to prepare a good micro channel small program has been certified, and access to the micro channel payment function. Specific how to operate, please check, pay.weixin.qq.com/static/pay_… . Then prepare the appID and AppSecret of wechat mini program, as well as the McH_id and key of the associated merchant

{appID :' small program ID, necessary, whether to obtain the user's openID, or unified order (wechat small program must be) need to ', AppSecret :' small program key, access information ', McH_id: 'Merchant number, necessary for unified order', key:' merchant key '}Copy the code

2, use first wx. Login, the user’s information, the openid, reference documents: developers.weixin.qq.com/miniprogram…

The client in the small program, the use of wx. Login, methods to obtain the user’s code, then call in the developer server backstage auth. Code2Session (developers.weixin.qq.com/miniprogram…). , use code to exchange openID, unionID, session_key and other information

wx.login({ success (res) { console.log(res); If (res.code) {wx.request({url: url,// back end interface, pass code, then back end request for user information data: {code: res.code, user_name:e.nickName }, success: (res) => { console.log(res.data); if(res.data.ret){ let userInfo = Object.assign(e,res.data) wx.setStorage({ key:"userInfo", data:JSON.stringify(userInfo) }) wx.hideLoading() wx.stopPullDownRefresh() }else{ wx.showToast({title: 'Logon failed ',icon:'error',duration:2000}) wx.hideloading () wx.stopPulldownRefresh ()}}})} else {console.log(' Logon failed! ' + res.errMsg) } } })Copy the code

Back-end request interface

GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
Copy the code

3. After obtaining user information, we began to place unified orders

Application scenario: The merchant invokes this interface in the small program to generate the pre-payment transaction order in the background of wechat Payment service, and then returns the correct pre-payment transaction to initiate the payment.

Interface API: URL: api.mch.weixin.qq.com/pay/unified…

Request parameters, the reference document: pay.weixin.qq.com/wiki/doc/ap…

I here according to the demand, is to run this interface at the back end, so in the small program client, just need to send a request, and then get the returned information, and then run wechat payment interface

(1) Send requests to the back end and run the unified ordering API. Since the small program must use the user’s OpenID to use wechat Payment,

GetPayMomey (e){// The user ID already exists locally at login time, Let info = wx.getStoragesync ('userInfo') let that = this wx.showloading ({title: 'Obtaining ', Mask :"true"}) var url = app.urldata. url + '/wx/create_order' var random = math.random () var userInfo = JSON.parse(info) wx.request({ url: Url, data: {random: random, order_id: e.c. with our fabrication: urrentTarget. Dataset. Id, / / order IO, Openid: userinfo.user_info. openID}, header: {'content-type': 'application/json' // default value}, success: (res) => { console.log(res.data); If (res.data.ret){wx.hideloading () that.payweixin (res.data)}else{ wx.hideLoading() wx.showToast({title: res.data.err_code_des,icon:'none',duration:2000}) wx.stopPullDownRefresh() } } }) },Copy the code

(2) call pay interface, need to use the signature, the specific reference documentation, pay.weixin.qq.com/wiki/doc/ap…

I’m using the MD5 signature type here

Main parameters

paySign=MD5(appId=wxd678efh567hg6787&nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS&package=prepay_id=wx2017033010242291fcfe0 db70013231072&signType=MD5&timeStamp=1490840662&key=qazwsxedcrfvtgbyhnujmikolp111111) = 22D9B4E54AB1950F51E0649E8810ACD6  wx.requestPayment( { "timeStamp":"", "nonceStr": "", "package": "", "signType": "MD5", "paySign": "", "success":function(res){}, "fail":function(res){}, "complete":function(res){} })Copy the code

Here’s what I did

PayWeixin (data){let that = this let random = (math.random ()).toString(); Let timestamp=(new Date().getTime()).toString() Let obj = {appId:appId, nonceStr:random, let McH_key = 'merchant key'; package:"prepay_id="+data.prepay_id, signType:'MD5', TimeStamp: timeStamp} let arr = object.keys (obj).sort().map(item => {return `${item}=${obj[item]}`; }); Let STR = arr.join('&') + '&key=' + McH_key; console.log(str); Let paySign = MD5 (STR).toupperCase () console.log(paySign); wx.requestPayment({ "timeStamp":timestamp, "nonceStr": random, "package": "prepay_id="+data.prepay_id, "signType": "MD5", "paySign": PaySign, "success":function(res){// Use setTimeout to execute a callback. SetTimeout (function(){that.payOrderSuccess(data.order_id)},200)}, "fail":function(res){ console.log(res); if (res.errMsg==='requestPayment:fail cancel') { wx.showToast({title: 'User cancels payment ',icon:' None ',duration:2000})} else {wx.showtoast ({title: res.errMsg,icon:'none',duration:2000}) } }, "complete":function(res){} }) },Copy the code

(3) Sometimes error: requestPayment:fail cancel, prompt: payment signature failed, official send the user to cancel the payment. However, if you report this mistake, in addition to canceling the payment, there may be a sign error on the top. So you have to pay attention to some pits

·· The signed key value must be the hump value, except package

The argument is a string

··· The signed string must be followed by the key, the merchant key

After MD5 signing, be sure to uppercase

SetTimeout = setTimeout = setTimeout = setTimeout = setTimeout = setTimeout = setTimeout

4. MD5 signature