PHP實現微信提現功能

提現必須得用雙向證書、因此你們必定要在微信的商戶平臺找到相應的地方去設置、由於作這個提現已經有一段時間了、因此設置微信商戶平臺的那幾個地方沒有圖的狀況、也說不清楚、下次再作提現的時候、給你們分享如何設置商戶平臺那幾個地方、不是很難、下面貼代碼php

注意事項:商戶打款時是從商戶可用餘額中減錢,因此確保商戶可用餘額充足,同時注意官方文檔中的付款規則;html

 

封裝提現的方法web

 1 function tixian($money){
 2     $appid = "################";//商戶帳號appid
 3     $secret = "##########";//api密碼
 4     $mch_id = "#######";//商戶號
 5     $mch_no = "#######";
 6     $openid="123456789";//受權用戶openid
 7 
 8     $arr = array();
 9     $arr['mch_appid'] = $appid;
10     $arr['mchid'] = $mch_id;
11     $arr['nonce_str'] = ugv::randomid(20);//隨機字符串,不長於32位
12     $arr['partner_trade_no'] = '1298016501' . date("Ymd") . rand(10000, 90000) . rand(10000, 90000);//商戶訂單號
13     $arr['openid'] = $openid;
14     $arr['check_name'] = 'NO_CHECK';//是否驗證用戶真實姓名,這裏不驗證
15     $arr['amount'] = $money;//付款金額,單位爲分
16     $desc = "###提現";
17     $arr['desc'] = $desc;//描述信息
18     $arr['spbill_create_ip'] = '192.168.0.1';//獲取服務器的ip
19     //封裝的關於簽名的算法
20     $notify = new Notify_pub();
21     $notify->weixin_app_config = array();
22     $notify->weixin_app_config['KEY'] = $mch_no;
23 
24     $arr['sign'] = $notify->getSign($arr);//簽名
25 
26     $var = $notify->arrayToXml($arr);
27     $xml = $this->curl_post_ssl('https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers', $var, 30, array(), 1);
28     $rdata = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
29     $return_code = (string)$rdata->return_code;
30     $result_code = (string)$rdata->result_code;
31     $return_code = trim(strtoupper($return_code));
32     $result_code = trim(strtoupper($result_code));
33 
34     if ($return_code == 'SUCCESS' && $result_code == 'SUCCESS') {
35       $isrr = array(
36         'con'=>'ok',
37         'error' => 0,
38       );
39     } else {
40       $returnmsg = (string)$rdata->return_msg;
41       $isrr = array(
42         'error' => 1,
43         'errmsg' => $returnmsg,
44       );
45 
46     }
47     return json_encode($isrr);
48 } 

 

 

用到的curl_post_ssl()算法

 1 function curl_post_ssl($url, $vars, $second = 30, $aHeader = array())
 2   {
 3     $isdir = "/cert/";//證書位置
 4 
 5     $ch = curl_init();//初始化curl
 6 
 7     curl_setopt($ch, CURLOPT_TIMEOUT, $second);//設置執行最長秒數
 8     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果爲字符串且輸出到屏幕上
 9     curl_setopt($ch, CURLOPT_URL, $url);//抓取指定網頁
10     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// 終止從服務端進行驗證
11     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//
12     curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');//證書類型
13     curl_setopt($ch, CURLOPT_SSLCERT, $isdir . 'apiclient_cert.pem');//證書位置
14     curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');//CURLOPT_SSLKEY中規定的私鑰的加密類型
15     curl_setopt($ch, CURLOPT_SSLKEY, $isdir . 'apiclient_key.pem');//證書位置
16     curl_setopt($ch, CURLOPT_CAINFO, 'PEM');
17     curl_setopt($ch, CURLOPT_CAINFO, $isdir . 'rootca.pem');
18     if (count($aHeader) >= 1) {
19       curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);//設置頭部
20     }
21     curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
22     curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);//所有數據使用HTTP協議中的"POST"操做來發送
23 
24     $data = curl_exec($ch);//執行回話
25     if ($data) {
26       curl_close($ch);
27       return $data;
28     } else {
29       $error = curl_errno($ch);
30       echo "call faild, errorCode:$error\n";
31       curl_close($ch);
32       return false;
33     }
34 }

 

關於具體簽名算法,可參考微信官方文檔;json

簡單示範簽名算法:api

 1 //將要發送的數據整理爲$data
 2 
 3 ksort($data);//排序
 4 //使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字符串
 5 $str='';
 6 foreach($data as $k=>$v) {
 7   $str.=$k.'='.$v.'&';
 8 }
 9 //拼接API密鑰
10 $str.='key='.$secrect;
11 $data['sign']=md5($str);//加密

 

 

將數組轉換成xml格式(簡單方法):數組

