您好,登錄后才能下訂單哦!
利用php怎么實現一個微信企業轉賬功能?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
具體內容如下
<?php /** * 配置賬號信息 * 配置要和證書在一起!!!! */ class WxTransfersConfig { //=======【基本信息設置】============== // /** * TODO: 修改這里配置為您自己申請的商戶信息 * 微信公眾號信息配置 * * APPID:綁定支付的APPID(必須配置,開戶郵件中可查看) * * MCHID:商戶號(必須配置,開戶郵件中可查看) * * KEY:商戶支付密鑰,參考開戶郵件設置(必須配置,登錄商戶平臺自行設置) * 設置地址:https://pay.weixin.qq.com/index.php/account/api_cert * */ const APPID = ''; const MCHID = ''; const KEY = ''; //=======【證書路徑設置】===================================== /** * TODO:設置商戶證書路徑 * 證書路徑,注意應該填寫絕對路徑,發送紅包和查詢需要,可登錄商戶平臺下載 * API證書下載地址:https://pay.weixin.qq.com/index.php/account/api_cert,下載之前需要安裝商戶操作證書) * @var path 跟這個文件同一目錄下的cert文件夾放置證書!!!! */ const SSLCRET12 = 'cert/apiclient_cert.p12'; const SSLCERT_PATH = 'cert/apiclient_cert.pem'; const SSLKEY_PATH = 'cert/apiclient_key.pem'; const SSLROOTCA = 'cert/rootca.pem'; //=======【證書路徑設置】===================================== /** * 獲取文件的路徑,證書需要完整路徑 * @return string */ public static function getRealPath(){ return __DIR__.'/'; } }
微信企業轉賬工具類:
<?php require_once "WxTransfers.Config.php"; /** * 微信企業轉賬工具類 */ class WxTransfers { // 企業轉賬請求地址 const TRANSFERS_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers'; //獲取轉賬信息地址 const GETINFO_URL='https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo'; // 轉賬需要的配置 'wxappid','mch_id','key' private $_keys; // 轉賬需要的證書文件 'api_cert', 'api_key', 'rootca',請傳入絕對路徑!!! private $_cert; protected $log_file; public $error; // 相關配置必備參數 protected $_parameters = array(); // 最后一次生產的訂單號 protected $_lastPartnerTradeNo; // 記錄最后一次發送請求的結果對象 protected $_lastResult; // 最后一次隨機數 protected $_lastRandNum; public function __construct($config) { $keys = array( 'wxappid', 'mch_id', 'key' ); $files = array( 'api_cert', 'api_key', 'rootca' ); foreach ($keys as $key) { try { $this->_keys[$key] = $config[$key]; } catch (Exception $e) { throw new Exception('參數缺失:' . $key); } } foreach ($files as $file) { try { $cret_file = $config[$file]; if (is_file($cret_file)) { $this->_cert[$file] = $cret_file; } } catch (Exception $e) { throw new Exception('證書錯誤'); } } } public function transfers($parameters){ $this->log($parameters, 'SEND_PARAM'); $this->setParameter('mchid', $this->_keys['mch_id']); $this->setParameter('mch_appid', $this->_keys['wxappid']); $must = array( 'openid', 'check_name', 're_user_name', 'amount', 'desc', 'spbill_create_ip', ); foreach ($must as $key) { if (isset($parameters[$key]) && $parameters[$key]) { $this->setParameter($key, $parameters[$key]); } else if (! isset($this->_parameters[$key]) || ! $this->_parameters[$key]) { $this->error = '參數缺損:' . $key; return false; } } if (! isset($parameters['partner_trade_no'])) { $parameters['partner_trade_no'] = $this->getPartnerTradeNo(); } $this->setParameter('partner_trade_no', $parameters['partner_trade_no']); $this->setParameter('nonce_str', $this->getRand(30, 3)); $postXml = $this->_createXml(); if (! $postXml) { return false; } $this->log($postXml, 'SEND_XML'); $result = $this->curl_post_ssl(self::TRANSFERS_URL, $postXml); $this->log($result, 'RESULT_XML'); if (! $result) { return false; } $resultObj = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA); $this->_lastResult = $resultObj; if ($resultObj->return_code == 'SUCCESS') { // 成功標識 if ($resultObj->result_code == 'SUCCESS') { return $resultObj->send_listid; } if ($resultObj->return_msg) { $this->error = (string) $resultObj->return_msg; return false; } $this->error = (string) $resultObj->err_code_des; return false; } if ($resultObj->return_code != 'FAIL') { $this->error = '返回信息格式異常'; return false; } $this->error = (string) $resultObj->return_msg; return false; } /** * 獲取轉賬信息 * @param unknown $partner_trade_no * @return boolean|SimpleXMLElement */ public function getInfo($partner_trade_no){ $param = array( 'nonce_str' => $this->getRand(30, 3), 'partner_trade_no'=> $partner_trade_no , 'mch_id' => $this->_keys['mch_id'], 'appid' => $this->_keys['wxappid'], ); ksort($param); $unSignParaString = $this->_formatQueryParaMap($param, false); $param['sign'] = $this->_sign($unSignParaString, $this->_keys['key']); $xml = $this->arrayToXml($param); $this->log($xml, 'GETINFO_XML'); $result = $this->curl_post_ssl(self::GETINFO_URL, $xml); if(!$result){ return false ; } $this->log($result, 'RESULT_XML'); $resultObj = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA); $this->_lastResult = $resultObj ; if($resultObj->return_code == 'SUCCESS'){//成功標識 if($resultObj->result_code == 'SUCCESS'){ return $resultObj ; } if($resultObj->return_msg){ $this->error = $resultObj->return_msg ; return false ; } $this->error = $resultObj->err_code_des ; return false ; } if($resultObj->return_code != 'FAIL'){ $this->error = '返回信息格式異常'; return false ; } $this->error = $resultObj->return_msg ; return false ; } /** * 設置所需要的參數 * @param $parameter 鍵值數組/鍵 * @param $value 值 * @return WxBonusApi */ public function setParameter($parameter, $value = null) { if (! is_array($parameter)) { return $this->setParameter(array( $parameter => $value )); } foreach ($parameter as $key => $value) { $key = trim($key); $value = trim($value); $this->_parameters[$key] = $value; } return $this; } /** * 獲取參數值 * @param $parameter 鍵名 * @return multitype: */ public function getParameter($parameter) { return $this->_parameters[$parameter]; } /** * 獲取隨機數 * @param number $len 隨機數的位數 * @param number $type 取值范圍 1表示數字 2小寫字母 4大寫字母 * @return string */ public function getRand($len = 30, $type = 0) { $str = ''; $max = - 1; if (! $type) { $type = 3; } if ($type & 1) { $str .= '1234567890'; $max += 10; } if ($type & 2) { $str .= 'abcdefghijklmnopqrstuvwxyz'; $max += 26; } if ($type & 4) { $str .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $max += 26; } $rand = ''; for ($i = 0; $i < $len; $i ++) { $rand .= $str[rand(0, $max)]; } return $rand; } /** * 生成商戶的訂單號 * @return string */ public function getPartnerTradeNo() { $this->_lastPartnerTradeNo = $this->_parameters['mch_id'] . date('YmdHis') . $this->getRand(4, 1); // $this->getRandNum(); return $this->_lastPartnerTradeNo; } /** * 獲取最后一次創建生成的訂單號 * @return string */ public function getLastPartnerTradeNo() { return $this->_lastPartnerTradeNo; } /** * 創建XML的方法 * @param number $retcode * @param string $reterrmsg * @return boolean|string */ private function _createXml() { try { $sign = $this->_getSign(); if (! $sign) { return false; } $this->setParameter('sign', $sign); return $this->arrayToXml($this->_parameters); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } /** * 參數轉換成XML * @param array $arr 參數數組 * @return string */ public function arrayToXml($arr) { $xml = "<xml>"; foreach ($arr as $key => $val) { if (is_numeric($val)) { $xml .= "<" . $key . ">" . $val . "</" . $key . ">"; } else { $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">"; } } $xml .= "</xml>"; return $xml; } /** * 獲得簽名結果 * @return boolean|Ambigous <string, boolean> */ protected function _getSign() { try { if ($this->_checkSign() == false) { // 檢查生成簽名參數 $this->error = '生成簽名參數缺失!'; $this->log(json_encode($this->_parameters, JSON_UNESCAPED_UNICODE), 'ERROR_Sign_XML'); return false; } ksort($this->_parameters); $unSignParaString = $this->_formatQueryParaMap($this->_parameters, false); return $this->_sign($unSignParaString, $this->_keys['key']); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } /** * 檢查簽名所需參數是否齊全 * @return boolean */ private function _checkSign() { // return true; if ($this->_parameters["mch_appid"] == null || $this->_parameters["mchid"] == null || //$this->_parameters["device_info"] == null || 設備id $this->_parameters["nonce_str"] == null || $this->_parameters["partner_trade_no"] == null || $this->_parameters["openid"] == null || $this->_parameters["check_name"] == null || $this->_parameters["re_user_name"] == null || $this->_parameters["desc"] == null || $this->_parameters["spbill_create_ip"] == null) { return false; } return true; } /** * * @param $paraMap * @param $urlencode * @return string */ private function _formatQueryParaMap($paraMap,$urlencode) { $buff = ""; ksort($paraMap); foreach ($paraMap as $k => $v) { if (null != $v && "null" != $v && "sign" != $k) { if ($urlencode) { $v = urlencode($v); } $buff .= $k . "=" . $v . "&"; } } $reqPar; if (strlen($buff) > 0) { $reqPar = substr($buff, 0, strlen($buff) - 1); } return $reqPar; } /** * 簽名 * @param $content 簽名的字符串 * @param $key 密鑰 * @throws Exception * @return string|boolean */ private function _sign($content, $key) { try { if (null == $key) { $this->error = '簽名key不能為空!'; return false; } if (null == $content) { $this->error = '簽名內容不能為空'; return false; } $signStr = $content . "&key=" . $key; return strtoupper(md5($signStr)); } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } /** * cURL抓取 * * @param $url 鏈接地址 * @param $vars 參數 * @param * $second * @param * $aHeader * @return mixed|boolean */ function curl_post_ssl($url, $data, $second = 30, $aHeader = array()) { $ch = curl_init(); // 超時時間 curl_setopt($ch, CURLOPT_TIMEOUT, $second); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 這里設置代理,如果有的話 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // cert 與 key 分別屬于兩個.pem文件 curl_setopt($ch, CURLOPT_SSLCERT, $this->_cert['api_cert']); curl_setopt($ch, CURLOPT_SSLKEY, $this->_cert['api_key']); curl_setopt($ch, CURLOPT_CAINFO, $this->_cert['rootca']); if (count($aHeader) >= 1) { curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader); } curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $data = curl_exec($ch); if ($data) { curl_close($ch); return $data; } else { $this->log(json_encode($this->_cert)); $this->error = 'aa:'.curl_errno($ch); curl_close($ch); return false; } } /** * 獲取服務器ip * * @return string */ public function getServerIp() { $server_ip = '127.0.0.1'; if (isset($_SERVER)) { if (isset($_SERVER['SERVER_ADDR']) && $_SERVER['SERVER_ADDR']) { $server_ip = $_SERVER['SERVER_ADDR']; } elseif (isset($_SERVER['LOCAL_ADDR']) && $_SERVER['LOCAL_ADDR']) { $server_ip = $_SERVER['LOCAL_ADDR']; } } else { $server_ip = getenv('SERVER_ADDR'); } return $server_ip; } /** * 設置日志目錄文件 * * @param unknown $file */ public function setLogFile($file) { $this->log_file = $file; } /** * 寫日志 * * @param $msg 寫入的信息 * @param $type 日志類型作為查詢標示 */ public function log($msg, $type) { if ($this->log_file) { $log = str_replace(array( "\r\n", "\r", "\n" ), array( "", "", "" ), $msg); error_log($type . ' ' . date('Y-m-d H:i:s') . ' ' . json_encode($log,JSON_UNESCAPED_UNICODE) . "\r\n", 3, $this->log_file); } } }
<?php include 'WxTransfers.Api.php'; class WxTransfers{ /** *調用方法即可測試 */ public function index(){ $path = WxTransfersConfig::getRealPath(); // 證書文件路徑 $config['wxappid'] = WxTransfersConfig::APPID; $config['mch_id'] = WxTransfersConfig::MCHID; $config['key'] = WxTransfersConfig::KEY; $config['PARTNERKEY'] = WxTransfersConfig::KEY; $config['api_cert'] = $path . WxTransfersConfig::SSLCERT_PATH; $config['api_key'] = $path . WxTransfersConfig::SSLKEY_PATH; $config['rootca'] = $path . WxTransfersConfig::SSLROOTCA; $wxtran=new WxTransfers($config); $wxtran->setLogFile('D:\\transfers.log');//日志地址 //轉賬 $data=array( 'openid'=>'',//openid 'check_name'=>'NO_CHECK',//是否驗證真實姓名參數 're_user_name'=>'11',//姓名 'amount'=>100,//最小1元 也就是100 'desc'=>'企業轉賬測試',//描述 'spbill_create_ip'=>$wxtran->getServerIp(),//服務器IP地址 ); var_dump(json_encode($wxtran->transfers($data),JSON_UNESCAPED_UNICODE)); var_dump($wxtran->error); //獲取轉賬信息 var_dump($wxtran->getInfo('11111111')); var_dump($wxtran->error); } }
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。