This article mainly introduces the relevant information about Thinkphp integrating WeChat payment function. It is very good and has reference value. Friends who need it can refer to it.
First, let’s look at the renderings: I want to tell you about this. This article is about WeChat payment (unified order JSPI for ordinary merchants rather than service provider merchants) WeChat payment:
In fact, I failed to integrate the SDK myself. I used the code integrated by a blogger. Write a note here:
Preparation:
1. WeChat public account:
Set the domain name that can obtain the user ID information permission among the unique appid, appscrect, and interface permissions (each user will have different permissions for different publics) A unique ID. Use this ID to obtain the basic information of the user's WeChat account. For details, see the WeChat developer documentation), set the WeChat payment authorization directory on the WeChat payment button (write to the level of the controller that initiates the request), and set the developer WeChat account. To test the whitelist (required when using WeChat developer tools)
2. WeChat payment platform:
Merchant platform login account and payment key (you can create it yourself at any time Settings, there can only be one),
3. Integrate into thinkphp logic:
Front-end WeChat payment button settings click to call the payment initiation controller method,
The controller runs, references the WeChat payment class, obtains the user openid, obtains the order data, splices out all the data required by ordinary merchants’ prepayment jsp, and displays the customized payment page.
During payment Click on the page to pay, call the jspi script function provided by WeChat to initiate payment,
After the payment is completed, the page will redirect to (the jump directory set in the script function of the custom payment page {:U( 'controller/function)}), and asynchronous (silent) settings for asynchronous processing of order logic (record payment time, mark as paid, mark as WeChat payment) and the like,
Code:
WeChat payment button on my order page:
<a href="{:U('Wxpay/js_api_start',array('order_key_num'=>$v['order_key_num]))}"> 微信支付</a>
Initiate payment controller Wxpay:
<?php namespace Home\Controller; use Think\Controller; //微信支付類 class WxpayController extends Controller { //獲取access_token過程中的跳轉(zhuǎn)uri,通過跳轉(zhuǎn)將code傳入jsapi支付頁面 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'); //使用jsapi接口 $jsApi = new \JsApi_pub(); //=========步驟1:網(wǎng)頁授權(quán)獲取用戶openid============ //通過code獲得openid if($_GET['code'] == ''){ //跳轉(zhuǎn) $redirect_uri = 'https://當(dāng)前域名+模塊+控制器+方法'; $url = 'https://open.weixin.qq.com/connect/oauth2/authorize ?appid=公眾號(hào)特有IDredirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'; header("Location: $url"); exit(); }else{ //獲取openid $url = 'https://api.weixin.qq.com/sns/oauth2/access_token ?appid=公眾號(hào)ID&secret=公眾號(hào)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('當(dāng)前訂單已經(jīng)支付'); } }else{ $this->error("不存在當(dāng)前訂單編號(hào)!"); } $res = array( 'order_sn' => $order_info['order_sn'], 'order_amount' => $order_info['pay_money'] ); //=========步驟2:使用統(tǒng)一支付接口,獲取prepay_id============ //使用統(tǒng)一支付接口 $unifiedOrder = new \UnifiedOrder_pub(); //設(shè)置統(tǒng)一支付接口參數(shù) //設(shè)置必填參數(shù) //appid已填,商戶無需重復(fù)填寫 //mch_id已填,商戶無需重復(fù)填寫 //noncestr已填,商戶無需重復(fù)填寫 //spbill_create_ip已填,商戶無需重復(fù)填寫 //sign已填,商戶無需重復(fù)填寫 $total_fee = $order_info['pay_money']*100; // $total_fee = $res['order_amount']; //$total_fee = 1; // var_dump($order_info['pay_money']);die; $body = "訂單支付"; $unifiedOrder->setParameter("openid", "$openid");//用戶標(biāo)識(shí) $unifiedOrder->setParameter("body", '商品采購');//商品描述 //自定義訂單號(hào),此處僅作舉例 $unifiedOrder->setParameter("out_trade_no", $order_info['order_sn']);//商戶訂單號(hào) $unifiedOrder->setParameter("total_fee", $total_fee);//總金額 //$unifiedOrder->setParameter("attach", "order_sn={$res['order_sn']}");//附加數(shù)據(jù) $unifiedOrder->setParameter("notify_url", \WxPayConf_pub::NOTIFY_URL);//通知地址 $unifiedOrder->setParameter("trade_type", "JSAPI");//交易類型 //非必填參數(shù),商戶可根據(jù)實(shí)際情況選填 //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商戶號(hào) //$unifiedOrder->setParameter("device_info","XXXX");//設(shè)備號(hào) //$unifiedOrder->setParameter("attach","XXXX");//附加數(shù)據(jù) //$unifiedOrder->setParameter("time_start","XXXX");//交易起始時(shí)間 //$unifiedOrder->setParameter("time_expire","XXXX");//交易結(jié)束時(shí)間 //$unifiedOrder->setParameter("goods_tag","XXXX");//商品標(biāo)記 //$unifiedOrder->setParameter("openid","XXXX");//用戶標(biāo)識(shí) //$unifiedOrder->setParameter("product_id","XXXX");//商品ID $prepay_id = $unifiedOrder->getPrepayId(); // var_dump($prepay_id);die; //=========步驟3:使用jsapi調(diào)起支付============ $jsApi->setPrepayId($prepay_id); $jsApiParameters = $jsApi->getParameters(); $wxconf = json_decode($jsApiParameters, true); if ($wxconf['package'] == 'prepay_id=') { $this->error('當(dāng)前訂單存在異常!'); } $this->assign('res', $res); $this->assign('jsApiParameters', $jsApiParameters); $this->display('jsapi'); } //異步通知url,商戶根據(jù)實(shí)際開發(fā)過程設(shè)定 public function notify_url() { vendor('Weixinpay.WxPayPubHelper'); //使用通用通知接口 $notify = new \Notify_pub(); //存儲(chǔ)微信的回調(diào) $xml = $GLOBALS['HTTP_RAW_POST_DATA']; $notify->saveData($xml); //驗(yàn)證簽名,并回應(yīng)微信。 //對(duì)后臺(tái)通知交互時(shí),如果微信收到商戶的應(yīng)答不是成功或超時(shí),微信認(rèn)為通知失敗, //微信會(huì)通過一定的策略(如30分鐘共8次)定期重新發(fā)起通知, //盡可能提高通知的成功率,但微信不保證通知最終能成功。 if($notify->checkSign() == FALSE){ $notify->setReturnParameter("return_code", "FAIL");//返回狀態(tài)碼 $notify->setReturnParameter("return_msg", "簽名失敗");//返回信息 }else{ $notify->setReturnParameter("return_code", "SUCCESS");//設(shè)置返回碼 } $returnXml = $notify->returnXml(); //==商戶根據(jù)實(shí)際情況設(shè)置相應(yīng)的處理流程,此處僅作舉例======= //以log文件形式記錄回調(diào)信息 //$log_name = "notify_url.log";//log文件路徑 //$this->log_result($log_name, "【接收到的notify通知】:\n".$xml."\n"); $parameter = $notify->xmlToArray($xml); //$this->log_result($log_name, "【接收到的notify通知】:\n".$parameter."\n"); if($notify->checkSign() == TRUE){ if ($notify->data["return_code"] == "FAIL") { //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作 //$this->log_result($log_name, "【通信出錯(cuò)】:\n".$xml."\n"); //更新訂單數(shù)據(jù)【通信出錯(cuò)】設(shè)為無效訂單 echo 'error'; } else if($notify->data["result_code"] == "FAIL"){ //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作 //$this->log_result($log_name, "【業(yè)務(wù)出錯(cuò)】:\n".$xml."\n"); //更新訂單數(shù)據(jù)【通信出錯(cuò)】設(shè)為無效訂單 echo 'error'; } else{ //$this->log_result($log_name, "【支付成功】:\n".$xml."\n"); //我這里用到一個(gè)process方法,成功返回?cái)?shù)據(jù)后處理,返回地?cái)?shù)據(jù)具體可以參考微信的文檔 if ($this->process($parameter)) { //處理成功后輸出success,微信就不會(huì)再下發(fā)請(qǐng)求了 echo 'success'; }else { //沒有處理成功,微信會(huì)間隔的發(fā)送請(qǐng)求 echo 'error'; } } } } //訂單處理 private function process($parameter) { //此處應(yīng)該更新一下訂單狀態(tài),商戶自行增刪操作 /* * 返回的數(shù)據(jù)最少有以下幾個(gè) * $parameter = array( 'out_trade_no' => xxx,//商戶訂單號(hào) 'total_fee' => XXXX,//支付金額 'openid' => XXxxx,//付款的用戶ID ); */ $data = array( 'order_sn'=>$parameter['out_trade_no'], 'des'=>('訂單交易:'.$parameter['out_trade_no']), 'money'=>$parameter['total_fee'], ); orderhandlestarysdgdss($data);//這是一個(gè)common方法,他會(huì)將該訂單狀態(tài)設(shè)置為已支付之類的 return true; } } ?>
After initiating payment, the prepayment data parameters are spliced ??(for the parameter list, please refer to WeChat ordinary merchant developer documentation - WeChat payment - unified order) display page:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" /> <meta name="format-detection" content="telephone=no"/> <title>下</title> <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> <meta name="keyword" content=""> <meta name="description" content=""> <script type="text/javascript"> var order_sn = "{$res['order_sn']}"; //調(diào)用微信JS api 支付 function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', <?php echo $jsApiParameters; ?>, function(res){ //如果支付成功 if (res.err_msg == 'get_brand_wcpay_request:ok') { //支付成功后跳轉(zhuǎn)的地址 location.href = "{:U('Home/User/my_order')}"; }else if (res.err_msg == 'get_brand_wcpay_request:cancel') { alert('請(qǐng)盡快完成支付哦!'); }else if (res.err_msg == 'get_brand_wcpay_request:fail') { alert('支付失敗'); }else { alert('意外錯(cuò)誤'); } //WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); /*if (res.err_msg == 'get_brand_wcpay_request:ok') { alert('支付成功'); }else { alert('取消支付'); }*/ } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> <style> *{font-family:'微軟雅黑','Microsoft YaHei';} body #head{position:relative;z-index:99999999999999;padding:0 10px;} body .zh-head{padding:0 0 0 0;height:auto;} .zh-head-conter{position:relative;height:40px;} .zh-logo{position:absolute;left:50%;top:0;margin:0 0 0 -60px;float:none;width:auto;} .zh-logo a{display:block;} .zh-logo img{width:120px;height:40px;display:block;} .heads_fix .zh-logo{} #head{position:fixed!important;left:0;top:0;right:0;z-index:99999;background:#fff;border-bottom:1px solid #ddd;} .zh-logo{height:40px;} .flowpay{margin-top:25%;} .flowpay dt{text-align:center;} .flowpay strong.price{font-size:40px;} .wxLogo{text-align:center;} .wxLogo img{} .flowpay dd{margin:0;padding:20px 0 10px 0;} .flowpay dd input{margin:0 auto;padding:0;width:90%;height:45px;line-height:45px;border:0;border-radius:4px;background:#0CBC0A;color:#fff;font-size:17px;display:block;-webkit-appearance:none;-moz-appearance:none;appearance:none;outline:none;} </style> </head> <body> <!--頭部開始--> <p class="flowpay"> <dl> <dt> <p class="wxLogo"><img src="/static/imghw/default1.png" data-src="__PUBLIC__/home/images/1479953699138120.png" class="lazy" alt=""></p> 本次訂單需支付:¥<strong class="price">{$res['order_amount']}</strong> 元 </dt> <dd> <input type="button" id="hhhhhh" onclick="callpay()" value="立即支付" /> </dd> </dl> </p> <!--尾結(jié)束--> </body> </html>
Then there are the class files:
The cacert is the certificate storage directory; the certificate is not necessarily needed;
vendor Just look for the folder in My Files.
The above is the Thinkphp integrated WeChat payment function introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!
For more articles related to Thinkphp integrating WeChat payment function, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)