PHP的微信支付接口使用方法講解
在開發(fā)之中經(jīng)常會(huì)使用到支付的功能,現(xiàn)在常用的兩種支付方式是支付寶和微信。相對(duì)而言,支付寶的文檔較為健全,并且配置和調(diào)用方式方式比較簡(jiǎn)單,這里就不過(guò)多的描述。
首先去微信官網(wǎng)網(wǎng)站下去下載服務(wù)端的demo:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=11_1
這里雖然是官網(wǎng)提供的公眾號(hào)支付的demo,雖然微信支付的預(yù)下單等都可以在前端進(jìn)行實(shí)現(xiàn),不過(guò)官方還是建議在服務(wù)端進(jìn)行處理。下載后,將其中的demo引入你的項(xiàng)目就好,注意的是如果是公眾號(hào)的支付用到的類文件WxPay.JsApiPay.php在文件中example目錄下。
接下來(lái)我們就可以進(jìn)行引用了并實(shí)現(xiàn)。以thinkphp框架下進(jìn)行調(diào)用為例(以下案例包括移動(dòng)端以及公眾號(hào)支付以及公眾號(hào)獲取openid等功能)。以下代碼為了能夠更容易理解,將一些類中的方法提取了出來(lái),寫的有點(diǎn)亂,請(qǐng)見諒。
/* 微信APP下支付預(yù)下單 */ public function wxAppOrder(){ //TODO:首先獲取訂單詳情,例如傳遞過(guò)來(lái)訂單號(hào)或訂單id,獲取訂單的詳情信息,例如將取出的數(shù)據(jù)存放入$user_order_info數(shù)組,訂單中包含的商品在$user_order_product_info之中。 /* 向微信發(fā)起請(qǐng)求 */ vendor('WxpayAPI.lib.WxPay','','.Api.php'); vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成數(shù)據(jù) //統(tǒng)一下單輸入對(duì)象 $order_info= new WxPayUnifiedOrder(); $order_info->SetOut_trade_no($user_order_info['orderNo']);//商品訂單號(hào) $body=$user_order_product_info['productName']; // $body=iconv('UTF-8', 'ISO-8859-1', $user_order_product_info['productName']); $order_info->SetBody($body);//商品描述 $order_info->SetTrade_type('CNY');//人民幣 $order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//總金額,以分為單位 $order_info->SetTrade_type('APP');//交易類型 $order_info->SetAppid(C('wxAPPID')); $order_info->SetMch_id(C('wxMCHID')); $order_info->SetNotify_url('你的回調(diào)地址'); $order_info->SetSign(); //進(jìn)行統(tǒng)一支付 $wxpay=new WxPayApi(); $order_result=$wxpay->unifiedOrder($order_info);//統(tǒng)一下單 if ($order_result['return_code']=='FAIL') { $arr=array( 'resultCode'=>'99', 'resultDesc'=>$order_result['return_msg'], 'resultObj'=>array(''=>''), ); echo JSON($arr); exit(); } if ($order_result['result_code']=='SUCCESS') { //預(yù)下單成功后,重新簽名返回給移動(dòng)端 $wxpay_result=new WxPayResults(); $timestamp=time(); $wxpay_result->SetData('appid', $order_result['appid']); $wxpay_result->SetData('partnerid', $order_result['mch_id']); $wxpay_result->SetData('prepayid', $order_result['prepay_id']); $wxpay_result->SetData('timestamp', $timestamp); $wxpay_result->SetData('noncestr', $order_result['nonce_str']); $wxpay_result->SetData('package', 'Sign=WXPay'); // $wxpay_result->SetData('key', C('wxKEY')); //上方注釋的代碼是再簽名中必要的一步,只是這個(gè)包含在了微信demo的類中,如果像該項(xiàng)目中既有app支付,又有公眾號(hào)支付,最好是注釋類中代碼,并自己寫入 $resign_result=$wxpay_result->SetSign(); //處理返回?cái)?shù)據(jù) $result=array( 'appid'=>$order_result['appid'],//appid 'partnerid'=>$order_result['mch_id'],//商戶號(hào) 'prepayid'=>$order_result['prepay_id'],//與支付id 'package'=>'Sign=WXPay', 'noncestr'=>$order_result['nonce_str'], 'timestamp'=>$timestamp, 'sign'=>$resign_result, ); $arr=array( 'resultCode'=>'00', 'resultDesc'=>'成功', 'resultObj'=>$result, ); echo JSON($arr); exit(); }else{ $arr=array( 'resultCode'=>'99', 'resultDesc'=>'失敗', 'resultObj'=>$order_result, ); echo JSON($arr); exit(); } } /* 微信支付回調(diào)函數(shù) */ public function wxpayNotify(){ vendor('WxpayAPI.lib.Logwx','','.Log.php');//在回調(diào)中最好是引入日志進(jìn)行記錄,在這里因?yàn)長(zhǎng)og類與thinkphp中的log類重復(fù),需要進(jìn)行處理 $handle=new CLogFileHandler('./Public/wxlog.txt'); $log=Logwx::Init($handle); $xml = $GLOBALS['HTTP_RAW_POST_DATA'];//獲取數(shù)據(jù) vendor('WxpayAPI.lib.WxPay','','.Api.php'); vendor('WxpayAPI.lib.WxPay','','.Data.php'); $wxpay=new WxPayApi(); $notify=new WxPayNotifyReply(); $result=WxPayResults::Init($xml);//獲取數(shù)據(jù)并轉(zhuǎn)換為數(shù)組 if ($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS') {//此字段是通信標(biāo)識(shí),非交易標(biāo)識(shí),交易是否成功需要查看result_code來(lái)判斷 //TODO:進(jìn)行數(shù)據(jù)庫(kù)操作的業(yè)務(wù)邏輯處理,假設(shè)其成功與否的數(shù)據(jù)為$res if ($res) { $log->INFO('訂單:'.$result['out_trade_no'].'支付成功'); $notify->SetReturn_code('SUCCESS'); $notify->SetReturn_msg('OK'); $notify->SetSign(); }else{ $log->ERROR('微信支付失敗'); $notify->SetReturn_code('FAIL'); $notify->SetReturn_msg('客戶服務(wù)器錯(cuò)誤'); } }else{ $log->ERROR('微信回調(diào)返回錯(cuò)誤'); $notify->SetReturn_code('FAIL'); $notify->SetReturn_msg('微信支付失敗'); } //返回微信端 $wxpay->replyNotify($notify->ToXml()); } /* 微信公眾賬號(hào)下單 * 獲取code等信息 * 跳轉(zhuǎn)至獲取信息 * */ public function wxPubOrder(){ //此流程中 $orderId=$_GET['orderId']; //注意:此處如果想要回調(diào)成功,需要在微信公眾平臺(tái)設(shè)置回調(diào)域名 // print_r('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.C('wxAPPID').'&redirect_uri='.'http://你的域名/Pay/getOpenid/orderId/'.$orderId.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect'); // exit(); header('Location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.'*******'.'&redirect_uri='.urlencode('http://*****/Pay/getOpenid/orderId/'.$orderId).'&response_type=code&scope=snsapi_base&state=123#wechat_redirect'); exit(); } /* 微信獲取openid,跳轉(zhuǎn)到微信同意下單接口 */ public function getOpenid(){ //code $code=$_GET['code']; $state=$_GET['state']; $orderId=$_GET['orderId']; $appid='******'; $appsecret='******'; //獲取openid $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code'; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$get_token_url); curl_setopt($ch,CURLOPT_HEADER,0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); $res = curl_exec($ch); curl_close($ch); $json_obj = json_decode($res,true); $openId=$json_obj['openid']; // 跳轉(zhuǎn)到預(yù)下單 // echo $openId;exit(); $url='http://******/html5/#/pay/'.$orderId.'openid='.$openId; header('Location:'.$url); } /* 微信公眾賬號(hào)統(tǒng)一下單 */ public function wxOrder(){ $orderId=$_GET['orderId']; $openId=$_GET['openId']; if (empty($orderId)||empty($openId)) { $arr=array( 'resultCode'=>'66', 'resultDesc'=>'缺少參數(shù)', 'resultObj'=>array(), ); echo JSON($arr); exit(); } //TODO:獲取訂單和訂單商品信息,分別存儲(chǔ)在$user_order_info中和$user_order_good_info中 if (empty($user_order_info)) { $arr=array( 'resultCode'=>'99', 'resultDesc'=>'不存在該訂單', 'resultObj'=>array(), ); echo JSON($arr); exit(); } /* 向微信發(fā)起請(qǐng)求 */ vendor('WxpayAPI.lib.WxPay','','.Api.php'); vendor('WxpayAPI.lib.WxPay','','.Data.php');//生成數(shù)據(jù) // vendor('WxpayAPI.lib.WxPay','','.JsApiPay.php'); //統(tǒng)一下單輸入對(duì)象 $order_info= new WxPayUnifiedOrder(); $wxpay=new WxPayApi(); $order_info->SetMch_id('***');//商戶號(hào) $order_info->SetAppid('****');//微信號(hào)APPID//wx70a40dfa2711c4fe $order_info->SetOut_trade_no($user_order_info['orderNo']);//商品訂單號(hào) $order_info->SetBody($user_order_good_info['productName']);//商品描述 $order_info->SetTrade_type('CNY');//人民幣 $order_info->SetTotal_fee(intval($user_order_info['sumPrice']*100));//總金額,以分為單位 $order_info->SetTrade_type('JSAPI');//交易類型 $order_info->SetNonce_str($wxpay->getNonceStr(32)); $order_info->SetSpbill_create_ip('1.1.1.1'); // $order_info->SetOpenid($user_info['openId']); $order_info->SetOpenid($openId); //TODO: $order_info->SetNotify_url('http://****/Pay/wxpayNotify'); $order_info->SetSign();//設(shè)置簽名 //進(jìn)行統(tǒng)一支付 $order_result=$wxpay->unifiedOrder($order_info);//統(tǒng)一下單 //同意下單后再加 if ($order_result['return_code']=='FAIL') { $arr=array( 'resultCode'=>'99', 'resultDesc'=>$order_result['return_code'].':'.$order_result['return_msg'], 'resultObj'=>array(), ); echo JSON($arr); exit(); } if ($order_result['result_code']=='SUCCESS') { $jsapi = new WxPayJsApiPay(); $jsapi->SetAppid($order_result["appid"]); $timeStamp = time(); $jsapi->SetTimeStamp("$timeStamp"); $jsapi->SetNonceStr(WxPayApi::getNonceStr()); $jsapi->SetPackage("prepay_id=" . $order_result['prepay_id']); $jsapi->SetSignType("MD5"); $jsapi->SetPaySign($jsapi->MakeSign()); $order_result = $jsapi->GetValues(); // print_r($order_result);exit(); $arr=array( 'resultCode'=>'00', 'resultDesc'=>'成功', 'resultObj'=>$order_result, ); echo JSON($arr); exit(); }else{ $arr=array( 'resultCode'=>'99', 'resultDesc'=>'失敗', 'resultObj'=>$order_result, ); echo JSON($arr); exit(); } }
這就是一個(gè)支付的流程,在這之中會(huì)遇到很多問(wèn)題,在此給出一個(gè)大多數(shù)會(huì)遇到的問(wèn)題的解決方法的大概思路:
- 1、APP統(tǒng)一下單后數(shù)據(jù)返回給前端,前端調(diào)用報(bào)簽名錯(cuò)誤:首先驗(yàn)證自己的秘鑰信息是否正確,要注意移動(dòng)端和公眾號(hào)的是不同的,而類拿著key又去重新簽名,可以將微信官方提供的demo中的直接內(nèi)部調(diào)用配置文件那里注釋掉
- 2、在公眾號(hào)獲取openid的時(shí)候,顯示跨域:這個(gè)解決參考YII2框架中對(duì)于\yii::$app->response->header,中的remove方法,將報(bào)頭去掉即可。
- 3、對(duì)于微信支付的配置,包括公眾號(hào)支付配置白名單、測(cè)試目錄啥的就不過(guò)多說(shuō)了,請(qǐng)自行搜索資料
過(guò)程中肯定還遇到很多問(wèn)題,這里不一一寫了,如果還有問(wèn)題可以在評(píng)論中留言,大家一起討論學(xué)習(xí),共同進(jìn)步。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
Function eregi is deprecated (解決方法)
本篇文章是對(duì)Function eregi() is deprecated錯(cuò)誤的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06php實(shí)現(xiàn)的統(tǒng)計(jì)字?jǐn)?shù)函數(shù)定義與使用示例
這篇文章主要介紹了php實(shí)現(xiàn)的統(tǒng)計(jì)字?jǐn)?shù)函數(shù)定義與使用方法,結(jié)合實(shí)例形式分析了php針對(duì)字符串的統(tǒng)計(jì)運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-07-07php讀取二進(jìn)制流(C語(yǔ)言結(jié)構(gòu)體struct數(shù)據(jù)文件)的深入解析
本篇文章是對(duì)php讀取二進(jìn)制流(C語(yǔ)言結(jié)構(gòu)體struct數(shù)據(jù)文件)進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP字符串逆序排列實(shí)現(xiàn)方法小結(jié)【strrev函數(shù),二分法,循環(huán)法,遞歸法】
這篇文章主要介紹了PHP字符串逆序排列實(shí)現(xiàn)方法,結(jié)合實(shí)例形式總結(jié)分析了strrev函數(shù),二分法,循環(huán)法,遞歸法等常用的字符串逆序排列操作實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-01-01使用php將某個(gè)目錄下面的所有文件羅列出來(lái)的方法詳解
本篇文章是對(duì)使用php將某個(gè)目錄下面的所有文件羅列出來(lái)的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06php中通過(guò)eval實(shí)現(xiàn)字符串格式的計(jì)算公式
有時(shí)候我們對(duì)每一種產(chǎn)品都有一個(gè)提成公式,而這個(gè)計(jì)算提成的公式是以字符串格式存在表中的,當(dāng)我們用這個(gè)計(jì)算公式時(shí),他并不像我們寫的:$a=2+3*5;這樣簡(jiǎn)單的能計(jì)算出結(jié)果,而它是個(gè)字符串,所以,我們就必須把字符串轉(zhuǎn)化為我們能夠處理的結(jié)果2017-03-03使用PHPMailer實(shí)現(xiàn)郵件的實(shí)時(shí)發(fā)送功能
這篇文章主要為大家詳細(xì)介紹了如何使用PHPMailer 實(shí)現(xiàn)一個(gè)接收詢盤并實(shí)時(shí)同步到指定郵箱的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以了解一下2023-12-12