PHP implementation of APP WeChat payment examples, app examples

Source: Internet
Author: User
Tags cdata

Example of APP payment implementation in PHP, and description of app instances

I. the PHP background generates a pre-payment transaction ticket, returns the correct pre-payment transaction session ID, and then calls the payment in the APP!

Official documents: https://pay.weixin.qq.com/wiki/doc/api/app/app.php? Chapter = 9_1

According to the parameters required for document splicing, here are a few methods to directly go to the code!

The transmitted parameters must be assembled and sent in xml format, such as the parameter array!

Public function ToXml ($ data = array () {if (! Is_array ($ data) | count ($ data) <= 0) {return 'array exception';} $ xml = "<xml> "; foreach ($ data as $ key => $ val) {if (is_numeric ($ val) {$ xml. = "<". $ key. "> ". $ val. "</". $ key. ">";} else {$ xml. = "<". $ key. "> <! [CDATA [". $ val. "]> </". $ key. ">" ;}}$ xml. = "</xml>"; return $ xml ;}

2. Generate a random string. Required parameter! There are many ways to do this. You can do whatever you like!

Function rand_code () {$ str = 'hangzhou'; // 62 characters $ str = str_shuffle ($ str); $ str = substr ($ str ); return $ str ;}

3. This is an important step. This method will be used multiple times! Generate a signature

Private function getSign ($ params) {ksort ($ params); // sort the parameter array in ascending order of the parameter ASCII code ($ params as $ key => $ item) {if (! Empty ($ item) {// removes the parameter $ newArr [] = $ key. '= '. $ item; // integrate the new parameter array} $ stringA = implode ("&", $ newArr); // use the & symbol to connect the parameter $ stringSignTemp = $ stringA. "& key = ". "************************"; // concatenate the key // key is the $ stringSignTemp = MD5 ($ stringSignTemp) set in the API security of the merchant platform ); // perform MD5 encryption on the string $ sign = strtoupper ($ stringSignTemp); // convert all characters into uppercase return $ sign ;}

4. Pass the parameter to generate a pre-payment order! After receiving the returned data, the APP calls the payment interface to complete the payment! For the parameters required for the APP end, see the document: https://pay.weixin.qq.com/wiki/doc/api/app/app.php? Chapter = 9_12 & index = 2

Public function wx_pay () {$ nonce_str = $ this-> rand_code (); // call the random string generation method to obtain the random string $ data ['appid '] = 'wxdbc5dc *******'; // appid $ data ['mch _ id'] = '2017 ***** '; // merchant id $ data ['body'] = "APP payment test "; $ data ['spbill _ create_ip'] = $ _ SERVER ['HTTP _ host']; // ip address $ data ['total _ host'] = 1; // amount $ data ['out _ trade_no '] = time (). mt_rand (random, 99999); // Merchant Order number, which cannot be repeated $ data ['nonce _ str'] = $ nonce_str; // random string $ data ['random Y _ url'] = 'HTTP: // xxx.xxx.com/wx_policy'; // The callback address. After receiving the notification, the user must be a URL that can be accessed directly, the parameter $ data ['trade _ type'] = 'app'; // payment method // Save the data involved in the signature to the array. Note: the preceding parameters are appended to $ data, $ data should contain all data other than sign required in the Development documentation. $ data ['sign'] = $ this-> getSign ($ data ); // get the signature $ xml = $ this-> ToXml ($ data); // convert the array to xml // curl to the party $ url = "https://api.mch.weixin.qq.com/pay/unifiedorder "; // header ("Content-type: text/xml"); $ ch = curl_init (); curl_setopt ($ Ch, CURLOPT_URL, $ url); if (stripos ($ url, "https ://")! = FALSE) {curl_setopt ($ ch, CURLOPT_SSLVERSION, scheme); curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ ch, CURLOPT_SSL_VERIFYHOST, FALSE );} else {curl_setopt ($ ch, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt ($ ch, expires, 2); // strict validation} // set header curl_setopt ($ ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); curl_setopt ($ ch, CURLOPT_HEADER, FALSE); // The result must be a string and Output Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, TRUE) on the screen; // set the timeout curl_setopt ($ ch, CURLOPT_TIMEOUT, 30); curl_setopt ($ ch, CURLOPT_POST, TRUE ); // transfer the file curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ xml); // run curl $ data = curl_exec ($ ch); // return the result if ($ data) {curl_close ($ ch); // return success. Convert xml data to an array. $ re = $ this-> FromXml ($ data); if ($ re ['Return _ Code']! = 'Success') {json ("201", 'signature failed');} else {// receives the returned data and sends it to the APP! $ Arr = array ('prepayid' => $ re ['prepay _ id'], 'appid '=> 'wxdbc5dc *****', 'aterid' => '1970 ***** ', 'package' => 'sign = wxpay', 'noncestr' => $ nonce_str, 'timestamp' => time (),); // The second signature generated $ sign = $ this-> getSign ($ arr ); $ arr ['sign'] = $ sign; json ('000000', 'signature successful ', $ arr) ;}} else {$ error = curl_errno ($ ch ); curl_close ($ ch); json ('20140901', "curl error, error code: $ error ");}}

5. Convert xml data to an array and use it when receiving returned data.

Public function FromXml ($ xml) {if (! $ Xml) {echo "xml Data Exception! ";}// Convert XML into array // disable reference to external xml Entity libxml_disable_entity_loader (true); $ data = json_decode (json_encode (simplexml_load_string ($ xml, 'simplexmlelement ', LIBXML_NOCDATA), true); return $ data ;}

2. After the APP payment is successful, the callback address you entered will be called.

For return parameters, see the document: https://pay.weixin.qq.com/wiki/doc/api/app/app.php? Chapter = 9_7 & index = 3

// Payment callback function wx_notify () {// receives the returned data in the xml format $ xmlData = file_get_contents ('php: // input '); // convert the xml format to an array $ data = $ this-> FromXml ($ xmlData); // use a log record to check whether the data is accepted successfully. After the verification is successful, it can be deleted. $ File = fopen ('. /log.txt ', 'a +'); fwrite ($ file, var_export ($ data, true); // verify whether the signature is the same as the returned signature to prevent false data. // Record the returned signature. The sign field must be excluded when the signature is generated. $ Sign = $ data ['sign']; unset ($ data ['sign']); if ($ sign = $ this-> getSign ($ data )) {// if ($ data ['result _ Code'] = 'success ') returned after signature verification is successful ') {// business logic based on the returned order Number $ arr = array ('pay _ status' => 1,); $ re = M ('order ') -> where (['order _ sn '=> $ data ['out _ trade_no'])-> save ($ arr); // after processing is complete, the success result is displayed! If ($ re) {echo '<xml> <return_code> <! [CDATA [SUCCESS]> </return_code> <return_msg> <! [CDATA [OK]> </return_msg> </xml> '; exit () ;}// payment failed. The error message else {$ file = fopen ('. /log.txt ', 'a +'); fwrite ($ file, "error message :". $ data ['Return _ msg ']. date ("Y-m-d H: I: s"), time (). "\ r \ n") ;}} else {$ file = fopen ('. /log.txt ', 'a +'); fwrite ($ file, "error message: Signature Verification Failed ". date ("Y-m-d H: I: s"), time (). "\ r \ n ");}}

Here, the APP payment process is complete! Thank you for your support!

The above example of php app payment implementation is all the content shared by the editor. I hope you can give us a reference and support the house of helping customers.

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.