WeChat payment PHP SDK WeChat public number payment code detailed _php instance

Source: Internet
Author: User
Tags openid
This assumes that you have applied for the payment

1. Background configuration

We test first, so we add the test authorization directory and the test whitelist first. The Test authorization directory is the directory where you want to initiate the requested file.

For example, the JSAPI originating request is typically the directory where jsapi.php is the test directory, and the test whitelist is the developer's number.

The official Payment authorization directory cannot be the same as the test or it will error. Do not fill out or fill in the wrong authorization directory and test white list will be an error.

Examples of error:

Nansystem:access_denied

Not on the test white list

2. Configuring the lib/wxpay.config.php File

The main configuration is four items:

Const APPID = ";
Const MCHID = ";
Const KEY = ';
Const APPSECRET = ";
Both APPID and Appsecret can be found in the background.
Mchid can be found in the e-mail sent after the application, KEY is based on the mail prompt

Go to the Merchant platform configuration.

3. Access to start index.php

First visit index.php you can see the interface

The first thing we need is a JSAPI payment. But see the code index.php the bottom link. He defaults to a demo link, which we can customize to

 
  
  
  • ">jsapi Payment
  • "> Credit card payment
  • "> Scan Code payment
  • "> Order Enquiry
  • "> Order Refunds
  • "> Refund Enquiry
  • "> Download Order

Of course you can also directly write dead links for your own visit.

4. JSAPI Payment

Necessary code parsing:

$logHandler = new Clogfilehandler (".. /logs/". Date (' y-m-d '). Log '); $log = Log::init ($logHandler, 15);

The Call log class can be passed $log->debug (' Test '); Print debugging information. In fact, you can also use the $Log directly::D ebug (' Test '); To debug

$tools = new Jsapipay (), $openId = $tools->getopenid ();

Primarily to get OpenID where the Getopenid () function is defined in the file WxPay.JsApiPay.php file

Public Function Getopenid () {//through code to obtain OpenID if (!isset ($_get[' code ')) {  //Trigger return code 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 actually in order to jump back to this page. Can continue to trace function __createoauthurlforcode () is actually through the Auth2.0 to get OpenID

Reference Link: http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

This will require you to put the Web licensing interface is also set up.

Get to Openid to invoke the unified next single interface for payment. Back to the file jsapi.php 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 () +)), $input->setgoods_tag ("test"), $input->setnotify_url (" Http://paysdk.weixin.qq.com/example/notify.php "); $input->settrade_type (" JSAPI "); $input->setopenid ($ OPENID); er = Wxpayapi::unifiedorder ($input); Echo ' Unified Single Payment order information
';p rintf_info (er); $jsApiParameters = $tools->getjsapiparameters (er);

Here's the code:

$input->setattach ("test");

If you change the value to $input->setattach ("Test this is attach"), there will be a bug after that, in fact, this parameter is not necessary simply can be removed.

Code:

$input->setnotify_url (http://paysdk.weixin.qq.com/example/notify.php);

is to set the URL to receive notification of payment results here is the default demo link we can set to our:

$input->setnotify_url (dirname (' http://' $_server[' http_host '].$_server[' Request_uri ']). ' /notify.php ');

Of course you can also choose to write directly to death.
Where the function Unifiedorder ($input) can be WxPay.Api.php in the file tracking, in fact, is called the Unified next single interface.

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

The asynchronous notification URL is not set, then the URL in the configuration file is used    if (! $INPUTOBJ->isnotify_urlset ()) {      $inputObj->setnotify_url ( Wxpayconfig::notify_url);//Asynchronous Notification URL    }

is when the Notifyurl is not set to go back to the configuration file, but the configuration file is not set at all.

So you can choose to add this configuration to the profile WxPay.Config.php, or you can write a default notify link directly.

The function getjsapiparameters () is to get the parameters of the JSAPI payment to the variable $jsApiParameters conveniently called in the JS below

Jsapi.php JS in the code:

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 ();}}

Where click the Pay Now button is called the Callpay () function, he has the call Jsapicall () function to open the payment program.
Then enter the password to complete the payment.

After completing the payment page click Finish will return to this payment page and pop up the payment success prompt box

This is actually the JS function jsapicall inside the Alter popup dialog box

Where res.err_msg for Get_brand_wcpay_request:ok indicates that the front-end judgment of the payment is successful, we can jump to the success page based on this payment.

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

5. Notification of payment Results notify.php

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

$notify = new Paynotifycallback (); $notify->handle (false);

Most of the logic handles the file in the Handle function WxPay.Notify.php

Final public Function Handle ($needSign = true) {$msg = "OK")//when the return false indicates that the call to Notifycallback callback in notify failed to get the signature check failure, The direct reply fails at this time $result = wxpayapi::notify (Array ($this, ' notifycallback '), $msg); if ($result = = False) {  $this->setreturn_code ("FAIL");  $this->setreturn_msg ($msg);  $this->replynotify (false);  Return } else {  //The branch is successfully callback to the Notifycallback method, and the process  $this->setreturn_code ("SUCCESS") after processing is completed;  $this->setreturn_msg ("OK"); } $this->replynotify ($needSign); }

Main code:

$result = wxpayapi::notify (Array ($this, ' notifycallback '), $msg);

Trace function notify file WxPay.Api.php

public static function Notify ($callback, & $msg) {//Get the data of the notification $xml = $GLOBALS [' http_raw_post_data '];//If the return succeeds verify the signature try {  $result = Wxpayresults::init ($xml);} catch (Wxpayexception $e) {  $msg = $e->errormessage ();  return false; }  return Call_user_func ($callback, $result);}

by $GLOBALS [' Http_raw_post_data ']; Get gay data then the Init function verifies the signature and so on. Verification of successful run code

Return Call_user_func ($callback, $result);

That is, call a callback function, Notifycallback () function and pass parameters $result in the Notifycallback function will call our overridden notifyprocess () function (this function is overridden in notify.php)

Notifyprocess () No problem will be set to return success XML information

$this->setreturn_code ("SUCCESS"); $this->setreturn_msg ("OK");

And finally call the function $this->replynotify ($needSign); The results of Echo success

The function replynotify need to modify a code:

Final Private Function replynotify ($needSign = True) {//if required signature if ($needSign = = True &&   $this->getreturn_c Ode ($return _code) = = "SUCCESS") {  $this->setsign ();} Wxpayapi::replynotify ($this->toxml ()); } $this->getreturn_code ($return _code) = = "SUCCESS")

Switch

$this->getreturn_code () = = "SUCCESS")

Can.

So the whole process is over. The delivery order parameters are mentioned above

$input->setattach ("test");

If I set the value to test this is attach (as long as there are spaces there will be bugs)
Delivery of order information

Can see the attach information is normal, of course, pay is normal without any problems.

However, the discovery always receives a notify notification, which means that there is no correct result notification returned to the server.

The notification data sent by the print server

You can see that attach is Test+this+is+attach, that is, the space is converted to a plus

Print the received signature differs from the signature found by the program, that is, the received result is considered to be abnormal.

So if we want to use attach, we can't have a space, or we can simply not use this parameter.

(Wait for the bug to be fixed, or is there a place on my side?) - -#)

So the payment of the JSAPI payment is done in a rough analysis.

  • Related Article

    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.