1 //遍歷數組方法
2 function arraytoxml($data){
3   $str='<xml>';
4   foreach($data as $k=>$v) {
5     $str.='<'.$k.'>'.$v.'</'.$k.'>';
6   }
7   $str.='</xml>';
8   return $str;
9 }

 

 

將xml格式轉換爲數組:服務器

1 function xmltoarray($xml) { 
2    //禁止引用外部xml實體 
3   libxml_disable_entity_loader(true); 
4   $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
5   $val = json_decode(json_encode($xmlstring),true); 
6   return $val;
7 }
8  

 

 

下面來看看ThinkPHP5封裝的提現類。微信

  1 <?php
  2 namespace Home\Controller;
  3 use Think\Controller;
  4 class TixianController extends Controller{
  5 
  6   //高級功能-》開發者模式-》獲取
  7   private $app_id1 = '';   //appid
  8   private $app_secret1 = ''; //secreat
  9   private $apikey1 = ''; //支付祕鑰
 10   private $mchid1 = 's';    //商戶號
 11 
 12     private $app_id=null;
 13     private $app_secret=null;
 14     private $apikey=null;
 15     private $mchid=null;
 16 
 17 
 18   public $error=0;
 19   public $state = '';
 20   //金額,需在實例化時傳入
 21   public $amount = '0';
 22   //用戶訂單號,需在實例化時傳入
 23   public $order_sn = '';
 24   //用戶openid,需在實例化時傳入
 25   public $openid = '';
 26 
 27 
 28 
 29   //微信提現操做接口-------》
 30   public function actionAct_tixian()
 31   {
 32 
 33    $this->state=md5(uniqid(rand(), TRUE));
 34    $this->amount=I('amount');//設置POST過來錢數
 35    $this->order_sn=rand(100,999).date('YmdHis'); //隨機數能夠做爲單號
 36    $this->openid= I('openid'); //設置獲取POST過來用戶的OPENID
 37     $user_id = I('user_id');
 38 
 39    $this->app_id=$this->app_id1;
 40    $this->app_secret=$this->app_secret1;
 41    $this->apikey=$this->apikey1;
 42    $this->mchid=$this->mchid1;
 43    $xml=$this->tiXianAction();
 44    $result=simplexml_load_string($xml);
 45 
 46    if($result->return_code=='SUCCESS' && $result->result_code=='SUCCESS') {
 47 
 48         $cash = D('cash');
 49         $data['user_id'] = $user_id;
 50         $data['amount'] = $this->amount;
 51         $res = $cash->where('user_id="'.$user_id.'"')->find();
 52         if($res){
 53           $res2 = $cash->where('user_id="'.$user_id.'"')->setInc('amount',$this->amount);
 54           $res4 = D('member')->where('user_id="'.$user_id.'"')->setDec('user_balance',$this->amount);
 55         }else{
 56           $res3 = $cash->add($data);
 57         }
 58 
 59       $output = array('code' => 1, 'data' => $result->result_code, 'info' => '提現成功');
 60       exit(json_encode($output));
 61    }else{
 62 
 63       $output = array('code' => 2, 'data' => $xml, 'info' => '提現失敗');
 64       exit(json_encode($output));
 65    }
 66   }
 67   /**
 68   * 提現接口操做,控制器調用
 69   * @param $openid 用戶openid 惟一標示
 70   * @return
 71   */
 72   //提現接口操做
 73   public function tiXianAction(){
 74    //獲取xml數據
 75    $data=$this->getdataXml($this->openid);
 76    $ch = curl_init ();
 77    //接口地址
 78    $MENU_URL="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
 79 
 80    curl_setopt ( $ch, CURLOPT_URL, $MENU_URL );
 81    curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
 82    curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
 83    curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
 84 
 85    //證書地址,微信支付下面
 86 
 87     curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
 88     curl_setopt($ch,CURLOPT_SSLCERT, 'C:\web\www\Home\wx_pay\apiclient_cert.pem'); //證書這塊你們把文件放到哪都行、
 89     curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
 90     curl_setopt($ch,CURLOPT_SSLKEY, 'C:\web\www\Home\wx_pay\apiclient_key.pem');//注意證書名字千萬別寫錯、
 91 
 92    //$zs1=dirname(dirname(__FILE__)).'\wx_pay\apiclient_cert.pem';
 93    //$zs2=dirname(dirname(__FILE__)).'\wx_pay\apiclient_key.pem';
 94    //show_bug($zs1);
 95 
 96    //curl_setopt($ch,CURLOPT_SSLCERT,$zs1);
 97    //curl_setopt($ch,CURLOPT_SSLKEY,$zs2);
 98    // curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01;
 99    // Windows NT 5.0)');
100    //curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
101    curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 );
102    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
103    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
104    $info = curl_exec ( $ch );
105     //返回結果
106     if($info){
107       curl_close($ch);
108       return $info;
109     } else {
110       $error = curl_errno($ch);
111       curl_close($ch);
112       return "curl出錯,錯誤碼:$error";
113     }
114   }
115   /**
116   * 獲取數據封裝爲數組
117   * @param $openid 用戶openid 惟一標示
118   * @return xml
119   */
120 
121   private function getdataXml($openid){
122    //封裝成數據
123    $dataArr=array(
124      'amount'=>$this->amount*100,//金額(以分爲單位,必須大於100)
125      'check_name'=>'NO_CHECK',//校驗用戶姓名選項,NO_CHECK:不校驗真實姓名 FORCE_CHECK:強校驗真實姓名(未實名認證的用戶會校驗失敗,沒法轉帳)OPTION_CHECK:針對已實名認證的用戶才校驗真實姓名(未實名認證用戶不校驗,能夠轉帳成功)
126      'desc'=>'提現',//描述
127      'mch_appid'=>$this->app_id,
128      'mchid'=>$this->mchid,//商戶號
129      'nonce_str'=>rand(100000, 999999),//不長於32位的隨機數
130      'openid'=>$openid,//用戶惟一標識
131      'partner_trade_no'=>$this->order_sn,//商戶訂單號
132      're_user_name'=>'',//用戶姓名,check_name爲NO_CHECK時爲可選項
133      'spbill_create_ip'=>$_SERVER["REMOTE_ADDR"],//服務器ip
134    );
135    //獲取簽名
136    $sign=$this->getSign($dataArr);
137    //xml數據
138    $data="<xml>
139      <mch_appid>".$dataArr['mch_appid']."</mch_appid>
140      <mchid>".$dataArr['mchid']."</mchid>
141      <nonce_str>".$dataArr['nonce_str']."</nonce_str>
142      <partner_trade_no>".$dataArr['partner_trade_no']."</partner_trade_no>
143      <openid>".$dataArr['openid']."</openid>
144      <check_name>".$dataArr['check_name']."</check_name>
145      <re_user_name>".$dataArr['re_user_name']."</re_user_name>
146      <amount>".$dataArr['amount']."</amount>
147      <desc>".$dataArr['desc']."</desc>
148      <spbill_create_ip>".$dataArr['spbill_create_ip']."</spbill_create_ip>
149      <sign>".$sign."</sign>
150      </xml>";
151    return $data;
152 
153   }
154   /**
155   *   做用:格式化參數,簽名過程須要使用
156   */
157   private function formatBizQueryParaMap($paraMap, $urlencode)
158   {
159 
160    $buff = "";
161    ksort($paraMap);
162    foreach ($paraMap as $k => $v)
163    {
164      if($v){
165       if($urlencode)
166       {
167         $v = urlencode($v);
168       }
169 
170       $buff .= $k . "=" . $v . "&";
171      }
172 
173    }
174    $reqPar=NULL;
175    if (strlen($buff) > 0)
176    {
177      $reqPar = substr($buff, 0, strlen($buff)-1);
178    }
179 
180    return $reqPar;
181   }
182 
183   /**
184   *   做用:生成簽名
185   */
186   private function getSign($Obj)
187   {
188 
189    foreach ($Obj as $k => $v)
190    {
191      $Parameters[$k] = $v;
192    }
193    //簽名步驟一:按字典序排序參數
194    ksort($Parameters);
195    $String = $this->formatBizQueryParaMap($Parameters, false);
196    //echo '【string1】'.$String.'</br>';
197    //簽名步驟二:在string後加入KEY
198    $String = $String."&key=".$this->apikey;
199    //echo "【string2】".$String."</br>";
200    //簽名步驟三:MD5加密
201    $String = md5($String);
202    //echo "【string3】 ".$String."</br>";
203    //簽名步驟四:全部字符轉爲大寫
204    $result_ = strtoupper($String);
205    //echo "【result】 ".$result_."</br>";
206    return $result_;
207   }
208   //-----------
209   private function http($url, $method='POST', $postfields = null, $headers = array())
210   {
211    header("Content-Type:text/html;charset=utf-8");
212    $ch = curl_init();
213    /* Curl settings */
214    curl_setopt($ch, CURLOPT_URL, $url);
215    curl_setopt($ch, CURLOPT_POSTFIELDS, "");
216    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
217    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https請求 不驗證證書和hosts
218    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
219    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
220    switch ($method){
221      case 'POST':
222       curl_setopt($ch,CURLOPT_POST, true);
223       break;
224    }
225    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
226    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
227    $response = curl_exec($ch);
228    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //返回請求狀態碼
229    curl_close($ch);
230    return array($http_code, $response);
231   }
232 
233 }
相關文章
相關標籤/搜索