WeChat payment Scan Code payment PHP version _php instance

Source: Internet
Author: User
The example of this article for everyone to share the PHP code to pay the source, for your reference, the specific content as follows

The code contains four files createurl.php, arraytoxml.php, returngoodsurl.php, notifyurl.php .

createurl.php: Create a two-dimensional code payment link

<?php/** * @author Chantrans * This page is to generate a product QR Code link *///test echo createurl ("12314124");/** * generates a random string */function getnoncestr ( {$chars = ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '; $noceStr = ""; for ($i = 0; $i < $i + +) {$noceStr. = $chars [Mt_rand (0, strlen ($chars)-1)];} $oldNonceStr = $noceStr; return $NOCESTR;} /** * QR Code Scan link Construction Method: * weixin://wxpay/bizpayurl?sign=xxxxx&appid=xxxxxx&productid=xxxxxx&timestamp= XXXXXX&AMP;NONCESTR=XXXXXX * AppID is the name of the field: Public id; field Source: Merchant Registration with the payment permission of the public number can be obtained after success; incoming: directly by the merchant. Timestamp is the field name: Timestamp; field Source: The number of seconds that the merchant generated from January 1, 1970 00:00:00 to the present, that is, the current time; generated by the merchant and passed in. Value range: 32 characters The following noncestr is the field name: random string; field Source: A random string generated by a merchant; Range: 32 characters or less in length. Generated by the merchant and then passed in. Value range: 32 characters The following ProductID is the field name: Commodity unique ID; field Source: The merchant needs to define and maintain its own product ID, which is equivalent to an order, and the backend obtains the transaction's required information through the post merchant background with the ID. Generated by the merchant and then passed in. Value range: 32 characters The following sign is the field name: Signature; field Source: The results obtained by using the SHA1 algorithm after ordering the previous fields and Appkey in dictionary order. Generated by the merchant and then passed in. The fields that participate in sign signing include: AppID, timestamp, Noncestr, ProductID, and Appkey. */function CreateURL ($productid) {$app _id = "wxbce29784bdd01454 "; Public number AppID $app _key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";//Public number payment request for encryption key key, The merchant's unique identity can be verified, and the Paysignkey corresponds to the Appkey value in the payment scenario. $nonce _str =getnoncestr (); $time _stamp = Strtotime ("Now"); For all parameters that need to be passed in, add Appkey as a key=value dictionary order $keyvaluestring = "appid=". $app _id. " &appkey= ". $app _key." &noncestr= ". $nonce _str." &productid= ". $productid." &timestamp= ". $time _stamp; $sign = SHA1 ($keyvaluestring). ""; $url = "weixin://wxpay/bizpayurl?sign=". $sign. " &appid= ". $app _id." &productid= ". $productid." &timestamp= ". $time _stamp." &noncestr= ". $nonce _str."; return $url;}

returngoodsurl.php: After the user scans the QR-code link, the product ID in the link, OpenID and other information is post to the script, which is responsible for returning the product information corresponding to the product ID.

