Php sdk for WeChat payment-Explanation of Public Account Payment Code and sdk details

Source: Internet
Author: User
Tags openid

Php sdk for payment-Explanation of Public Account Payment Code and sdk details

Download the latest php SDK from the payment developer documentation page

Http://mch.weixin.qq.com/wiki/doc/api/jsapi.php? Chapter = 11_1

Assume that you have applied for the payment.

1. Background Configuration

We first perform the test, so we first add the test authorization directory and the test whitelist. The authorization directory is the directory of the file to which you want to initiate the request.

For example, the jsapi initiates a request. The directory where jsapi. php is located is the test directory, and the test whitelist is the developer's number.

The formal payment authorization directory cannot be the same as the one tested; otherwise, an error is reported. If you do not fill in the authorization directory or enter an error in the white list, an error is reported.

Error example:

NaNsystem: access_denied

Not in the test whitelist

2. Configure the lib/WxPay. Config. php file

The main configuration items are as follows:

Const APPID = '';
Const MCHID = '';
Const KEY = '';
Const APPSECRET = '';

Both APPID and APPSECRET can be found in the background.
The MCHID can be found in the email sent after the payment application, and the KEY is displayed as prompted by the email.

Go to the merchant platform for configuration.

3. Access start index. php

First visit index. php and you can see the interface

The first thing we need is JSAPI payment. But check the bottom link of the Code index. php. By default, it is a demo link, which can be customized.

<Ul>
<Li style = "background-color: # FF7F24"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/jsapi. php ';?> "> JSAPI payment </a> </li>
<Li style = "background-color: #698B22"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/micropay. php ';?> "> Card payment </a> </li>
<Li style = "background-color: #8B6914"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/native. php ';?> "> Scan the QR code for payment </a> </li>
<Li style = "background-color: # CDCD00"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/orderquery. php ';?> "> Order query </a> </li>
<Li style = "background-color: # CD3278"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/refund. php ';?> "> Order refund </a> </li>
<Li style = "background-color: #848484"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/refundquery. php ';?> "> Refund query </a> </li>
<Li style = "background-color: # 8EE5EE"> <a href = "<? Php echo 'HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']. 'example/download. php ';?> "> Download order </a> </li>
</Ul>

Of course, you can also directly write your own access link.

4. JSAPI payment

Necessary code parsing:

$ LogHandler = new CLogFileHandler ("../logs/". date ('Y-m-d'). '. log ');
$ Log = Log: Init ($ logHandler, 15 );

You can use $ log-> DEBUG ('test') to print debugging information for the call log class. You can also directly use $ Log: DEBUG ('test'); for debugging.

$ Tools = new JsApiPay ();
$ OpenId = $ tools-> GetOpenid ();

The main purpose is to obtain the openid. The GetOpenid () function is defined in the WxPay. JsApiPay. php file.

