Integrate ThinkPHP with WeChat payment in JSAPI Mode

Source: Internet
Author: User
Tags flock openid
Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn. Currently, payment is rarely seen on the Internet for a series of detailed demos. Therefore, take a moment to complete the payment series tutorials. This tutorial is based on the JSAPI mode, and others will continue to be written.
First, download the payment demo and integrate it into TP Based on the demo.

This section describes the following files:

In the demo Folder:
Js_api_call.php: provides the main functions of jsapi.
Log _. php: Provides the log printing function.
Notify_url.php: asynchronous notification function
Notify_url.log: asynchronous notification log
Qrcode. js: generate the QR code js plug-in

Next we will introduce the files in the WxPayPubHelper Folder:

The cacert folder stores the certificate (PS: I have not used the certificate yet. Although the certificate has been downloaded, please download it on the merchant's platform)
SDKRuntimeException. php: handle exceptions,
WxPay. pub. config. php: some configurations will be made.
WxPayPubHelper. php: This is actually the payment tool class. It is enough for beginners to know how to use the methods in it.

OK. After learning about the official files, we can start to integrate them into TP. If you don't talk much about it, let's get started!

Step 1: copy the entire WxPayPubHelper folder in the demo to the vender directory of TP, like me:

Step 2: configure the WxPay. pub. config. php file:
All the configurations here are commented out. If you still do not understand the configurations or encounter configuration problems, you can leave a message to ask questions.
At the same time, I put this configuration in the TP config, which can be freely used. Return array (
// 'Config maps '=> 'configuration value'
Define ('web _ host', 'This is your website domain address '),
/* Payment configuration */
'Wxpayconf _ pub' => array (
'Appid '=> 'your APPID ',
'Mkid' => 'your merchant id ',
'Key' => 'Merchant's KEY ',
'Appsecret' => 'your appsecret ',
'Js _ API_CALL_URL '=> WEB_HOST.'/index. php/Home/WxJsAPI/jsapicall ',
'Sslcert _ path' => WEB_HOST. '/ThinkPHP/Library/Vendor/WxPayPubHelper/cacert/apiclient_cert.pem ',
'Sslkey _ path' => WEB_HOST. '/ThinkPHP/Library/Vendor/WxPayPubHelper/cacert/apiclient_key.pem ',
'Your Y _ url' => WEB_HOST. '/index. php/Home/WxJsAPI/Your y ',
'Curl _ timeout' => 30
)
);
Step 3: place the js Code that generates the QR code in the Public directory (this js is not used here, and it is used only when the QR code is used for payment) and put the log file in the Public directory: like me:

Step 4: Create a controller: here we have created a WxJsAPIController controller. Here we can give you a name as long as it matches your settings on the public platform (public platform settings will be introduced later)

The following is the Controller code. First, initialize the controller and import WxPayPubHelper /**
* Initialization
*/
Public function _ initialize ()
{
// Introduce WxPayPubHelper
Vendor ('wxpaypubhelper. WxPayPubHelper ');
}
Next, use the unified payment interface to obtain the prepay_id: Public function jsApiCall ()
{
// Use the jsapi
$ JsApi = new \ JsApi_pub ();

// =========== Step 1: Obtain the user's openid through web page authorization ==============
// Obtain the openid through code
If (! Isset ($ _ GET ['code'])
{
// Trigger return code
$ Url = $ jsApi-> createOauthUrlForCode (C ('wxpayconf _ pub. JS_API_CALL_URL '));
Header ("Location: $ url ");
} Else
{
// Obtain the code to obtain the openid
$ Code = $ _ GET ['code'];
$ JsApi-> setCode ($ code );
$ Openid = $ jsApi-> getOpenId ();
}

// ========= Step 2: Use the unified payment interface to obtain the prepay_id ==============
// Use the unified payment Interface
$ UnifiedOrder = new \ UnifiedOrder_pub ();

// Set unified payment Interface Parameters
// Set required parameters
// Appid is entered, and merchants do not need to fill it again
// Mch_id is entered, and the Merchant does not need to fill it again
// Noncestr is entered, and merchants do not need to enter it again
// Spbill_create_ip has been filled in, and merchants do not need to fill it in again
// The sign has been filled in, and the Merchant does not need to fill in it again
$ UnifiedOrder-> setParameter ("openid", $ openid); // product description
$ UnifiedOrder-> setParameter ("body", "contribute a penny"); // product description
// Customize the order number, which is used as an example here
$ TimeStamp = time ();
$ Out_trade_no = C ('wxpayconf _ pub. APPID '). $ timeStamp;
$ UnifiedOrder-> setParameter ("out_trade_no", $ out_trade_no); // merchant's Order Number
$ UnifiedOrder-> setParameter ("total_eter", "1"); // total amount
$ UnifiedOrder-> setParameter ("notify_url", C ('wxpayconf _ pub. yy_url '); // notification address
$ UnifiedOrder-> setParameter ("trade_type", "JSAPI"); // transaction type
// Optional parameters
// $ UnifiedOrder-> setParameter ("sub_mch_id", "XXXX"); // sub-merchant ID
// $ UnifiedOrder-> setParameter ("device_info", "XXXX"); // device number
// $ UnifiedOrder-> setParameter ("attach", "XXXX"); // additional data
// $ UnifiedOrder-> setParameter ("time_start", "XXXX"); // transaction Start Time
// $ UnifiedOrder-> setParameter ("time_expire", "XXXX"); // transaction End Time
// $ UnifiedOrder-> setParameter ("goods_tag", "XXXX"); // product tag
// $ UnifiedOrder-> setParameter ("openid", "XXXX"); // user ID
// $ UnifiedOrder-> setParameter ("product_id", "XXXX"); // item ID

$ Prepay_id = $ unifiedOrder-> getPrepayId ();
// ========= Step 3: Use jsapi to initiate a payment ================
$ JsApi-> setPrepayId ($ prepay_id );

$ JsApiParameters = $ jsApi-> getParameters ();

$ This-> assign ('jsapiparameters ', $ jsApiParameters );
$ This-> display ('pae ');
// Echo $ jsApiParameters;
}
Here we all copy the demo. Just change the name. There is nothing else.

The next step is the asynchronous notification method, which is also on the replication demo. Public function notify ()
{
// Use the universal notification Interface
$ Policy = new \ policy_pub ();

// Storage callback
$ Xml = $ GLOBALS ['HTTP _ RAW_POST_DATA '];
$ Policy-> saveData ($ xml );

// Verify the signature and respond.
// For background notification interaction, if the response received by the merchant is not successful or times out, the notification is deemed to fail,
// The notification will be sent back on a regular basis through a certain policy (for example, 8 times in 30 minutes,
// Improve the notification success rate as much as possible, but it is not guaranteed that the notification will succeed.
If ($ policy-> checkSign () = FALSE ){
$ Y-> setReturnParameter ("return_code", "FAIL"); // return the status code
$ Y-> setReturnParameter ("return_msg", "signature failed"); // return information
} Else {
$ Y-> setReturnParameter ("return_code", "SUCCESS"); // you can specify the return code.
}
$ ReturnXml = $ notify-> returnXml ();
Echo $ returnXml;

// = The Merchant sets the corresponding processing process based on the actual situation. Here, only the example ========

// Record the callback information in the form of a log file
// $ Log _ = new Log _();
$ Log_name =. "/Public/notify_url.log"; // log File Path

Log_result ($ log_name, "[received notify y Notification]: \ n". $ xml. "\ n ");

If ($ policy-> checkSign () = TRUE)
{
If ($ policy-> data ["return_code"] = "FAIL "){
// The order status should be updated here, and merchants can add or delete orders by themselves
Log_result ($ log_name, "[communication error]: \ n". $ xml. "\ n ");
}
Elseif ($ policy-> data ["result_code"] = "FAIL "){
// The order status should be updated here, and merchants can add or delete orders by themselves
Log_result ($ log_name, "[service error]: \ n". $ xml. "\ n ");
}
Else {
// The order status should be updated here, and merchants can add or delete orders by themselves
Log_result ($ log_name, "[payment successful]: \ n". $ xml. "\ n ");
}

// The Merchant adds the processing process by himself,
// For example, update the order status
// For example, database operations
// Example: Push payment completion Information
}
}
Here I write the logging class to function. php: Function log_result ($ file, $ word)
{
$ Fp = fopen ($ file, "");
Flock ($ fp, LOCK_EX );
Fwrite ($ fp, "execution date :". strftime ("% Y-% m-% d-% H: % M: % S", time ()). "\ n ". $ word. "\ n ");
Flock ($ fp, LOCK_UN );
Fclose ($ fp );
}
Okay, actually there are so many controller methods. There is nothing else. Let's take a look at the page and go directly to the Code:



Secure Payment

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.