微信開發系列----企業付款到銀行卡介面開發
阿新 • • 發佈:2018-12-10
一、微信商戶號須開通此功能;
二、應用環境TP5+Mysql+Centos三、編寫程式碼3.1、Model層,Wechat.php
<?php namespace app\home\model; use think\Cache; class Wechat extends Model { private $appid; //公眾號APPID private $appsecret; //公眾號appsecret private $mchid; //商戶號 private $key; //支付金鑰 private $sslcert; //證書儲存的絕對路徑 private $sslkey; //證書儲存的絕對路徑 public function __construct($appid,$appsecret,$mchid,$key,$sslcert,$sslkey) { parent::__construct(); $this->appid = $appid; $this->appsecret = $appsecret; $this->mchid = $mchid; $this->key = $key; $this->sslcert = $sslcert; $this->sslkey = $sslkey; } /* * 企業付款到銀行卡介面 * @params string $out_trade_no : 商戶訂單號 * @params int $amount : 付款金額,單位分 * @params string $enc_bank_no : 收款方銀行卡號 * @params string $enc_true_name : 收款方使用者名稱 * @params string $bank_name : 收款方開戶行,根據銀行名稱獲取銀行編號bank_code * @params string $desc : 付款備註 * return string $payment_no :支付成功的訂單號 */ public function payForBank($out_trade_no,$amount,$enc_bank_no,$enc_true_name,$bank_name,$desc='企業付款到銀行卡') { $data['amount'] = $amount; $data['bank_code'] = $this->getBankCode($bank_code); $data['desc'] = $desc; $data['enc_bank_no'] = $this->publicEncrypt($enc_bank_no); $data['enc_true_name'] = $this->publicEncrypt($enc_true_name); $data['mch_id'] = $this->mchid; $data['nonce_str'] = $this->random(12); $data['partner_trade_no'] = $out_trade_no; $sign = $this->getParam($data); $dataXML="<xml> <amount>".$data['amount']."</amount> <bank_code>".$data['bank_code']."</bank_code> <desc>".$data['desc']."</desc> <enc_bank_no>".$data['enc_bank_no']."</enc_bank_no> <enc_true_name>".$data['enc_true_name']."</enc_true_name> <mch_id>".$data['mch_id']."</mch_id> <nonce_str>".$data['nonce_str']."</nonce_str> <partner_trade_no>".$data['partner_trade_no']."</partner_trade_no> <sign>".$sign."</sign> </xml>"; $url = 'https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank'; $ret = $this->httpsPost($url,$dataXML,true); if($ret['return_code'] == 'SUCCESS' && $ret['result_code'] == 'SUCCESS' && $ret['err_code'] == 'SUCCESS'){ return $ret['payment_no']; }else{ $this->errorLog('微信付款到銀行卡失敗,appid:'.$this->appid,$ret); return false; } } /* * 查詢付款到銀行卡狀態 * @params string $out_trade_no : 商戶訂單號 * return array $ret:查詢狀態 * */ public function queryBank($out_trade_no) { $data['mch_id'] = $this->mchid; $data['nonce_str'] = $this->random(12); $data['partner_trade_no'] = $out_trade_no; $sign = $this->getParam($data); $dataXML="<xml> <mch_id>".$data['mch_id']."</mch_id> <nonce_str>".$data['nonce_str']."</nonce_str> <partner_trade_no>".$data['partner_trade_no']."</partner_trade_no> <sign>".$sign."</sign> </xml>"; $url = 'https://api.mch.weixin.qq.com/mmpaysptrans/query_bank'; $ret = $this->httpsPost($url,$dataXML,true); if($ret['return_code'] == 'SUCCESS' && $ret['result_code'] == 'SUCCESS' && $ret['err_code'] == 'SUCCESS'){ return $ret; }else{ $this->errorLog('查詢微信付款到銀行卡失敗,appid:'.$this->appid.',訂單號:'.$out_trade_no,$ret); return false; } } /* * 銀行編號列表,詳情參考:https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=24_4 * @params string $bank_name : 銀行名稱,4個漢字 * return int $bank_code : 銀行編碼 * */ private function getBankCode($bank_name) { $bank_code = 0; switch ($bank_name){ case '工商銀行': $bank_code = 1002; break; case '農業銀行': $bank_code = 1005; break; case '中國銀行': $bank_code = 1026; break; case '建設銀行': $bank_code = 1003; break; case '招商銀行': $bank_code = 1001; break; case '郵儲銀行': $bank_code = 1066; break; case '交通銀行': $bank_code = 1020; break; case '浦發銀行': $bank_code = 1004; break; case '民生銀行': $bank_code = 1006; break; case '興業銀行': $bank_code = 1009; break; case '平安銀行': $bank_code = 1010; break; case '中信銀行': $bank_code = 1021; break; case '華夏銀行': $bank_code = 1025; break; case '廣發銀行': $bank_code = 1027; break; case '光大銀行': $bank_code = 1022; break; case '北京銀行': $bank_code = 1032; break; case '寧波銀行': $bank_code = 1056; break; } return $bank_code; } /** * 公鑰加密,銀行卡號和姓名需要RSA演算法加密 * @param string $data 需要加密的字串,銀行卡/姓名 * @return null|string 加密後的字串 */ private function publicEncrypt($data) { // 進行加密 $pubkey = openssl_pkey_get_public(file_get_contents(ROOT_PATH.'data/cert/public_pkcs8.pem')); $encrypt_data = ''; $encrypted = ''; $r = openssl_public_encrypt($data,$encrypt_data,$pubkey,OPENSSL_PKCS1_OAEP_PADDING); if($r){//加密成功,返回base64編碼的字串 return base64_encode($encrypted.$encrypt_data); }else{ return false; } } /* * 獲取公鑰,格式為PKCS#1 轉PKCS#8 * openssl rsa -RSAPublicKey_in -in <filename> -out <out_put_filename> * */ private function get_pub_key() { $rsafile = ROOT_PATH.'data/cert/'.$this->appid.'_publicrsa.pem'; if(!is_file($rsafile)){ $data['mch_id'] = $this->mchid; $data['nonce_str'] = $this->random(12); $sign = $this->getParam($data); $dataXML="<xml> <mch_id>".$data['mch_id']."</mch_id> <nonce_str>".$data['nonce_str']."</nonce_str> <sign>".$sign."</sign> </xml>"; $url = 'https://fraud.mch.weixin.qq.com/risk/getpublickey'; $ret = $this->httpsPost($url,$dataXML,true); if($ret['return_code'] == 'SUCCESS' && isset($ret['pub_key'])){ file_put_contents($rsafile,$ret['pub_key']); return $ret['pub_key']; }else{ return null; } }else{ return file_get_contents($rsafile); } } /* * 發起POST網路請求 * @params string $url : 請求的url連結地址 * @params string $data : 資料包 * @params bool $ssl : 是否載入證書 * return array $result : 返回的資料結果 */ private function httpsPost($url,$data,$ssl = false) { $ch = curl_init (); curl_setopt ( $ch, CURLOPT_URL, $url ); curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, "POST" ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE ); curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE ); if($ssl) { curl_setopt ( $ch,CURLOPT_SSLCERT,$this->sslcert); curl_setopt ( $ch,CURLOPT_SSLKEY,$this->sslkey); } curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 ); curl_setopt ( $ch, CURLOPT_AUTOREFERER, 1 ); curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data ); curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true ); $result = curl_exec($ch); if (curl_errno($ch)) { return 'Errno: '.curl_error($ch); } curl_close($ch); return $this->xmlToArray($result); } //對引數排序,生成MD5加密簽名 private function getParam($paramArray, $isencode=false) { $paramStr = ''; ksort($paramArray); $i = 0; foreach ($paramArray as $key => $value) { if ($key == 'Signature'){ continue; } if ($i == 0){ $paramStr .= ''; }else{ $paramStr .= '&'; } $paramStr .= $key . '=' . ($isencode?urlencode($value):$value); ++$i; } $stringSignTemp=$paramStr."&key=".$this->key; $sign=strtoupper(md5($stringSignTemp)); return $sign; } /* * 將xml轉換成陣列 * @params xml $xml : xml資料 * return array $data : 返回陣列 */ private function xmlToArray($xml) { //禁止引用外部xml實體 libxml_disable_entity_loader(true); $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); $val = json_decode(json_encode($xmlstring),true); return $val; } /* * 隨機字串 * @param int $length 長度 * @param string $type 型別 * @param int $convert 轉換大小寫 1大寫 0小寫 * @return string */ private function random($length=10,$type='letter',$convert=false) { $config = array( 'number'=>'1234567890', 'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789', 'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' ); if(!isset($config[$type])) $type = 'letter'; $string = $config[$type]; $code = ''; $strlen = strlen($string) -1; for($i = 0; $i < $length; $i++){ $code .= $string{mt_rand(0, $strlen)}; } if(!empty($convert)){ $code = ($convert > 0)? strtoupper($code) : strtolower($code); } return $code; } /* * 日誌記錄 * @params string $msg : 文字描述 * @params array $ret : 呼叫介面返回的陣列 */ private function errorLog($msg,$ret) { $path = ROOT_PATH.'runtime/error/'; if(!is_dir($path)) mkdir($path,0777); file_put_contents(ROOT_PATH . 'runtime/error/wxpay.log', "[" . date('Y-m-d H:i:s') . "] ".$msg."," .json_encode($ret).PHP_EOL, FILE_APPEND); } }
3.2、Controller控制層呼叫,Wxpay.php
<?php namespace app\home\controller; use app\home\model\Wechat; class Wxpay extends Controller { //企業付款到銀行卡 public function payBank() { $appid = 'wx****d4'; $appsecret = '37***f0'; $mchid = '13***2'; $key = '53***e8'; $sslcert = ROOT_PATH.'data/cert/apiclient_cert.pem'; $sslkey = ROOT_PATH.'data/cert/apiclient_key.pem'; $out_trade_no = date('Ymdhis', time()).substr(floor(microtime()*1000),0,1).rand(0,9); $money = 100; $enc_bank_no = '62***44'; $enc_true_name = '張**'; $bank_name = '中國銀行'; $desc = '企業付款到銀行卡測試'; $wxapi = new Wechat($appid,$appsecret,$mchid,$key,$sslcert,$sslkey); $payment_no = $wxapi->payForBank($out_trade_no,$money,$enc_bank_no,$enc_true_name,$bank_name,$desc); if($payment_no){ echo '微信付款到銀行卡操作成功,微信訂單號:'.$payment_no; } else { echo '微信付款到銀行卡操作失敗,請檢查日記'; } } }
四、付款截圖
五、注意事項1、獲取的rsa為PKCS1格式需要轉成PKCS8,需要執行以下命令$filename : 從微信伺服器上獲取的公鑰陣列$out_put_filename :轉換成PKCS8後的檔案儲存路徑openssl rsa -RSAPublicKey_in -in <filename> -out <out_put_filename>