Thinkphp integrates the WeChat payment function and thinkphp payment function

Source: Internet
Author: User
Tags openid

Thinkphp integrated payment and thinkphp payment functions

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:

<A href = "{: U ('wxpay/js_api_start ', array ('order _ key_num' => $ v ['order _ key_num])} "> payment </a>

Initiate payment controller Wxpay:

<? Phpnamespace Home \ Controller; use Think \ Controller; // payment class WxpayController extends Controller {// jump uri when obtaining access_token, pass the code to the jsapi payment page through the jump public function js_api_start () {if (! Empty ($ _ GET ['order _ key_num ']) {// session (array ('pay _ now_id' => $ _ 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/o Au22./authorize? Appid = Special Public Account IDredirect_uri = '. $ redirect_uri. '& response_type = code & scope = snsapi_base & state = STATE # wechat_redirect'; header ("Location: $ url"); exit ();} else {// get 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:

<! DOCTYPE html> 

Then there is a class file:

The cacert is the certificate storage directory; the certificate is not required;

Find the vendor folder in my files.

The above is the Thinkphp integrated payment function introduced by xiaobian. I hope it will help you. If you have any questions, please leave a message and I 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.