Thinkphp整合微信支付功能
先上效果圖:我要告訴你我這一篇文章寫的是微信支付之中的(普通商戶而非服務(wù)商商戶的統(tǒng)一下單JSPI)微信支付:





其實(shí)自己整合SDK失敗了,用了一個(gè)博客博主整合的代碼,在這里寫一下筆記:
前面準(zhǔn)備:
1、微信公眾號(hào):
獨(dú)特的appid、appscrect、接口權(quán)限之中設(shè)置可以獲取用戶ID信息權(quán)限的域名(每個(gè)用戶對(duì)于不同公眾都會(huì)有一個(gè)特有ID,通過這個(gè)ID獲取用戶微信賬號(hào)基本信息、詳情看微信開發(fā)者文檔)、在微信支付按鈕出設(shè)置微信支付授權(quán)目錄(寫到發(fā)起請(qǐng)求的控制器那一層)、設(shè)置開發(fā)者微信賬號(hào)為測(cè)試白名單(用微信開發(fā)者工具的時(shí)候需要)
2、微信支付平臺(tái):
商戶平臺(tái)登陸賬號(hào)、支付密鑰(隨時(shí)可以自行設(shè)置,只能有一個(gè))、
3、整合進(jìn)去thinkphp之中邏輯:
前端微信支付按鈕設(shè)置點(diǎn)擊調(diào)用支付發(fā)起控制器方法、
控制器運(yùn)行,引用微信支付類、獲取用戶openid、獲取訂單數(shù)據(jù)、拼接出所有普通商戶預(yù)支付jsp需要的數(shù)據(jù),display出那個(gè)自定義的支付頁(yè)面、
在支付頁(yè)面點(diǎn)擊支付、調(diào)用微信提供的jspi發(fā)起支付的scripet函數(shù)發(fā)起支付、
支付完成以后頁(yè)面會(huì)重定向到(在自定義支付頁(yè)面的script函數(shù)里設(shè)置的跳轉(zhuǎn)目錄{:U('controller/function)}),并且異步(靜默)設(shè)置的異步處理訂單邏輯(記錄支付時(shí)間啦、標(biāo)記為已經(jīng)支付啦、標(biāo)記是微信支付啦)之類的、
代碼:
我的訂單頁(yè)面的微信支付按鈕:
<a href="{:U('Wxpay/js_api_start',array('order_key_num'=>$v['order_key_num]))}"> 微信支付</a>
發(fā)起支付控制器Wxpay:
<?php
namespace Home\Controller;
use Think\Controller;
//微信支付類
class WxpayController extends Controller {
//獲取access_token過程中的跳轉(zhuǎn)uri,通過跳轉(zhuǎn)將code傳入jsapi支付頁(yè)面
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)頁(yè)授權(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", '商品采購(gòu)');//商品描述
//自定義訂單號(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;
}
}
?>
發(fā)起支付后拼接預(yù)支付數(shù)據(jù)參數(shù)(參數(shù)列表看微信普通商戶開發(fā)者文檔——微信支付——統(tǒng)一下單)display的頁(yè)面:
<!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>
<!--頭部開始-->
<div class="flowpay">
<dl>
<dt>
<p class="wxLogo"><img src="__PUBLIC__/home/images/1479953699138120.png" alt=""></p>
本次訂單需支付:¥<strong class="price">{$res['order_amount']}</strong> 元
</dt>
<dd>
<input type="button" id="hhhhhh" onclick="callpay()" value="立即支付" />
</dd>
</dl>
</div>
<!--尾結(jié)束-->
</body>
</html>
然后就是類文件啦:

那個(gè)cacert是證書存放目錄;證書不一定需要的;
vendor文件夾在我的文件里面找找就可以。
以上所述是小編給大家介紹的Thinkphp整合微信支付功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
ThinkPHP框架實(shí)現(xiàn)定時(shí)執(zhí)行任務(wù)的兩種方法分析
這篇文章主要介紹了ThinkPHP框架實(shí)現(xiàn)定時(shí)執(zhí)行任務(wù)的兩種方法,結(jié)合實(shí)例形式分析了2種被動(dòng)執(zhí)行定時(shí)任務(wù)的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-09-09
Laravel中重寫資源路由自定義URL的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于Laravel中重寫資源路由自定義URL的實(shí)現(xiàn)方法,需要的朋友可以參考下2017-08-08
Laravel框架實(shí)現(xiàn)利用監(jiān)聽器進(jìn)行sql語句記錄功能
這篇文章主要介紹了Laravel框架實(shí)現(xiàn)利用監(jiān)聽器進(jìn)行sql語句記錄功能,結(jié)合實(shí)例形式分析了Laravel框架監(jiān)聽器的創(chuàng)建、引入以及使用監(jiān)聽器記錄sql語句的相關(guān)操作技巧,需要的朋友可以參考下2018-06-06
php的sprintf函數(shù)的用法 控制浮點(diǎn)數(shù)格式
這篇文章主要介紹了php的sprintf函數(shù)的用法,需要的朋友可以參考下2014-02-02
destoon實(shí)現(xiàn)調(diào)用自增數(shù)字從1開始的方法
這篇文章主要介紹了destoon實(shí)現(xiàn)調(diào)用自增數(shù)字從1開始的方法,很有實(shí)用價(jià)值的一個(gè)技巧,需要的朋友可以參考下2014-08-08
thinkPHP5使用Rabc實(shí)現(xiàn)權(quán)限管理
這篇文章主要介紹了thinkPHP5使用Rabc實(shí)現(xiàn)權(quán)限管理功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08

