WeChat payment QR payment php _ php instance

Source: Internet
Author: User
Tags openid
This article mainly introduces the payment and php code scanning payment source code, which has some reference value, interested friends can refer to the examples in this article to share with you the php scan code payment source code for your reference. the specific content is as follows:

The code contains four files.CreateUrl. php, ArrayToXML. php, returnGoodsUrl. php, and yyurl. php.

CreateUrl. php:Create QR code payment link

<? Php/*** @ author chantrans * the function of this page is to generate the product QR code link * // Test echo createUrl ("12314124 "); /*** generate a random string */function getNonceStr () {$ chars = 'callback'; $ noceStr = ""; for ($ I = 0; $ I <32; $ 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 & noncestr = XXXXXX * appid is the field name: public id; field Source: after a merchant registers a public account with the payment permission, the account can be obtained. import method: the account is directly transferred by the merchant. Timestamp is the field name: timestamp; field Source: The number of seconds generated by the merchant since 00:00:00, January 1, January 1, 1970, that is, the current time. Value range: noncestr with less than 32 characters is the field name: random string; field Source: random string generated by the merchant; value range: Length: 32 characters or less. Generated by the merchant and passed in. Value range: productid with less than 32 characters is the field name: Unique Product id; field Source: The Merchant needs to define and maintain its own product id, which is equivalent to an order, the background uses this id to obtain the required transaction information through the Post merchant background. Generated by the merchant and passed in. Value range: 32 characters or less. sign is the field name: Signature. field Source: The SHA1 algorithm is used to obtain the result after the other fields and appKey are sorted alphabetically. Generated by the merchant and passed in. The fields involved in sign signing include appid, timestamp, noncestr, productid, and appkey. */Function createUrl ($ productid) {$ app_id = "wxbce29784bdd01454"; // public account appid $ app_key = "expiration "; // the Key used for encryption in the public account payment request, which can verify the unique identity of the merchant. the PaySignKey corresponds to the appKey value in the payment scenario. $ Nonce_str = getNonceStr (); $ time_stamp = strtotime ("now "); // add the appkey to all parameters to be passed in and sort the key = value lexicographically $ 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 scanning the QR code link, the user will post the product ID, openId, and other information in the link to this script, which is responsible for returning the product information corresponding to the product ID.

<? Phpinclude 'arraytoxml. php '; header ('content-Type: text/XML');/*** when the public receives a Native (Native) payment request, the callback URL is called to obtain the product information. * // ** Step 1: receive post information from the server (1) OpenId, click the link to the user openid (2) AppId and appid of the public account (3) isSubscribe, which indicates whether the user subscribes to the public account. 1 is followed, 0 is not followed (4) ProductId, third-party item ID number (5) TimeStamp, TimeStamp (6) NonceStr, random string (7) AppSignature, the encrypted signature of the parameter, is the signature generated according to the signature method described in the 2.7 payment signature generation method (8) SignMethod, signature method, currently, only "SHA1" is supported ". This 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 ;/ * ** Step 2: generate the order number and store the order information such as the user's openID in the database with the product information. **/function createTradeId () {$ curDateTime = date ("YmdHis"); // date_default_timezone_set (PRC); $ strDate = date ("Ymd"); $ strTime = date ("His "); // 4-digit random number $ randNum = rand (1000,999 9); // 10-digit serial number, which can be adjusted by yourself. $ StrReq = $ strTime. $ randNum;/* Merchant's order number */$ mch_vno = $ curDateTime. $ strReq; /******************** // todo saves order information to the database *//****** * *************/return $ mch_vno ;} /*** Step 3: generate the product details pakage * @ param string $ body product description * @ param string $ total_fee total order amount, in minutes. * @ Param string $ out_trade_no internal order number of the 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. here, we will use GBK $ policy_url =" http://xxxxxx.com/Wxpay/notify.html "; // After the payment is successful, the address $ out_trade_no = createTradeId () will be notified; // the order number. the merchant must ensure that this field is unique to the merchant. $ partner =" XXXXXXXX "; // merchant ID $ spbill_create_ip = $ ip; // The IP address of the machine generated by the order $ partnerKey = "xxxxxxxxxxxxxxxxxxxxxxxxx"; // This value is different from other values above: it is required for signature, the final transmission string cannot contain it. This key must be well preserved by merchants. // First step: sign the original string. do not encode any fields here. Sort the parameters alphabetically by key = value to form the following string, and splice the string with key = XXXX. 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. "& policy_url = ". $ policy_url. "& out_trade_no = ". $ out_trade_no. "& partner = ". $ partner. "& spbill_create_ip = ". $ spbill_create_ip. "& total_detail = ". $ total_detail. "& key = ". $ partnerKey; $ md5SignValue = ("". strtoupper (md5 ($ signString); // echo $ md5SignValue; // perform url transcoding for each parameter in step 2. $ Banktype = encodeURIComponent ($ banktype); $ body = encodeURIComponent ($ body); $ fee_type = bytes ($ fee_type); $ input_charset = encodeURIComponent ($ input_charset ); $ yy_url = encodeURIComponent ($ notify_url); $ out_trade_no = encodeURIComponent ($ out_trade_no); $ partner = member ($ partner); $ member = encodeURIComponent ($ response ); $ total_component = encodeURIComponent ($ Total_fee); // then perform the last step. here, sort the key = value in lexicographic order in addition to sign to form the following strings, finally, concatenate sign = value $ completeString = "bank_type = ". $ banktype. "& body = ". $ body. "& fee_type = ". $ fee_type. "& input_charset = ". $ input_charset. "& policy_url = ". $ policy_url. "& out_trade_no = ". $ out_trade_no. "& partner = ". $ partner. "& spbill_create_ip = ". $ spbill_create_ip. "& total_detail = ". $ total_fee; $ completeString = $ completeString. "& sign = ". $ md5SignValue; $ oldPacka GeString = $ completeString; // Remember the package so that you can use return $ completeString when signing the package.} // simulate the encodeURIComponent method function encodeURIComponent ($ str) in js) {$ revert = array ('% 21' => '! ',' % 2A '=>' * ',' % 27' => "'",' % 28' => '(', '% 29' => ') '); return strtr (rawurlencode ($ str), $ revert);}/** Step 4: to return Package data, the callback URL must return data in xml format, shape:
 wwwwb4f85f3a797777
  a=1&url=http%3A%2F%2Fwww.qq.com
  
  
   
1369745073
  
  iuytxA0cH6PyTAVISB28
  
  
   
0
  
  ok
   53cca9d47b883bd4a5c85a9300df3da0cb48565c
   sha1
    
   
  
 If a third party finds that the product has expired or has other errors, it can be reflected in RetCode and RetErrMsg. if the RetCode is 0, it indicates that it is correct and other errors can be defined. when other errors are defined, you can enter the UTF8-encoded error message in RetErrMsg. for example, if "this product is not available", the client will prompt you directly. **/$ Data = array ("AppId" => $ AppId, "Package" => getPackage ("test item", 100, "201311291504302501231 "), "TimeStamp" => strtotime (), "NonceStr" => $ NonceStr, "RetCode" => 0, // The value of RetCode 0 indicates that it is correct and other errors can be defined; when defining other errors, you can enter the UTF8 encoding error message in RetErrMsg, for example, "This product is not available", and the client will prompt it directly. "RetErrMsg" => "returned correctly", "AppSignature" => $ AppSignature, "SignMethod" => "sha1"); // return the generated xml data echo ArrayToXML :: arrtoxml ($ data );

Yyurl. php:After the user pays for the product, the server will pass important information such as the product information, payment result, and user's openId to the link in get and post mode, and the script will receive the information, deliver the goods according to the payment information, and finally return it to the server success to inform them that we have handled the notification. Otherwise, the server will periodically initiate a new notification.

<? /** Background notifications are performed by using the yy_url in the request and the post mechanism is used. The parameters in the returned notification are the same. the url contains the following content: see the notification Interface section in the documentation v2.2.pdf of the public payment interface, and the postData file also contains xml data. The data is as follows:
 
  111222
  wwwwb4f85f3a797777
  
   
1
  
  
   
1369743511
  
  jALldRTHAFd5Tgs5
  bafe07f060f22dcda0bfdb4b5ff756f973aecffa
  sha1
   
  
 The merchant needs to save these parameters and determine the user's payment status * // Obtain the 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 has many other parameters to save, for the parameter list, see the *** ************************/if ($ trade_state = 0) {echo "success" ;}else {echo "false ";}

ArrayToXML. php:This script converts an array to xml.

<?phpclass 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 all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own 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.