thinkphp integrated micro-credit payment function _php Example

Source: Internet
Author: User

First effect Picture: I'm going to tell you. This article is written in the micro-letter payment (ordinary merchant rather than the service provider Merchant's unified JSPI) micro-letter payment:

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

Previous preparation:

1, micro-credit public number:

Unique AppID, Appscrect, interface permissions to set the domain name that can obtain user ID information permissions (each user will have a unique ID for different public, through this ID to obtain the user's micro-credit account basic information, details to see the micro-trust developer documentation), Set up a micro-credit payment authorization directory on the Micro-credit button (write to the controller that initiates the request), and set up the developer micro-account for the test whitelist (required when using the micro-trust developer tool)

2, micro-credit payment platform:

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

3, integration into the thinkphp logic:

Front-end micro-letter Payment button Set Click call Payment Initiator Controller method,

Controller operation, reference micro-letter payment category, get user OpenID, get order data, stitching out all ordinary merchant pre-payment JSP required data, display out of that custom payment page,

In the payment page click Pay, call the micro-letter provided by the JSPI to initiate the payment of the Scripet function to initiate payment,

After the payment completes, the page is redirected to the jump directory {: U (' controller/function)} ' set in the script function of the custom payment page, and the asynchronous (silent) Set asynchronous processing order logic (record payment time, marked as already paid, The mark is a micro-letter payment) or something,

Code:

The micro-mail payment button for my order page:

<a href= ' {: U (' Wxpay/js_api_start ', Array (' Order_key_num ' => $v [' order_key_num])} ' > Micro-credit Payment </a>

Initiate payment controller Wxpay:

<?php namespace Home\controller;
Use Think\controller; Micro-Credit Payment class Wxpaycontroller extends Controller {//Get the jump URI in the Access_token process, passing code into the JSAPI Payment page public Function Js_ap I_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: Web page authorization to obtain the user openid============//via code to obtain OpenID if ($_get[' code '] = = ') {//jump $redirect _uri = ' http
    s://Current domain + module + controller + method '; $url = ' https://open.weixin.qq.com/connect/oauth2/authorize appid= public number 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 number Scrept&amp 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 ("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 up uniform Payment interface parameters//set Required parameters//appid has been filled out, the merchant does not need to fill in the//mch_id has been filled, the merchant does not need to fill in the duplicate//noncestr has filled in, the merchant does not need to repeat fills//spbill_create_ip has filled, the merchant does not need
  Sign has been filled, the merchant does not need to fill $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 identification $unifiedOrder->setparameter ("body", ' commodity purchase ');//Product Description/ /custom order number, here 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, the merchant may fill in the actual situation by filling//$unifiedOrder->setparameter ("sub_mch_id", " XXXX ");//Merchant number//$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");//mark of goods//$ Unifiedorder->setparameter ("OpenID", "XXXX");//user ID//$unifiedOrder-&GT;SETPArameter ("product_id", "XXXX");//commodity id $prepay _id = $unifiedOrder->getprepayid ();
  Var_dump ($prepay _id);d ie;
  ========= Step 3: Use Jsapi to adjust payment ============ $jsApi->setprepayid ($prepay _id);
  $jsApiParameters = $jsApi->getparameters ();
  $wxconf = Json_decode ($jsApiParameters, true);
  if ($wxconf [' package '] = = ' prepay_id= ') {$this->error (' current order is abnormal! ')
  $this->assign (' res ', $res);
  $this->assign (' jsapiparameters ', $jsApiParameters);
 $this->display (' Jsapi ');
  ///asynchronous notification URL, the merchant based on the actual development process to set Public function Notify_url () {Vendor (' weixinpay.wxpaypubhelper ');
  Use the universal notification interface $notify = new \notify_pub (); 
  A callback $xml for storing a micro-letter = $GLOBALS [' Http_raw_post_data '];
  $notify->savedata ($xml);
  Verify the signature and respond to the micro-letter.
  When you interact with a background notification, if the micro-letter received the merchant's reply is not a success or timeout, the micro-letter believes that the notification failed,//micro-letter through a certain strategy (such as 30 minutes a total of 8 times) to periodically restart the notification,///As far as possible to increase the success rate of notification, but the if ($notify->checksign () = FALSE) {$notify->setreturnparameter ("Return_code", "FAIL");//Return Status code $notify->set Returnparameter ("Return_msg", "Signature failed//Return information}else{$notify->setreturnparameter ("Return_code", "SUCCESS");/Set return code} $RETURNXML = $notify->retu
  rnXML (); = Merchant According to the actual situation set up the corresponding processing flow, here just for example =======//log file Form record callback information//$log _name = "Notify_url.log";//log file path//$this->log_resul T ($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") {//The order status should be updated here, the merchant's own additions and deletions operation/ /$this->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") {//This should update the order status, the merchant's own additions and deletions operation//$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, successfully returns the data processing, the return data can refer to the micro-letter document specifically ($this->process ($parameter)){//Processing success after output success, micro-letter will not be issued request echo ' success ';
    }else {//No successful processing, the micro-letter will send the interval request echo ' ERROR '; ///Order Processing Private Function process ($parameter) {//This should update the order status, the merchant's own additions and deletions operation * * The data returned by at least a few * $paramet
  er = Array (' out_trade_no ' => xxx,//merchant order number ' Total_fee ' => xxxx,//pay the amount ' OpenID ' => the user ID of the payment); */$data = array (' ORDER_SN ' => $parameter [' out_trade_no '], ' des ' => (' Order transaction: '. $parameter [' out_trade_no '])
  , ' Money ' => $parameter [' Total_fee '],);
 ORDERHANDLESTARYSDGDSS ($data);//This is a common method, he will set the order status to be paid and so on return true; }}?>

Post-payment pre-payment data parameters (parameter list for micro-trust merchant developer documents-micro-credit payment-Unified order) display page:

<! DOCTYPE html>  

And then there's the class file:

That CACert is a certificate store directory, the certificate does not necessarily need;

The vendor folder can be found in my file.

The above is a small set to introduce the thinkphp integrated micro-credit payment function, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.