PHP: WeChat applet WeChat payment server integration instance details

Source: Internet
Author: User
This article mainly introduces the details of the integration instance of the mini-program payment server and the relevant information for source code download. if you need such information, refer to the mini-program payment server set.

Theoretically, all the work of integrating payment can be done on the small program end, because the small program js has the ability to access the network, but for security, no sensitive key is exposed, in addition, the official ready-made php demo can be used to save effort, so the signature and request are signed and initiated on the server side, and the applet end only makes one wx. the connection of the requestPayment (OBJECT) interface.

The overall integration process is similar to that of JSAPI and APP. you must place an order in a unified manner and then request the returned result for payment.

Three steps in total:

1. the applet exchanges the code returned by wx. login for openid. 2. the server places a uniform order. 3. the applet initiates a payment.

Prepare these items in advance:

APPID = 'wx426b3015555a46be';MCHID = '1900009851';KEY = '8934e7d15453e97507ef794cf7b0519d';APPSECRET = '7813490da6f1265e4901ffb80afaa36f';

Php sdk. for the download link, see the end of the article.

1st and 4 are obtained when applying for a mini-app, and 2nd and 3 are obtained when applying for activation and payment. Note that 3rd and 4 are similar, but they are actually two things, obfuscation of the two will cause the signature to fail.

Place an order at the peer end and get prepay_id

1. create a Controller and introduce the WxPay. Api. php class.

 

Then you can use index. php/wxpay for access requests.

2. modify the configuration file WxPay. Config. php.

Apply for the corresponding key by yourself

3. implement the index method

Function index () {// initialization value object $ input = new WxPayUnifiedOrder (); // The parameter specifications mentioned in this document: seller Name-sales product category $ input-> SetBody ("smart mall-mobile phone"); // the order number should be sent to the server by the applet, which is generated when the user places an order, the value in the demo is a generated timestamp $ input-> SetOut_trade_no ('000000'); // the fee should be transmitted to the server by the applet, inform the server of the amount payable when the user places an order. The value in the demo is 1, that is, 1 cent $ input-> SetTotal_fee ("1"); $ input-> SetNotify_url ("http://paysdk.weixin.qq.com/example/notify.php "); $ input-> SetTrade_type ("JSAPI"); // it is sent from the applet to the server $ input-> SetOpenid ($ this-> input-> post ('openid ')); // place an order in a unified manner and return order, which is an array $ order = WxPayApi: unifiedOrder ($ input ); // return the header ("Content-Type: application/json") to the applet in json format; echo json_encode ($ order );}

Note 1: The nonce_str mentioned in this document is not submitted, but is filled in by the sdk.

The source is in line 55th of WxPay. Api. php.

$ InputObj-> SetNonce_str (self: getNonceStr (); // random string

Note 2: The sign has also been kindly added to setSign. the source is in line 111st of WxPay. Data. php and MakeSign ().

/*** Generate the signature * @ return signature. This function does not overwrite the sign member variable. to set the signature, call the SetSign method to assign a value */public function MakeSign () {// signature Step 1: sort the parameter ksort ($ this-> values) by lexicographically; $ string = $ this-> ToUrlParams (); // signature Step 2: add KEY $ string = $ string. "& key = ". wxPayConfig: KEY; // signature Step 3: MD5 encryption $ string = md5 ($ string); // signature Step 4: convert all characters to uppercase $ result = strtoupper ($ string); return $ result ;}

4. call the logon interface in the applet to obtain the openid

Send a login request, get the code, and then submit the code in exchange for the openId

Wx. login ({success: function (res) {if (res. code) {// initiate a network request wx. request ({url: 'https: // api.weixin.qq.com/sns/jscode2session? Appid = wx9114b997bd86f *** & secret = d27551c7803cf16015e536b192 ***** & js_code = '+ res. code + '& grant_type = authorization_code', data: {code: res. code}, success: function (response) {console. log (response) ;}})} else {console. log ('failed to get the user logon status! '+ Res. errMsg )}}});

We can see from the console that we have successfully obtained the openid, and the rest is to upload it to the server. the server side $ this-> input-> post ('openid') is waiting for receiving it.

5. send a request from the applet to the https://lendoo.leanapp.cn/index.php/wxpayinitiator and submit a uniform ticket

// The unified order interface is connected to wx. request ({url: 'https: // lendoo.leanapp.cn/index.php/WXPay', data: {openId: openId}, success: function (response) {console. log (response) ;}, header: {'content-type': 'application/x-www-form-urlencoded '},});

The following result is displayed.

{ "appid": "wx9114b997bd86f8ed", "mch_id": "1414142302", "nonce_str": "eEICgYFuGqxFRK6f", "prepay_id": "wx201701022235141fc713b8f80137935406", "result_code": "SUCCESS", "return_code": "SUCCESS", "return_msg": "OK", "sign": "63E60C8CD90394FB50E612D085F5362C", "trade_type": "JSAPI"}

The premise is that the https://lendoo.leanapp.cn is already on the whitelist:

6. the applet calls the payment API

// Initiate payment var appId = response. data. appid; var timeStamp = (Date. parse (new Date ()/1000 ). toString (); var pkg = 'prepay _ id = '+ response. data. prepay_id; var nonceStr = response. data. nonce_str; var paySign = md5.hex _ md5 ('appid = '+ appId +' & nonceStr = '+ nonceStr +' & package = '+ pkg +' & signType = MD5 & timeStamp = '+ timeStamp + "& key = d27551c7803cf16 *** e536b192d5d03b "). toUpperCase (); console. log (paySign); console. log (appId); wx. requestPayment ({'timestamp': timeStamp, 'noncestr ': nonceStr, 'Package': pkg, 'signtype': 'md5', 'paysign': paySign, 'success ': function (res) {console. log ('success'); console. log (res );}});

Simulator Test. a QR code is displayed for scanning.

An error was reported:

ErrMsg: "requestPayment: fail" err_code: 2err_desc: "Payment verification signature failed"

The key must be added to the signature !!! 'Appid = '+ appId +' & nonceStr = '+ nonceStr +' & package = '+ pkg +' & signType = MD5 & timeStamp = '+ timeStamp + "& key = d27551c7803cf16 * e536b192d5d03b "is complete.

But the key is not mentioned in the document.

Payment successful

For more PHP: explanation of the integration instance of the mini-program payment server and the source code download related articles, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.