WeChat public account payment implementation code for WeChat payment PHPSDK

Source: Internet
Author: User
Tags openid
This article mainly introduces information about the implementation code for paying the public account of PHPSDK, for more information, see this article.

Assume that you have applied for the payment.

1. background configuration

 
 
  • "> 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 the code to GET openid $ code =$ _ GET ['code']; $ openid = $ this-> getOpenidFromMp ($ code ); return $ openid ;}}

$ BaseUrl is used to jump back to this page. The CreateOauthUrlForCode () function is used 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',  
 ,  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.

$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

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 description of the php sdk public account payment implementation code. For more information, see other related articles on 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.