Thinkphp integrates the WeChat payment function

Source: Internet
Author: User
Tags openid
This article mainly introduces Thinkphp integrated payment function related information, very good, has reference value, friends who need to refer to the next article mainly introduces Thinkphp integrated payment function related information, it is very good and has reference value. if you need it, you can refer to it.

First, I want to tell you that I wrote this article about payment (for general merchants rather than uniform orders by service provider merchants, JSPI:

In fact, I failed to integrate the SDK myself. I used a blog blogger's integrated code and wrote the following notes:

Preparations:

1. public account:

Unique appid, appscrect, and interface permissions are used to set domain names that can obtain user ID information permissions (each user has a unique ID for different public, use this ID to obtain the basic information of the user account and view the developer documentation for details), and set the payment authorization directory in the payment button (written to the layer of the controller that initiates the request) set the developer account to the test White List (required when using the developer tool)

2. payment platform:

Merchant platform login account, payment key (can be set at any time, only one ),

3. integrate the logic into thinkphp:

Front-end payment button settings click to call the payment to initiate the controller method,

The controller runs, referencing the payment class, obtaining the user's openid, obtaining the order data, splicing the data required by all common merchant pre-payment jsp, displaying the custom payment page,

On the payment page, click "pay" and call the provided scripet function to initiate the payment,

After the payment is complete, the page will be redirected to (the jump directory {: U ('Controller/function)} set in the script function of the custom payment page), and asynchronous (silent) set the asynchronous processing order logic (record the payment time, Mark as paid, mark as paid) and so on,

Code:

The payment button on the My orders page:

$ V ['Order _ key_num])} "> pay

Initiate payment controller Wxpay:

 $ _ GET ['Order _ key_num '], 'expire' => 3600); S ('pay _ now_id ', $ _ GET ['Order _ key_num'], 3600);} vendor ('weixinpay. wxPayPubHelper '); // use the jsapi interface $ jsApi = new \ JsApi_pub (); // ========== Step 1: openid ================/// obtain openid through code if ($ _ GET ['code'] = '') {// jump $ redirect_uri = 'https: // current domain name + Module + controller + method'; $ url =' https://open.weixin.qq.com/connect/oauth2/authorize ? Appid = special public account IDredirect_uri = '. $ redirect_uri. '& response_type = code & scope = snsapi_base & state = STATE # wechat_redirect'; header ("Location: $ url"); exit ();} else {// Obtain openid $ url =' https://api.weixin.qq.com/sns/oauth2/access_token ? Appid = public ID & secret = public account scrept & code = '. $ _ GET ['code']. '& grant_type = authorization_code'; $ openid_arr = json_decode (file_get_contents ($ url), true);} $ openid = $ openid_arr ['openid']; $ pay_now_id = S ('pay _ now_id '); if ($ pay_now_id) {$ id = $ pay_now_id; $ o = D ('Order _ info '); $ order_info = $ o-> where ('Order _ id = % d', $ id)-> find (); if (empty ($ order_info ['paycode']) {$ order_info ['paycode'] = 'weixin';} if ($ order_info ['Is _ pay']) {$ this-> error ('Current order already paid ');} else {$ this-> error ("The current order number does not exist! ") ;}$ Res = array ('Order _ sn '=> $ order_info ['Order _ sn'], 'order _ amount '=> $ order_info ['pay _ money']); // ========= Step 2: use the unified payment interface, get prepay_id ==============/// use the unified payment interface $ unifiedOrder = new \ UnifiedOrder_pub (); // Set the unified payment interface parameters // set the required parameters // appid is filled, and merchants do not need to enter the required parameters // mch_id is filled, and merchants do not need to enter the required parameters // noncestr is filled, the merchant does not need to fill in the fields with repeated input // spbill_create_ip, and the merchant does not need to fill in the fields with repeated input // sign, and the merchant does not need to fill in $ total_detail = $ order_info ['pay _ money'] * 100; // $ total_records = $ res [' Order_amount ']; // $ total_amount = 1; // var_dump ($ order_info ['pay _ money']); die; $ body = "order payment "; $ unifiedOrder-> setParameter ("openid", "$ openid"); // User ID $ unifiedOrder-> setParameter ("body", 'item sourcing '); // product description // custom order number. for example, $ unifiedOrder-> setParameter ("out_trade_no", $ order_info ['Order _ sn ']). // merchant Order No. $ unifiedOrder-> setParameter ("total_amount", $ total_amount); // Total amount // $ unifiiedorder-> setParameter ("attach", "order_s N = {$ res ['Order _ sn ']} "); // additional data $ unifiedOrder-> setParameter (" policy_url ", \ WxPayConf_pub: policy_url ); // notification address $ unifiedOrder-> setParameter ("trade_type", "JSAPI"); // transaction type // optional parameter, merchants can select/$ unifiedOrder-> setParameter ("sub_mch_id", "XXXX"); // sub-merchant ID // $ unifiedOrder-> setParameter ("device_info ", "XXXX"); // device No. // $ unifiedOrder-> setParameter ("attach", "XXXX "); // additional data // $ unifiedOrder-> setParameter ("time_start", "X XXX "); // 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 "); // product ID $ prepay_id = $ unifiedOrder-> getPrepayId (); // var_dump ($ prepay_id); die; // ======== Step 3: use jsapi to initiate a payment ===============$ jsApi-> setPrepayId ($ prepay_id); $ jsApiParam Eters = $ jsApi-> getParameters (); $ wxconf = json_decode ($ jsApiParameters, true); if ($ wxconf ['package'] = 'prepay _ id = ') {$ this-> error ('the current order has an exception! ') ;}$ This-> assign ('res', $ res); $ this-> assign ('jsapiparameters', $ jsApiParameters ); $ this-> display ('japi');} // asynchronous notification url. the merchant sets the public function policy_url () {vendor ('weixinpay. wxPayPubHelper '); // use the universal notification interface $ Y = new \ Notify_pub (); // The stored 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. // A policy is adopted (for example, 8 Notifications in 30 minutes) initiate a notification on a regular basis, // improve the notification success rate as much as possible, but it is not guaranteed that the notification will succeed. If ($ Every y-> checkSign () = FALSE) {$ Every y-> setReturnParameter ("return_code", "FAIL "); // return status code $ Y-> setReturnParameter ("return_msg", "signature failed"); // return information} else {$ notify-> setReturnParameter ("return_code ", "SUCCESS"); // set the return code} $ returnXml = $ Y-> returnXml (); // = The merchant sets the corresponding processing process based on the actual situation, here, we only use the example ========/// to record the callback information in the form of a log file // $ log_name = "yy_url.log "; // log file path // $ this-> log_result ($ log_name, "[received notify y]: \ n ". $ Xml. "\ n"); $ parameter = $ policy-> xmlToArray ($ xml); // $ this-> log_result ($ log_name, "[receive notify y ]: \ n ". $ parameter. "\ n"); if ($ Every y-> checkSign () = TRUE) {if ($ Every y-> data ["return_code"] = "FAIL ") {// The order status should be updated here. the merchant adds or deletes the order by himself/$ this-> log_result ($ log_name, "[communication error]: \ n ". $ xml. "\ n"); // update order data [communication error] to invalid order echo 'error ';} else if ($ policy-> data ["result_code"] = "FAIL") {// The order status should be updated here. add or delete the order by the merchant. // $ this-> Log_result ($ log_name, "[service error]: \ n ". $ xml. "\ n"); // update order data [communication error] Set to invalid order echo 'error';} else {// $ this-> log_result ($ log_name, "[payment successful]: \ n ". $ xml. "\ n"); // Here I use a process method. after data is successfully returned, the returned data is processed. for details about the returned data, see if ($ this-> process ($ parameter )) {// if success is output after processing is successful, the echo 'success ';} else {// The request is not processed successfully, send the request echo 'error'; }}}// private function process ($ parameter) for order processing. // The order status should be updated here, the Merchant's own addition/deletion operation/** returns at least the following data: * $ Parameter = array ('out _ trade_no '=> xxx, // merchant order number 'total _ sales' => XXXX, // payment amount 'openid' => XXxxx, // payment user id); */$ data = array ('Order _ sn '=> $ parameter ['out _ trade_no'], 'Des '=> ('Order transaction :'. $ parameter ['out _ trade_no ']), 'Money' => $ parameter ['total _ region'],); orderhandlestarysdgdss ($ data ); // This is a common method. it sets the order status to return true, for example, paid;}?>

After the payment is initiated, splice the pre-payment data parameters (for the parameter list, see the general merchant developer documentation -- payment -- unified order) on the display page:

 
 
 
  Lower
 
 
 

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.