Public function GetOpenid () {// obtain openid if (! Isset ($ _ GET ['code']) {// trigger return code $ baseUrl = urlencode ('HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['php _ SELF ']. $ _ SERVER ['query _ string']); $ url = $ this->__ CreateOauthUrlForCode ($ baseUrl); Header ("Location: $ url "); exit ();} else {// GET code to GET openid $ code =$ _ GET ['code']; $ openid = $ this-> getOpenidFromMp ($ code); return $ openid ;}}

$ BaseUrl is used to jump back to this page. You can continue to follow the function _ CreateOauthUrlForCode () to obtain the Openid through Auth2.0.
Reference: http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

In this case, you need to set the webpage authorization interface.

After obtaining the Openid, you can call the unified order interface for payment. Return to the file jsapi. php code $ input = new WxPayUnifiedOrder (); $ input-> SetBody ("test"); $ input-> SetAttach ("test "); $ input-> SetOut_trade_no (WxPayConfig: MCHID. date ("YmdHis"); $ input-> SetTotal_fee ("1"); $ input-> SetTime_start (date ("YmdHis ")); $ input-> SetTime_expire (date ("YmdHis", time () + 600); $ input-> SetGoods_tag ("test "); $ input-> setpolicy_url ("http://paysdk.weixin.qq.com/example/notify.php"); $ input-> SetTrade_type ("JSAPI"); $ input-> SetOpenid ($ openId); $ order = WxPayApi :: unifiedOrder ($ input); echo '<font color = "# f00"> <B> Unified order payment information </B> </font> <br/> '; printf_info ($ order); $ jsApiParameters = $ tools-> GetJsApiParameters ($ order );

The code below:

$ Input-> SetAttach ("test ");

If you change the value to $ input-> SetAttach ("test this is attach"), there will be bugs. In fact, this parameter is not necessary and can be simply removed.
Code:

$ Input-> setpolicy_url ("http://paysdk.weixin.qq.com/example/notify.php ");

Set the Url for receiving the notification of the payment result. Here is the default demo link. We can set it to ours:

$ Input-> setpolicy_url (dirname ('HTTP ://'. $ _ SERVER ['HTTP _ host']. $ _ SERVER ['request _ URI ']). '/policy. php ');

Of course, you can also choose to write it to death directly.

The unifiedOrder ($ input) function can be traced to the WxPay. Api. php file. In fact, it is to call the unified order interface.

One code that needs to be changed in WxPay. Api. php is:

// If the asynchronous notification url is not set, use the url if (! $ InputObj-> ispolicy_urlset () {$ inputObj-> setpolicy_url (WxPayConfig: policy_url); // asynchronous notification url}

If policyurl is not set, go back to the configuration file, but it is not set in the configuration file.

Therefore, you can add this configuration in the configuration file WxPay. Config. php, or directly write a default notify link.

The GetJsApiParameters () function is used to get the jsApi payment parameter to the variable $ jsApiParameters, which can be conveniently called in the following Js

Js Code in jsapi. php:

function jsApiCall() { WeixinJSBridge.invoke(  'getBrandWCPayRequest',  <?php echo $jsApiParameters; ?>,  function(res){  WeixinJSBridge.log(res.err_msg);  alert(res.err_code+res.err_desc+res.err_msg);  } ); } function callpay() { if (typeof WeixinJSBridge == "undefined"){   if( document.addEventListener ){     document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);   }else if (document.attachEvent){     document.attachEvent('WeixinJSBridgeReady', jsApiCall);      document.attachEvent('onWeixinJSBridgeReady', jsApiCall);   } }else{   jsApiCall(); } }

Click the pay now button to call the callpay () function, which calls the jsApiCall () function to open the Payment Program.
Enter the password to complete the payment.

Click "finish" on the "complete payment" page to return to the payment page. A prompt box Indicating successful payment is displayed.

This is actually the alter pop-up dialog box in the js function jsApiCall.

Res. err_msg is get_brand_wcpay_request: OK indicates that the payment is successful. Based on this, we can redirect the payment to the success page.

But this is not credible. Check whether the payment is successful or whether the business logic should be processed through notify. php.

5. notify. php of the payment result

In fact, the main code of this page is two lines.

$ Policy = new paypolicycallback ();
$ Policy-> Handle (false );

Most of the logic processes the WxPay. Policy. php file in the Handle function.

Final public function Handle ($ needSign = true) {$ msg = "OK"; // when false is returned, it indicates that the callback call yycallback in callback y fails to obtain signature verification, in this case, a direct reply fails. $ result = WxpayApi: Policy (array ($ this, 'policycallback'), $ msg); if ($ result = false) {$ this-> SetReturn_code ("FAIL"); $ this-> SetReturn_msg ($ msg); $ this-> ReplyNotify (false); return ;} else {// After the branch successfully calls back to the NotifyCallBack method, the process $ this-> SetReturn_code ("SUCCESS"); $ this-> SetReturn_msg ("OK ");} $ this-> replypolicy ($ needSign );}

Main Code:

$ Result = WxpayApi: Policy (array ($ this, 'policycallback'), $ msg); // The WxPay file of the tracking function notify. api. phppublic static function notify ($ callback, & $ msg) {// get notification data $ xml = $ GLOBALS ['HTTP _ RAW_POST_DATA ']; // If a success is returned, verify the signature try {$ result = WxPayResults: Init ($ xml);} catch (WxPayException $ e) {$ msg = $ e-> errorMessage (); return false;} return call_user_func ($ callback, $ result );}

Get the gay data through $ GLOBALS ['HTTP _ RAW_POST_DATA ']; then use the Init function to verify the signature. Code run successfully
Return call_user_func ($ callback, $ result );

That is, a callback function is called. The NotifyCallBack () function and the $ result parameter will be passed. In the NotifyCallBack function, we will call the rewritten NotifyProcess () function (this function is overwritten in notify. php)

If policyprocess () is correct, the xml Information of success is returned.

$ This-> SetReturn_code ("SUCCESS ");
$ This-> SetReturn_msg ("OK ");

And finally call the result of the function $ this-> ReplyNotify ($ needSign); echo success

The replypolicy function needs to modify a code:

Final private function ReplyNotify ($ needSign = true) {// if you need to sign if ($ needSign = true & $ this-> GetReturn_code ($ return_code) = "SUCCESS ") {$ this-> SetSign ();} WxpayApi: replypolicy ($ this-> ToXml ());}

$ This-> GetReturn_code ($ return_code) = "SUCCESS ")

Change

$ This-> GetReturn_code () = "SUCCESS ")

You can.
In this way, the entire process is over. The above mentioned transfer order parameters

$ Input-> SetAttach ("test ");

If I set the value to test this is attach (in fact, there will be a bug if there is space)

Delivered order information

You can see that the attach information is normal, of course, the payment is normal and there is no problem.

However, you will always receive the notify notification, which means that no correct result notification is returned to the server.
Print the notification data sent from the server

The attach is test + this + is + attach. That is, the space is converted to the plus sign.

The printed signature is different from the signature calculated by the program. Therefore, the receiving result is considered abnormal.

Therefore, if we want to use the attach value, there is no space, or we simply do not use this parameter.

(I am waiting to fix this bug. Maybe it's not where I am? --#)

In this way, the JsApi payment is roughly analyzed.

The above is a detailed explanation of the Payment Code for the php sdk. We will continue to add relevant information in the future. Thank you for your support for this site!

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.