ThinkPHP implements WeChat payment (jsapi payment) process tutorial details, thinkphpjsapi

Source: Internet
Author: User
Tags openid

ThinkPHP implementation of payment (jsapi payment) process tutorial details, thinkphpjsapi

I have written an article about the PHP implementation payment (jsapi payment) process. For details, see the article: PHP implementation payment (jsapi payment) process.

At that time, the environment did not use the framework. After creating a directory under the directory pointed to by a domain name, the directory was accessed for implementation. However, there are still some problems in applying the directory to the framework, in ThinkPHP, an error is reported because the routing rules are different from the payment authorization directory. This article describes how to integrate the payment process in TP.

The sdks and documents provided by the goose factory make you understand them and make it difficult to get around. Should documents and sdks be simpler, easier to understand, and better? Is it true that only vigorous reconstruction can demonstrate the high technical skill of the goose factory programmers? Does the SDK expose the attributes of cainiao? In fact, the SDK is quite useful, but it was also seen in the previous article. In the callback function for payment completion, it is really confusing.

For those who don't want to be bypassed by the official website and want to use the payment in TP, you can refer to a payment SDK that is simplified and developed by a great God based on the official document. I have downloaded the source code and read it, the code is very elegant and easy to understand. See blog: http://baijunyao.com/article/78

I still frown, used the official SDK, and successfully realized the payment. I will share with you the process below:

1. Download and modify the SDK

This is just a little more. If you don't know, you can read my previous article: PHP implements the payment (jsapi payment) process, which details which files need to be modified.

2. Set Public Accounts

A. You still need to set the webpage authorization domain name. This is not special;

B. pay attention to the payment authorization directory. Many users use the REWRITE mode or use the pseudo static mode when using the REWRITE mode, the generated link is: http: // serverName/Home/Blog/read/id/1;

If PATHINFO is used, the generated link is: http: // serverName/index. php/Home/Blog/read/id/1. For example, if a method in the Blog controller of the Home module is used for payment, the authorization directory of the payment should be http: // serverName/Home/Blog/or http: // serverName/index. php/Home/Blog/, which depends on the URL mode set by TP.

3. payment process

(1) unified order

The payment parameter configuration for the order remains unchanged from the previous article. Pay attention to the payment callback verification link because it needs to be called multiple times, I directly go to Application/Common/function. in php, the parameter configuration is encapsulated. My SDK is placed in the Api directory under the project root directory, so the Vendor function is not used when the SDK is introduced.

