How to implement micro-credit payment in PHP

Source: Internet
Author: User
Tags openid php class
This time to everyone to bring PHP how to achieve payment, PHP to pay attention to what matters, the following is the actual case, together to see.

Recently contacted a project, involving payment, engaged in the development so long since, have not made payment, before also had to make the public number of red envelopes, thank the predecessors of the exploration, I read their blog, let me less go a lot of detours.

Pre-Preparation:

1. Certification service number, and opened the payment

2. Payment SDK, download address: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1

3. Login Payment Platform Https://pay.weixin.qq.com/index.php/account/api_cert download Payment Certificate

Method steps:

1.demo file Processing

(1) The official demo download, the file name is Wxpayapi_php_v3, the file renamed to Wxpay, in order to write a directory behind the convenience;

(2) Open the WxPay.Api.php file under the Lib folder, there is a Curl network request configuration code in line 537:

curl_setopt ($ch, curlopt_ssl_verifypeer,true); curl_setopt ($ch, curlopt_ssl_verifyhost,2);//Strict calibration

Replace with:

curl_setopt ($ch, Curlopt_ssl_verifypeer,false); curl_setopt ($ch, curlopt_ssl_verifyhost,2);//Strict calibration

To prohibit CURL from validating peer certificates (peer's certificate).

(3) Open the Lib folder under the WxPay.Config.php file, the 25th line starts, according to their own account to complete the basic information settings;

Const APPID = ' public account APPID '; Const MCHID = ' Merchant number '; Const KEY = ' Merchant Payment key '; Const APPSECRET = ' public account Secert ';

(4) Open the Lib folder under the WxPay.Notify.php file, the 79th line of code:

if ($needSign = = True &&  $this->getreturn_code ($return _code) = = "SUCCESS") {  $this->setsign ();}

Change to:

if ($needSign = = True &&  $this->getreturn_code () = = "SUCCESS") {  $this->setsign ();}

(5) Open the CERT Certificate directory and replace the two certificates inside with your own payment certificate.

2. Public Number background settings

(1) Configure the Web page authorization domain name, my domain name is (xy.chuyin.ren);

(1) Configure the Payment authorization directory, the domain name is (xy.chuyin.ren), I put the demo into the directory of this domain name weixinopen/folder, the demo jsapi.php file is located in the example/directory, So the payment authorization directory is: xy.chuyin.ren/weixinopen/wxpay/example/

3. Payment Process

Open the example directory under the jsapi.php file, payment initiation and processing, are done here.

(1) Get user OpenID

AppID and Appsecert have been configured before, so there is no need to deal with it.

①, get user OpenID $tools = new Jsapipay (); $openId = $tools->getopenid ();

Here first Initializes a jsapipay () class to get an object, the file corresponding to the example/directory under the WxPay.JsApiPay.php, calls the Getopenid () method, will automatically get its own OpenID.

(2) Unification of orders

②, unified order $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->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 order information </b></font><br/> '; Printf_info ($order); $jsApiParameters = $tools->getjsapiparameters ($order);

The Unifiedorder () method that corresponds to the 24th line of WxPay.Api.php, configures the order information and the payment callback function, where several parameters need to be modified:

A. Product Name:

$input->setbody ("test");

B. Order Number

$input->setout_trade_no (Wxpayconfig::mchid.date ("Ymdhis"));

C. Amount paid

$input->settotal_fee ("1");

D. Payment Verification Link

Set to the location of your notify.php file, so I set it here to: http://xy.chuyin.ren/weixinopen/wxpay/example/notify.php

You can also write other addresses, of course, under the payment authorization domain name, after the successful payment will be automatically callback to the method specified by the link inside, you can judge and database operation.

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

E. Additional parameters

$input->setattach ("test");

Additional parameters, can be filled, fill in the words, inside the string is best not to appear space.

At this point, click to pay should be able to pay successfully.

(3) Initiating payment

<script type= "Text/javascript" >//Call JS API to pay 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 ();  }} </script>

Click the Pay Now button to invoke the Callpay () function, which will call the Jsapicall () function to open the payment program.

The Jsapicall () function listens for each step of the action:

res.err_msg 为get_brand_wcpay_request:cancel Indicates the cancellation of the front end of the payment, es.err_msg for Get_brand_wcpay_request:ok to indicate that the front-end judgment of the payment success, we can be paid according to this will jump to the success page.

(4) Support for successful callbacks

The payment results can be monitored through the front-end jsapicall () function, but this is not credible. Confirm whether the payment succeeds or the business logic should be processed through notify.php. Before the Payment verification link Setnotify_url () is configured, the server automatically requests your notify.php file according to the link, and the main code of this file is two lines:

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

This traces the handle () function to the WxPay.Notify.php class file:

/**  *  * Callback Entry  * @param bool $needSign need signature output *  /FINAL public function Handle ($needSign = True) {  $msg = "OK";  When False is returned, indicates that the call to Notifycallback callback in notify failed to get the signature check failure, at which point the direct reply failed  $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);

Then come to the No. 411 line of the WxPay.Api.php file, the Notify () function:

/**  *  * General notification of payment results  * @param function $callback  * Direct callback function using method: Notify (you_function);  * Callback class member function method: Notify (Array ($this, you_function));  * $callback prototype: function function_name ($data) {}  */public static function Notify ($callback, & $msg) {  // Gets the data of the notification  $xml = $GLOBALS [' Http_raw_post_data '];  File_put_contents (' Log.txt ', $xml, file_append);  If the return succeeds, verify that the signature  try {   $result = Wxpayresults::init ($xml),  } catch (Wxpayexception $e) {   $msg = $e- >errormessage ();   return false;  }    Return Call_user_func ($callback, $result); }

The $xml= in this $GLOBALS [' Http_raw_post_data '] is the result of a successful payment after the user returns to you, he is a string in XML format.

We can record the XML data returned here, and then open it to see if $out_trade_no is the order number I set myself before paying, $attach is the additional parameter set.

Get this order number, and then I write directly below the payment after the success of the logic, such as changing the data in the database and so on.

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

This is the integration of the official SDK implementation, if you do not use the SDK, you can use the simpler method, see: PHP Implementation payment (JSAPI payment) and refunds (no integration payment SDK required)

Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!

Recommended reading:

Use Angularjs to get passwords on the front-end interface

Promise simplification callbacks for small programs

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.