Micro-credit payment sweep code payment PHP version _php instance

Source: Internet
Author: User
Tags cdata openid sha1 unique id

The example of this article for everyone to share the PHP micro-scan code to pay the source code for your reference, the specific contents are as follows

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

createurl.php: Create a micro-letter two-dimensional code Payment link

<?php/** * @author Chantrans * The role of this page is to generate two-dimensional 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; /** * Two-dimensional code Sweep Code 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 has the right to pay the public number can be obtained after successful, incoming way: by the merchant directly. Timestamp is the field name: Timestamp; field Source: The number of seconds a merchant generates from January 1, 1970 to 00:00:00, the current time, and is passed in by the merchant after it is generated. Value range: 32 characters The following noncestr are field names: random string; field Source: Merchant generated random string; value range: 32 characters below. Generated by the merchant and then passed in. Value range: 32 characters The following ProductID is the name of the field: the Product unique ID; field Source: The merchant needs to define and maintain its own product ID, which is equivalent to an order, which is used by the background of the post merchant to obtain the transaction information. Generated by the merchant and then passed in. Value range: 32 characters The following sign is a field name: Signature; field Source: The results obtained by using the SHA1 algorithm are sorted by the preceding other fields and Appkey in the dictionary order. Generated by the merchant and then passed in.
 Fields that participate in sign signatures 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, can verify merchant unique identity,
 Paysignkey corresponds to the Appkey value in the payment scenario.
 $nonce _str =getnoncestr ();
 $time _stamp = Strtotime ("Now"); A key=value dictionary order $keyvaluestring = "appid=" for all parameters that need to be passed in, plus appkey. $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: When a user scans a two-dimensional code link, the micro-letter posts the Product ID, OpenID, and other information in the link to the script. The script is responsible for returning the merchandise information that corresponds to the commodity ID.

<?php include ' arraytoxml.php ';
Header (' Content-type:text/xml ');
 /*** * The script will call this callback URL to get the product information when the public receives the native (native) payment request. * */** First step: Receive the message from the micro-mail server (1) OpenID, click on the link ready to purchase the user OpenID (2) AppId, the public account of the AppId (3) Issubscribe, mark whether users subscribe to the public account, 1 for attention, 0 For not paying attention (4) ProductId, third party commodity ID number (5) TimeStamp, timestamp (6) Noncestr, random string (7) appsignature, parameter encryption signature, is based on 2.7 The signature (8) generated by the signature method described in the payment signature (paysign) generation is Signmethod, signed, and currently supports only "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 and merchandise 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 yourself. $strReq = $strTime.
 $randNum; * * Merchant's order number/$mch _vno = $curDateTime.
 $strReq;
/********************//*todo Save order information to the 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 _trade_no merchant System Internal Order number * @return $package/function Getpackage ($body, $total _fee, $out _trade_no) {$i
 p=$_server["REMOTE_ADDR"]; if ($ip = = ":: 1" | |
 Empty ($ip)) {$ip = "127.0.0.1";
 } $banktype = "WX"; $fee _type = "1";//cost type, here 1 is the default RMB $input _charset = "GBK";//Character set, which will be used uniformly GBK $notify _url = "http://xxxxxx.com/Wxpay/ Notify.html "//After successful payment will notify the address $out _trade_no =createtradeid ();//order number, the merchant needs to ensure that the field for the uniqueness of the merchant $partner =" XXXXXXXX "; Merchant number $spbill _create_ip = $IP;//order generated machine IP $partnerKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"; This value is not the same as the other values: the signature needs it, And the final composition of the transmission string cannot contain it.
 This key needs to be saved by the merchant. First step: Sign the original string, and note that you don't want to encode any of the fields here. Here are the words that are sorted by the dictionary of the parameters following Key=valueString, key=xxxx at the end of the concatenation of the strings.
 Because the fields here are fixed, you just need to sort them in that 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, the URL transcoding for each parameter.
 $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 proceed to the final step, which consists of the following strings, sorted by Key=value In addition to sign, followed by the 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 package, convenient to use return $completeString when the whole signature is final; }//Analog JS encodeURIComponent method function encodeURIComponent ($str) {$revert = array ('%21 ' => '! ', '%2a ' => ' * ', '%27 ' =
 > "', '%28 ' => ' (', '%29 ' => ')");
Return Strtr (Rawurlencode ($STR), $revert); /** Step Fourth: To return package data, the callback URL must return an XML-formatted return data, in the form of: <xml> <appid><! [cdata[wwwwb4f85f3a797777]]></appid> <package><!
[cdata[a=1&url=http%3a%2f%2fwww.qq.com]]></package> <TimeStamp> 1369745073</timestamp> <noncestr><! [cdata[iuytxa0ch6pytavisb28]]></noncestr> <RetCode>0</RetCode> <reterrmsg><! [Cdata[ok]]> </reterrmsg> <appsignature><! [cdata[53cca9d47b883bd4a5c85a9300df3da0cb48565c]]> </AppSignature> <signmethod><! [cdata[sha1]]></signmethod > </xml> For some third parties feel that the goods have expired or other errors, can be reflected in RetCode and Reterrmsg, RetCode 0
 To be correct, you can define other errors, and when you define other errors, you can fill in the reterrmsg with UTF8-encoded error messages, such as "the product is off the shelf" and the client prompts you directly. **/$data =array ("AppId" => $AppId, "Package" =>getpackage ("Test goods", "201311291504302501231"), "TimeStamp" = >strtotime (), "Noncestr" => $NonceStr, "RetCode" =>0,//retcode 0 indicates the correct, you can define other errors, and when you define other errors, you can fill in the reterrmsg
 A coded error message, such as "the product is off the shelf", will be prompted directly by the client.
"Reterrmsg" => "correct return", "Appsignature" => $AppSignature, "Signmethod" => "SHA1");
 Returns the generated XML data echo arraytoxml::arrtoxml ($DATA);

notifyurl.php: When a user pays a product, the micro-server delivers important information such as product information, payment results, and user OpenID to the link as get and post. The script receives this information and does the shipping processing according to the payment information, and finally returns to the success server to inform them that we have processed this notification. Otherwise, the micro-trust server will periodically reboot the notification.

? /** background notification through the request of the Notify_url, using the post mechanism. Returns the parameter in the notification to be consistent, the URL contains the following content: see "micro-credit public number payment" Public number payment interface document v2.2.pdf the Notification Interface section also includes XML data in PostData. The data are as follows: <xml> <openid><! [cdata[111222]]></openid> <appid><! [cdata[wwwwb4f85f3a797777]]></appid> <IsSubscribe>1</IsSubscribe> <TimeStamp> 1369743511</timestamp> <noncestr><! [cdata[jalldrthafd5tgs5]]></noncestr> <appsignature><! [cdata[bafe07f060f22dcda0bfdb4b5ff756f973aecffa]]> </AppSignature> <signmethod><! [cdata[sha1]]></signmethod > </xml> Merchants need to save these parameters and judge the payment status of the user *//Get the Micro-letter 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, and the parameter list is detailed in the document **************************/if ($trade _state==0) {echo "Success";} else{echo "false";

 }

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

<?php

class Arraytoxml
{
 /**
 * @param array $arr
 * @return string XML
 /public static function Arrtoxml ($arr, $dom =0, $item =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 entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.