App WeChat payment PHP background interface detailed

Source: Internet
Author: User
Tags md5 encryption
This article will introduce you to the PHP (7.0) Background payment and callback interface for app payment (2016.10.11), the framework is Thinkphp5.0: hope to help everyone.

    • Various parameters of the account

    • Order Information

    • Request prepay_id

    • * Back to App data processing

    • Callback

    • Modify Order Status

Various parameters of the account

The various parameters of the account is like the application payment will be sent to your account email address, there will be the corresponding payment allocation of the merchant number (Mchid), AppID and Appsecret is to apply for the app to pay permission to return, There are key needs of their own in the user's business background inside the set, this is very important! To avoid the leak!

Order Information

    • * * The client will be in the shopping cart inside the product data to the backstage, also including the user's information, to get the data first need to verify the data, where the verification is generally in the early stages of the project and the client set the transmission rules, such as transmission, parameter name, verify the parameters of the way, the focus here is to verify, Generally, the signature authentication method will be used:

    • Signature Step One: Sorting parameters by dictionary order;

    • Here are examples of code (formatting parameters formatted as URL parameters):

/**     * format parameter formatted as URL parameter     */public    function Tourlparams ()    {        $buff = "";        foreach ($this->values as $k = + $v)        {            if ($k! = "sign" && $v! = "" "&&!is_array ($v)) {                $bu ff. = $k. "=" . $v. "&";            }        }        $buff = Trim ($buff, "&");        return $buff;    }
    • Signature Step Two: Add key after string (this key will be negotiated with the front-end staff);


    • Signature Step three: MD5 encryption;


    • Signature Step four: all characters to uppercase


These are best encapsulated in the early stages of the project, as long as the call is good, for example:
(only required later, $param = $this->request (' parameter name ')), and the order information is pre-stored.

Request prepay_id

Here I directly on the code, (here is given the interface document download address:), although there are many on the Internet to write the request interface, but since it has been packaged, use on the line:

$input = new \app\wxpay\wxpayunifiedorder ()///$input->setbody ($data [' gname '] [' g_name '] referenced here;// A brief description of the goods or payment list $input->setattach ($data [' gname '] [' g_name ']);//placing additional data $input->setout_trade_no ($order _sn); Merchant Order number $input->settotal_fee (Intval ($data [' Data '] [' Order_price ']*100)]; $input->settime_start (Date ("Ymdhis")),//Order generation time $input->settime_expire (date ("Ymdhis", Time () + 600));//Order Expiration $input->setgoods_tag ($data [' gname '] [' g_name ']); Commodity Mark  $input->setnotify_url ("http://www.weixin.qq.com/wxpay/notify.php");//callback address after successful payment, $input Settrade_type ("APP"); $order = \app\wxpay\wxpayapi::unifiedorder ($input); return $order [' prepay_id '];

Here is the official unified next single Interface description address:
Https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1

Return client Information

$info = Array ();//The information of the account is usually placed in the configuration file, where there are also many $info[' appid ' = config (' app_appid '); $info [' partnerid '] = Config (' App_ Mchid '), $info [' package '] = Config (' app_package '), $info [' noncestr '] = $this->random_number ();//Generate random numbers, with a build instance below, Unified next single interface requires $info[' timestamp ' = time (), $info [' prepayid '] = $prepay _id; $info [' sign '] = self::_makesign ($info);// Generate signature return $info;

$info is the information the client needs.
Generate random Number instances

Generate random number Public function Random_number ($len =21, $format = ' all ') {$is _abc = $is _numer = 0;        $password = $tmp = "; Switch ($format) {case ' all ': $chars = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '            ;            Break            Case ' CHAR ': $chars = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz ';            Break            Case ' number ': $chars = ' 0123456789 ';            Break            Default: $chars = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ';        Break        }//Www.jb51.net Mt_srand ((double) Microtime () *1000000*getmypid ());            while (strlen ($password) < $len) {$tmp =substr ($chars, (Mt_rand ()%strlen ($chars)), 1); if ($is _numer <> 1 && is_numeric ($tmp) && $tmp >0) | | $format = = ' CHAR ') {$is _nume            R = 1; } if (($is _abc <> 1 && preg_match ('/[a-za-z]/', $tMP)) | |            $format = = ' number ') {$is _abc = 1;        } $password. = $tmp; if ($is _numer <> 1 | | $is _abc <> 1 | | empty ($password)) {$password = $this->random_numb        ER ($len, $format);        } return $password; }

Callback

Notice of payment Results notify.php (here is the address of the unified order to fill in the callback address, has been encapsulated), the document download address
Http://mch.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
In fact, the main code of this page is two lines

[PHP] View plain Copy

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

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

[PHP] View plain Copy

    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:
[PHP] View plain Copy

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

Trace function notify file WxPay.Api.php

[PHP] View plain Copy

    public static function Notify ($callback, & $msg)          {              //Get notification data              $xml = $GLOBALS [' Http_raw_post_data '];              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);          }

by $GLOBALS [' Http_raw_post_data ']; Get gay data then the Init function verifies the signature and so on. Verify that the code is running successfully.
Here need to explain, PHP7 itself does not support $globals[' http_raw_post_data ', need to download a plug-in, specifically what can be self-Baidu, I want to say is can use file_get_contents (' Php://input '), Specific reasons can refer to the following blog, written in very detailed (https://my.oschina.net/jiec/blog/485359)
[PHP] View plain Copy

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

[PHP] View plain Copy

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

And finally call the function this−>replynotify (this−>replynotify (needsign); Echo Success Results

The function replynotify need to modify a code:

[PHP] View plain Copy

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

[PHP] View plain Copy

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

Switch

[PHP] View plain Copy

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

Can.
Then, according to the return information to modify the order status, mainly, where to modify, I was in the notify.php inside a new method

Modify order Status Public    function Updatestate ($data) {        if ($data) {            $order _sn = $data [' out_trade_no '];\            $data = Array ();            $data [' order_id '] = $order _id;            Modify the order status (using the Curlpost method to request to the controller inside the thinkphp directory of the method, modify the state)            $url = ' www.test.com ';            Header (' Content-type:text/html;charset=utf8 ');            $curl = Curl_init ();            curl_setopt ($curl, Curlopt_url, $url);            curl_setopt ($curl, Curlopt_returntransfer, true);            curl_setopt ($curl, Curlopt_post, true);            curl_setopt ($curl, Curlopt_postfields, $data);            $result = curl_exec ($curl);            Curl_close ($curl);            if ($result = = ' success ') {                return true;            } else{                return false;}}    }

And then in Notify.php's

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

Add the following

Accept parameters, modify state $xml = file_get_contents ("Php://input"), $data = Json_decode (Json_encode (simplexml_load_string ($xml, ' SimpleXMLElement ', Libxml_nocdata)), true); $notify->updatestate ($data);
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.