thinkphp micro-Credit payment function

Source: Internet
Author: User
Tags openid
This article mainly introduces the thinkphp integrated payment function of the relevant information, very good, with reference value, the need for friends can refer to the next

First: I want to tell you that this article is written in the payment of (the common merchant rather than the merchant's uniform order Jspi) Payment:

In fact, the integration of the SDK failed, with a blog blogger integrated code, here to write notes:

Front Preparation:

1. Public Number:

Unique AppID, Appscrect, interface permissions set the domain name that can get the user ID information permission (each user will have a unique ID for different public, through this ID to get the basic information of the user account, the details of the developer documentation), In the payment button out of the set up payment authorization directory (write to the controller that initiated the request layer), set the developer account for the test whitelist (required when using developer tools)

2. Payment Platform:

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

3, integration into the thinkphp logic:

Front-End Payment button settings Click Invoke Payment Initiator Controller method,

The controller runs, refers to the payment class, obtains the user OpenID, obtains the order data, stitching out all the ordinary merchant pre-payment JSP needs data, display the custom payment page,

On the payment page click Pay, call the provided JSPI initiate payment Scripet function to initiate the payment,

After payment is completed, the page is redirected to the (jump directory {: U (' Controller/function)}), which is set in the script function of the custom payment page, and the asynchronous (silent) setting of the Asynchronous Processing order logic (record payment time, Mark as already paid, Mark is paid) and the like

Code:

The payment button on my order 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 {//Get Access_ Token in the process of the jump URI, by jumping the code into the JSAPI Payment page 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 ');  Using the JsApi interface $jsApi = new \jsapi_pub (); ========= Step 1: Web authorization to get the user openid============//through code to get OpenID if ($_get[' code ' = = ") {//jump $redirect _uri = ' https://    Current domain + module + controller + method '; $url = ' https://open.weixin.qq.com/connect/oauth2/authorize appid= public Special 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 number id&secret= public No. scrept&c Ode= '. $_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 has been paid ');  }}else{$this->error ("There is no current order number!");  } $res = Array (' order_sn ' = = $order _info[' order_sn '), ' order_amount ' = = $order _info[' Pay_money ']);  ========= Step 2: Use the unified payment interface to obtain prepay_id============//using the Unified Payment interface $unifiedOrder = new \unifiedorder_pub (); Set the unified Payment interface parameters//settings required Parameters//appid has been filled, merchants do not need to fill//mch_id filled, merchants do not need to fill in the//noncestr, merchants do not need to fill in the//spbill_create_ip filled, merchants do not need to repeat the//s  IGN is filled, merchants do not need to fill in the $total _fee = $order _info[' Pay_money ']*100;  $total _fee = $res [' Order_amount '];  $total _fee = 1;  Var_dump ($order _info[' Pay_money ');d ie;  $body = "Order Payment"; $unifiedOrder->setparameter ("OpenID", "$openid");//user ID $unifiEdorder->setparameter ("Body", ' merchandise purchase ');//Product Description//Custom order number, only for example $unifiedOrder->setparameter ("Out_trade_no", $ order_info[' ORDER_SN ');//Merchant Order number $unifiedOrder->setparameter ("Total_fee", $total _fee);//Total amount//$unifiedOrder- >setparameter ("Attach", "order_sn={$res [' Order_sn ']}");//Additional Data $unifiedOrder->setparameter ("Notify_url", \ Wxpayconf_pub::notify_url)///Notification address $unifiedOrder->setparameter ("Trade_type", "JSAPI");//transaction type//non-required parameter, The merchant may choose to fill in according to the actual situation//$unifiedOrder->setparameter ("sub_mch_id", "XXXX");//Sub-merchant number//$unifiedOrder->setparameter (" Device_info "," xxxx ");//device number//$unifiedOrder->setparameter (" Attach "," xxxx ");//Additional data//$unifiedOrder Setparameter ("Time_start", "xxxx");//Trading start time//$unifiedOrder->setparameter ("Time_expire", "xxxx");//Trading End time//$ Unifiedorder->setparameter ("Goods_tag", "xxxx");//commodity mark//$unifiedOrder->setparameter ("OpenID", "xxxx");// User ID//$unifiedOrder->setparameter ("product_id", "XXXX");//commodity id $prepay _id = $unifiedOrder->getprepayid ();  Var_dump ($prepay _id);d ie;  ========= Step 3: Use JsApi to adjust the payment ============ $jsApi->setprepayid ($prepay _id);  $jsApiParameters = $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 (' Jsapi ');  }//Asynchronous notification URL, the merchant sets public Function Notify_url () {Vendor (' weixinpay.wxpaypubhelper ') according to the actual development process;  Use the generic notification interface $notify = new \notify_pub ();   The stored callback $xml = $GLOBALS [' Http_raw_post_data '];  $notify->savedata ($xml);  Verify the signature and respond.  When interacting with background notifications, if the acknowledgement received by the Merchant is not successful or timed out, the notification fails,//The notification is periodically re-initiated through a certain strategy (e.g. 8 times in 30 minutes)//To maximize the success rate of the notification, but does not guarantee that the notification will eventually succeed. if ($notify->checksign () = = FALSE) {$notify->setreturnparameter ("Return_code", "FAIL");//Return Status code $notify Setreturnparameter ("Return_msg", "Signature failed");//return information}else{$notify->setreturnparameter ("Return_code", "SUCCESS");// Set return code} $RETURNXML = $notify->returnxmL (); = = Merchant According to the actual situation to set up the corresponding processing flow, here only for example =======//log callback information in the form of logs file//$log _name = "Notify_url.log";//log file path//$this->log_ Result ($log _name, "" Notify notification Received: \ n ". $xml."  \ n ");  $parameter = $notify->xmltoarray ($xml); $this->log_result ($log _name, "" Received notify notification: \ n ". $parameter."  \ n "); if ($notify->checksign () = = TRUE) {if ($notify->data["return_code"] = = "FAIL") {///Here The order status should be updated, merchant's own additions/deletions//$t His->log_result ($log _name, "Communication error: \ n". $xml. "    \ n ");   Update order Data "Communication error" set to invalid order echo ' error '; } else if ($notify->data["result_code"] = = "FAIL") {//The order status should be updated here, the merchant has to delete//$this->log_result ($log _name, "" Business Error ": \ n". $xml. "    \ n ");   Update order Data "Communication error" set to invalid order echo ' error '; } else{//$this->log_result ($log _name, "" Payment succeeded: \ n ". $xml."    \ n "); I use a process method here, the successful return of data processing, the return of the data can be referenced to the specific document if ($this->process ($parameter)) {//After processing the successful output success, will not be issued a request Ech    O ' success ';    }else {//did not process successfully, will be sent at intervals of the request echo ' error '; }}}}//Order Processing Private Function process ($Parameter) {//Here should update the status of the order, the Merchant's own additions and deletions * * * The data returned at least the following * $parameter = Array (' out_trade_no ' + xxx,//merchant order number ' tot  Al_fee ' + xxxx,//payment amount ' OpenID ' = xxxxx,//payment user ID);      */$data = array (' order_sn ' = = $parameter [' out_trade_no '], ' des ' = = (' Order trading: ' $parameter [' out_trade_no ']),  ' Money ' = $parameter [' Total_fee '],); ORDERHANDLESTARYSDGDSS ($data);//This is a common method that will set the order status to return true, such as paid; }}?>

Post-payment stitching pre-payment data parameters (parameter list see general merchant Developer Documentation-payment-Unified order) display page:

<! DOCTYPE html>

Then there is the class file:

The CACert is a certificate store directory; The certificate is not necessarily required;

The vendor folder can be found in my file.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

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.