<?phpinclude ' arraytoxml.php '; header (' Content-type:text/xml ');/*** * This script is for the public when the platform receives a native (native) payment request, This callback URL is called to get the product information. *//** First step: Receive server Post information (1) OpenID, click on the link ready to purchase the user OpenID (2) AppId, public account of AppId (3) Issubscribe, mark the user whether to subscribe to the public account, 1 for concern, 0 For not paying attention (4) ProductId, the third party's product ID number (5) TimeStamp, timestamp (6) Noncestr, random string (7) appsignature, parameter of the cryptographic signature, is based on 2.7 The signature (8) generated by the signature method described in the payment signature (Paysign) generation methods is Signmethod, signed, and currently only supports "SHA1". The field does not participate in the signature **/$postdata = file_get_contents ("Php://input"); $postObj = simplexml_load_string ($postdata, ' SimpleXMLElement ', libxml_nocdata); $openId = $postObj->openid; $AppId = $postObj->appid; $IsSubscribe = $POSTOBJ- >IsSubscribe; $ProductId = $postObj->productid; $TimeStamp = $postObj->timestamp; $NonceStr = $postObj noncestr; $AppSignature = $postObj->appsignature; $SignMethod = $postObj->signmethod;/** * Second step, generate order number, and product information, User OpenID and other order information stored in the database * */function Createtradeid () {$curDateTime = date ("Ymdhis");//date_default_timezone_set (PRC); $ Strdate = Date ("Ymd"); $strTime = Date ("his"); 4-bit random number $randNum = rand (1000, 9999); 10-bit serial number, you can adjust it yourself. $strReq = $strTime. $randNum; /* Merchant's order number */$mch _vno = $curDateTime. $strReq; /********************//*todo Save order information to database *//********************/return $mch _vno;} /** * Step three: Generate Product Details Pakage * @param string $body Product Description * @param string $total _fee order total amount in minutes. * @param string $out The order number within the _trade_no merchant system * @return $package */function getpackage ($body, $total _fee, $out _trade_no) {$ip =$ _server["REMOTE_ADDR"]; if ($ip = = ":: 1" | | Empty ($ip)) {$ip = "127.0.0.1";} $banktype = "WX"; $fee _type = "1";//fee type, here 1 is the default RMB $input _charset = "GBK";//Character Set, this will be used uniformly GBK $notify _url = "http://xxxxxx.com/Wxpay/ Notify.html ";//The address will be notified after successful payment $out _trade_no =createtradeid ();//order number, merchants need to ensure that the field for the merchant's uniqueness $partner =" XXXXXXXX "; Merchant number $spbill _create_ip = $IP;//the Machine IP $partnerKey of the Order generation = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";//This value is not the same as the above other values: signature requires it, The final transmission string cannot contain it. This key is required to be well preserved by the merchant. First step: Sign the original string, and be careful not to encode any fields here. Here is the string that consists of the following dictionary, sorted by Key=value, in which the string is key=xxxx at the end of the concatenation. Because the fields here are fixed, you only need to sort them in this order. $signString = "Bank_tyPe= ". $banktype." &body= ". $body." &fee_type= ". $fee _type." &input_charset= ". $input _charset." &notify_url= ". $notify _url." &out_trade_no= ". $out _trade_no." &partner= ". $partner." &spbill_create_ip= ". $spbill _create_ip." &total_fee= ". $total _fee." &key= ". $partnerKey; $MD 5SignValue = ("". Strtoupper (MD5 ($signString))); echo $MD 5SignValue; Then the second step is to transcode each parameter URL. $banktype = encodeURIComponent ($banktype); $body =encodeuricomponent ($body); $fee _type=encodeuricomponent ($fee _type); $input _charset = encodeuricomponent ($input _charset); $notify _url = encodeuricomponent ($notify _url); $out _trade_no = encodeuricomponent ($out _trade_no); $partner = encodeURIComponent ($partner); $spbill _create_ip = encodeuricomponent ($spbill _create_ip);  $total _fee = encodeuricomponent ($total _fee); Then take the final step, here according to Key=value in addition to sign dictionary ordered after the composition of the following string, and then threaded sign=value $completeString = "bank_type=". $banktype. " &body= ". $body." &fee_type= ". $fee _type." &input_charset= ". $input _charset." &notify_uRl= ". $notify _url." &out_trade_no= ". $out _trade_no." &partner= ". $partner." &spbill_create_ip= ". $spbill _create_ip." &total_fee= ". $total _fee; $completeString = $completeString. " &sign= ". $MD 5SignValue; $oldPackageString = $completeString; Remember that the package is easy to use return $completeString when the overall signature is final;} Analog JS in the encodeURIComponent method function encodeURIComponent ($str) {$revert = array ('%21 ' = '! ', '%2a ' = ' * ', '%27 ' = > "'", '%28 ' = ' (', '%29 ' = ') '); Return Strtr (Rawurlencode ($STR), $revert);} /** Fourth Step: In order to return the package data, the callback URL must return an XML-formatted return data, such as:
 
   wwwwb4f85f3a797777 
    
    1369745073 0 
    iuytxA0cH6PyTAVISB28 
 
    
    a=1&url=http%3A%2F%2Fwww.qq.com 
 
    
    ok 
     53cca9d47b883bd4a5c85a9300df3da0cb48565c 
     sha1 
      
   
  
     
  
  
 
   
 
 
 
 
 

  
 For some third parties feel that the product has expired or other errors can be reflected in RetCode and Reterrmsg, RetCode 0 to indicate that the correct, you can define other errors, when you define other errors, you can fill in the Reterrmsg UTF8 Coded error message, such as "the product has been off the shelf", the client will be directly prompted. **/$data =array ("AppId" = $AppId, "package" =>getpackage ("Test goods", "201311291504302501231"), "TimeStamp" = >strtotime (), "noncestr" = $NonceStr, "RetCode" =>0,//retcode 0 indicates correct, other errors can be defined, and when other errors are defined, you can fill reterrmsg Coded error message, such as "the product has been off the shelf", the client will be directly prompted. "Reterrmsg" = "correct return", "Appsignature" and "signmethod" = "SHA1");//returns the generated XML data echo Arraytoxml:: Arrtoxml ($data);

notifyurl.php: When a user pays a product, the server will store the product information, payment results, Important information, such as the user's OpenID, is passed to the link in the form of Get and post, which receives this information and makes shipping processing based on the payment information, and finally returns to the server success, informing them that we have processed this notification. Otherwise, the server will periodically re-initiate the notification.

<?/** background notification through the request of Notify_url, using the post mechanism. The parameters in the return notification are consistent, and the URL contains the following: see "Public number Payment" Public number payment interface document V2.2.pdf notifies the interface section at the same time, the XML data will also be included in PostData.
  The data is as follows: 
   
    111222 
    wwwwb4f85f3a797777 
   
     1 
    
   
     1369743511 
    
    jALldRTHAFd5Tgs5 
    
    
    sha1!--signmethod--> 
    /xml> merchants need to save these parameters and determine the user's payment status *///Get notification interface postdata Information $postdata = file_get_contents ("Php://input"); $POSTOBJ = simplexml_load_string ($postdata, ' simplexmlelement ', libxml_nocdata); $trade _state =$_get ["Trade_state"] ;//Payment Status $out_trade_no = $_get ["Out_trade_no"];//order number/***************** Todo There are many other parameters that need to be saved, the parameter list is detailed in the documentation ***************** /if ($trade _state==0) {echo "Success";} else{echo "false";} 
  

arraytoxml.php: The purpose of this script is to convert an array into XML.

<?phpclass arraytoxml{/** * @param array $arr * @return string XML */public static function Arrtoxml ($arr, $dom =0, $ite m=0) {if (! $dom) {  $dom = new DOMDocument ("1.0");} if (! $item) {  $item = $dom->createelement ("xml");   $dom->appendchild ($item); } foreach ($arr as $key = + $val) {  $itemx = $dom->createelement (is_string ($key)? $key: "Item");  $item->appendchild ($ITEMX);  if (!is_array ($val)) {   $text = $dom->createtextnode ($val);   $itemx->appendchild ($text);     } else {   self::arrtoxml ($val, $dom, $itemx);}  } return $dom->savexml ();}}

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support the script home.

  • 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.