/*** Payment ** @ param string $ openId openid * @ param string $ goods product name * @ param string $ attach additional parameter. You can choose to pass a parameter, for example, order ID * @ param string $ order_sn Order Number * @ param string $ total_amount */function wxpay ($ openId, $ goods, $ order_sn, $ total_amount, $ attach) {require_once APP_ROOT. "/Api/wxpay/lib/WxPay. api. php "; require_once APP_ROOT. "/Api/wxpay/payment/WxPay. jsApiPay. php "; require_once APP_ROOT. '/Api/wxpay/payment/log. php '; // initialization log $ logHandler = new CLogFileHandler (APP_ROOT. "/Api/wxpay/logs /". date ('Y-m-d '). '. log'); $ log = log: Init ($ logHandler, 15); $ tools = new JsApiPay (); if (empty ($ openId )) $ openId = $ tools-> GetOpenid (); $ input = new WxPayUnifiedOrder (); $ input-> SetBody ($ goods ); // product name $ input-> SetAttach ($ attach); // additional parameter, which can be left blank, the inside string cannot contain spaces $ input-> SetOut_trade_no ($ order_sn); // Order No. $ input-> SetTotal_fee ($ total_fee); // payment amount, unit: minute ($ input-> SetTime_start (date ("YmdHis"); // Payment Initiation time $ input-> SetTime_expire (date ("YmdHis", time () + 600 )); // payment timeout $ input-> SetGoods_tag ("test3"); // $ input-> setpolicy_url ("http ://". $ _ SERVER ['HTTP _ host']. "/payment. php "); // payment callback verification address $ input-> setpolicy_url (" http ://". $ _ SERVER ['HTTP _ host']. "/payment. php/WexinApi/WeixinPay/notify "); $ input-> SetTrade_type (" JSAPI "); // payment type $ input-> SetOpenid ($ openId ); // user openID $ order = WxPayApi: unifiedOrder ($ input); // unified order $ jsApiParameters = $ tools-> GetJsApiParameters ($ order); return $ jsApiParameters ;}

Note: the emphasis on the blackboard is as follows:

The payment callback verification link must not be authenticated. If you need to log on to the registration verification link by yourself, do not try it. You must have a link that is accessible, also, do not transmit a series of parameters.

It is best to use a simple and crude http: // serverName/xxx. php, I am in the directory, similar to index. php, re-write a special portal file for payment callback payment. php, and its corresponding WexinApi module, controller (WeixinPay) and method (policy) in the Application/directory ):

// Check the PHP environment if (version_compare (PHP_VERSION, '5. 3.0 ',' <') die ('require PHP> 5.3.0! '); // $ _ GET ['M'] = 'admin '; // enable the debugging mode. We recommend that you enable the annotation of the deployment phase in the development phase or set it to false define ('app _ debug', True ); // specify the module controller and method $ _ GET ['M'] = 'wexinapi '; $ _ GET ['C'] = 'weixinpa '; $ _ GET ['a'] = 'your y'; // define the application directory define ('app _ path ','. /Application/'); define ("APP_ROOT", dirname (_ FILE _); // introduce the ThinkPHP entry FILE require '. /ThinkCore. php '; // It's so simple that no code is needed in the end

Access http: // serverName/payment now. php directly enters http: // serverName/payment. php/WexinApi/WeixinPay/notify. In this way, you can write http: // serverName/payment to the callback verification link. php, you can also write http: // serverName/payment. php/WexinApi/WeixinPay/notify.

(2) initiate payment

It's still simple:

/* Payment test * Access: http://daoshi.sdxiaochengxu.com/payment.php/WexinApi/WeixinPay/pay */public function pay () {$ order_sn = getrand_num (true); $ openId = ''; $ jsApiParameters = wxpay ($ openId, 'jiangnan geek ', $ order_sn, 1); $ this-> assign (array ('data' => $ jsApiParameters); $ this-> display ();} 

However, pay attention to the URL of the payment page, because the URL of the payment page must contain many parameters. As mentioned in the REWRITE mode in TP, your link is similar to [http: // serverName/Home/Blog/read/id/1] may contain more parameters. At this time, the payment will assume that your payment authorization directory is [http: // serverName/Home/Blog/read/id/], but your actual authorization directory is [http: // serverName/Home/Blog/], so an error is reported. The solution is to refactor the URL and write it into the normal mode when entering the payment page, that is, [http: // serverName/Home/Blog/read? Id = 1.

(3) support successful callback

After the payment is complete, you will go to the method corresponding to the previously written link, that is, [http: // serverName/payment. php/WexinApi/WeixinPay/notify]:

// Payment callback verification public function notify () {$ xml = $ GLOBALS ['HTTP _ RAW_POST_DATA ']; // The file_put_contents statement is used to view the XML data returned by the server. After testing, you can delete file_put_contents ('. /Api/wxpay/logs/log.txt ', $ xml, FILE_APPEND); // convert the XML data returned by the server to an array // $ data = json_decode (json_encode (simplexml_load_string ($ xml, 'simplexmlelement', LIBXML_NOCDATA), true); $ data = xmlToArray ($ xml); // Save the signature sign returned by the server $ data_sign = $ data ['sign']; // sign does not participate in the signature algorithm unse T ($ data ['sign']); $ sign = $ this-> makeSign ($ data ); // determine whether the signature is correct. Determine the payment status if ($ sign ===$ data_sign) & ($ data ['Return _ Code'] = 'success ') & ($ data ['result _ Code'] = 'success') {$ result = $ data; // The file_put_contents statement is used to view the XML data returned by the server. After testing, you can delete file_put_contents ('. /Api/wxpay/logs/log1.txt ', $ xml, FILE_APPEND); // obtain the data returned by the server $ order_sn = $ data ['out _ trade_no']; // Order No. $ order_id = $ data ['Attach ']; // additional parameter, select transfer order ID $ openid = $ data ['openid']; // payer openid $ total_region = $ data ['total _ region']; // payment amount // update database $ this-> updateDB ($ order_id, $ order_sn, $ openid, $ total_fee);} else {$ result = false ;} // return the status to the server if ($ result) {$ str = '<xml> <return_code> <! [CDATA [SUCCESS]> </return_code> <return_msg> <! [CDATA [OK]> </return_msg> </xml> ';} else {$ str =' <xml> <return_code> <! [CDATA [FAIL]> </return_code> <return_msg> <! [CDATA [Signature failed]> </return_msg> </xml> ';} echo $ str; return $ result ;}

For the sake of security, re-verify the returned signature:

/*** Generate the signature * @ return signature. This function does not overwrite the sign member variable */protected function makeSign ($ data) {// obtain the payment key require_once APP_ROOT. "/Api/wxpay/lib/WxPay. api. php "; $ key = \ WxPayConfig: KEY; // enter $ data = array_filter ($ data); // signature Step 1: the parameter ksort ($ data); $ string_a = http_build_query ($ data); $ string_a = urldecode ($ string_a); // signature Step 2: add KEY // $ config = $ this-> config; $ string_sign_temp = $ string_a. "& key = ". $ key; // signature Step 3: MD5 encryption $ sign = md5 ($ string_sign_temp); // signature Step 4: Convert all characters to uppercase $ result = strtoupper ($ sign ); return $ result ;}

So far, the payment in TP will be done. This is integrated with the official SDK. If you do not use the SDK, you can use a simpler method. For details, see PHP implementation of payment (jsapi payment) and refund (no need to integrate the payment SDK)

Summary

The above is a detailed tutorial on ThinkPHP implementation payment (jsapi payment). I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.