Micro-letter Payment PHP sdk--Public number payment code detailed _php instance

Source: Internet
Author: User
Tags openid

Download the latest PHP SDK on the micro-credit Payment Developer Documentation page

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

This assumes that you have applied for a micro-letter payment

1. Micro-letter background configuration as shown

We test first, so add the test authorization directory and the test whitelist. Test Authorization directory is the directory where you want to initiate a micro-letter request.

For example, the JSAPI initiation request is typically the directory where the jsapi.php resides for the test directory, and the white list is the developer's micro-signal.

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

Error Sample:

Nansystem:access_denied

Not on the test white list

2. Configure lib/wxpay.config.php Files

The main configuration of the four items:

Const APPID = ';
Const MCHID = ';
Const KEY = ';
Const Appsecret = ';

APPID and Appsecret can be found in the micro-letter backstage.
Mchid can be found in the message sent after the application for the micro-letter payment, KEY according to the mail prompt

To the merchant platform configuration can be.

3. Visit Start index.php

First visit index.php you can see the interface

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

<ul>
<li style= "Background-color: #FF7F24" ><a href= "<?php echo ' http://'. $_server[' http_host '].$_SERVER[' Request_uri ']. ' Example/jsapi.php ';? > "&GT;JSAPI payment </a></li>
<li style= "Background-color: #698B22" ><a href= "<?php echo ' http://'. $_server[' http_host '].$_SERVER[' Request_uri ']. ' Example/micropay.php ';? > "> Credit card payment </a></li>
<li style= "Background-color: #8B6914" ><a href= "<?php echo ' http://'. $_server[' http_host '].$_SERVER[' Request_uri ']. ' Example/native.php ';? > "> Sweep code Payment </a></li>
<li style= "Background-color: #CDCD00" ><a href= "<?php echo ' http://'. $_server[' http_host '].$_SERVER[' Request_uri ']. ' Example/orderquery.php ';? > "> Order Search </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 Inquiry </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 write directly to death for your own access links.

4. JSAPI Payment

Necessary code resolution:

$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 $Log directly::D ebug (' Test '); To debug

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

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

Public Function Getopenid ()
 {//
 via code to obtain OpenID
 if (!isset ($_get[' code ')) {
  //Trigger micro-letter return code code
  $ BaseURL = UrlEncode (' http://'. $_server[' Http_host '].$_server['s ' php_self '].$_server[' query_string ']);
  $url = $this->__createoauthurlforcode ($BASEURL);
  Header ("Location: $url");
  Exit ();
 } else {
  //Get code code to get OpenID
   $code = $_get[' code '];
  $openid = $this->getopenidfrommp ($code);
  return $openid;
 }
 

$BASEURL is actually in order to jump back to this page. You can continue tracking functions __createoauthurlforcode () in fact, through the micro-letter Auth2.0 to obtain OpenID
Reference Link: http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

This will require you to set up the Web licensing interface for the micro-letter as well.

Access to Openid can invoke the unified next single interface of the micro-credit payment. Back to 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);
$order = Wxpayapi::unifiedorder ($input);
Echo ' <font color= "#f00" ><b> Unified Single payment information </b></font><br/> ';
Printf_info ($order);
$jsApiParameters = $tools->getjsapiparameters ($order);

Here's the code:

$input->setattach ("test");

If the value is changed to $input->setattach ("test is Attach"), there will be a bug behind it, 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.

The function Unifiedorder ($input) can go to the WxPay.Api.php file tracking, in fact, is to call the unified next single interface.

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

The asynchronous notification URL is not set, then use the URL in the configuration file
    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 there is no setting at all in the configuration file.

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

function Getjsapiparameters () is to obtain JSAPI payment parameters to the variable $jsApiParameters convenient in the following JS call

jsapi.php in JS 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 ();
 }
 

The call to the immediate payment button is the Callpay () function, and he will invoke the 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 out payment success prompt box

This is actually the JS function Jsapicall inside the Alter pop-up dialog box

Where res.err_msg for Get_brand_wcpay_request:ok indicates that the front end of the payment success, we can according to this will pay jump to the success page.

But this is not believable. Verify that the payment is successful or that the business logic should be handled through notify.php.

5. Notice of payment Results notify.php

In fact, the most important code on this page is two lines.

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

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

Final public Function Handle ($needSign = True)
 {
 $msg = "OK";
 When False is returned, the Notifycallback callback failure is invoked in notify to obtain a signature checksum failure, at which point the direct reply fails
 $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 succeeds in callback to the Notifycallback method, after the process completes
  $this->setreturn_code ("SUCCESS");
  $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 notification data
 $xml = $ globals[' Http_raw_post_data '];
 Verify that the signature
 try {
  $result = Wxpayresults::init ($xml);
 } catch (Wxpayexception $e) {
  $msg = $e-> If success is returned ErrorMessage ();
  return false;
 }
 
 Return Call_user_func ($callback, $result);
 }

Through $GLOBALS [' Http_raw_post_data ']; Get the gay data then Init function to validate the signature, and so on. Verification successfully run code
Return Call_user_func ($callback, $result);

That is, a callback function is invoked, the Notifycallback () function passes the argument $result the Notifyprocess () function that we override is invoked in the Notifycallback function (this function is overridden in notify.php)

Notifyprocess () and no problem will set the XML information to return success

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

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

function replynotify need to modify one code:

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

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

To

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

Can.
So the whole process is over. The above mentioned the pass order parameter

$input->setattach ("test");

If I set the value to test this is attach (in fact, there is a bug as long as there are spaces)

Order information as shown in figure

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

However, the discovery always receives a notify notification, meaning that it does not return the correct result notification to the micro-trust server.
Notification data sent from the print server

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

The signature that is received by the print and the signature found by the program is different, that is, the received result is abnormal.

So if we want to use the value of attach, we can't have spaces or simply not use this parameter

(Wait for the micro-letter to fix the bug, it could be somewhere on my side.) - -#)

So the JSAPI payment of the micro-letter payment is analyzed and finished roughly.

The above is the micro-letter payment PHP SDK Payment code detailed, follow-up continue to supplement the relevant information, thank you for your support of 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.