Php implements WeChat QR payment and php implements payment

Source: Internet
Author: User
Tags openid

Php implements code scanning payment and php implements payment

The Code contains four files: createUrl. php, ArrayToXML. php, returnGoodsUrl. php, and yyurl. php.

CreateUrl. php: Create a 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 × tamp = 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. "× tamp = ". $ time_stamp; $ sign = sha1 ($ keyvaluestring ). ""; $ url = "weixin: // wxpay/bizpayurl? Sign = ". $ sign. "& appid = ". $ app_id. "& productid = ". $ productid. "× tamp = ". $ time_stamp. "& noncestr = ". $ nonce_str. ""; return $ url ;}

ReturnGoodsUrl. php: After you scan the QR code link, you can post the product ID, openId, and other information in the link to this script. This script returns 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 save 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 $ yy_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 $ Partner = "XXXXXXXX"; // merchant ID $ spbill_create_ip = $ ip; // IP address of the machine generated by the order $ partnerKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXX "; // This value is different from other values: the signature requires it, and 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. "verify ify _ 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. "verify ify _ 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; $ oldPackageS Tring = $ completeString; // remember the package, so that you can use return $ completeString;} // 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, format: <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> it can be reflected in RetCode and RetErrMsg when a third party finds that the product has expired or has other errors, if the RetCode is 0, it 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 ", the client will prompt you. **/$ 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 a user pays for a 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: <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 determine the user's payment status * // get 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.

<?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 all the content of this instance. I hope you will like it.

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.