WeChat payment PHPSDK-explanation of WeChat public account payment code

Source: Internet
Author: User
Tags openid
This article mainly introduces the details of the payment code for the public account of PHPSDK. For more information, see here. Suppose 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.

 
 
  • "> JSAPI payment
  • "> Card payment
  • "> Scan the QR code to pay
  • "> Order query
  • "> Order refund
  • "> Refund query
  • "> Download order

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 with the following 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'Unified order payment ticket information
'; 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->SetNotify_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->SetNotify_url(dirname('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']).'/notify.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.

$notify = new PayNotifyCallBack();$notify->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::notify(array($this, 'NotifyCallBack'), $msg);

Tracking function notify file WxPay. Api. php

Public 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.

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.