经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
php实现微信企业转账功能
来源:jb51  时间:2018/10/8 8:45:22  对本文有异议

本文实例为大家分享了php实现微信企业转账的具体代码,供大家参考,具体内容如下

  1. <?php
  2. /**
  3. * 配置账号信息
  4. * 配置要和证书在一起!!!!
  5. */
  6. class WxTransfersConfig
  7. {
  8. //=======【基本信息设置】==============
  9. //
  10. /**
  11. * TODO: 修改这里配置为您自己申请的商户信息
  12. * 微信公众号信息配置
  13. *
  14. * APPID:绑定支付的APPID(必须配置,开户邮件中可查看)
  15. *
  16. * MCHID:商户号(必须配置,开户邮件中可查看)
  17. *
  18. * KEY:商户支付密钥,参考开户邮件设置(必须配置,登录商户平台自行设置)
  19. * 设置地址:https://pay.weixin.qq.com/index.php/account/api_cert
  20. *
  21. */
  22. const APPID = '';
  23. const MCHID = '';
  24. const KEY = '';
  25. //=======【证书路径设置】=====================================
  26. /**
  27. * TODO:设置商户证书路径
  28. * 证书路径,注意应该填写绝对路径,发送红包和查询需要,可登录商户平台下载
  29. * API证书下载地址:https://pay.weixin.qq.com/index.php/account/api_cert,下载之前需要安装商户操作证书)
  30. * @var path 跟这个文件同一目录下的cert文件夹放置证书!!!!
  31. */
  32. const SSLCRET12 = 'cert/apiclient_cert.p12';
  33. const SSLCERT_PATH = 'cert/apiclient_cert.pem';
  34. const SSLKEY_PATH = 'cert/apiclient_key.pem';
  35. const SSLROOTCA = 'cert/rootca.pem';
  36. //=======【证书路径设置】=====================================
  37. /**
  38. * 获取文件的路径,证书需要完整路径
  39. * @return string
  40. */
  41. public static function getRealPath(){
  42. return __DIR__.'/';
  43. }
  44. }
  45.  

微信企业转账工具类:

  1. <?php
  2. require_once "WxTransfers.Config.php";
  3. /**
  4. * 微信企业转账工具类
  5. */
  6. class WxTransfers
  7. {
  8. // 企业转账请求地址
  9. const TRANSFERS_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
  10. //获取转账信息地址
  11. const GETINFO_URL='https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo';
  12. // 转账需要的配置 'wxappid','mch_id','key'
  13. private $_keys;
  14. // 转账需要的证书文件 'api_cert', 'api_key', 'rootca',请传入绝对路径!!!
  15. private $_cert;
  16. protected $log_file;
  17. public $error;
  18. // 相关配置必备参数
  19. protected $_parameters = array();
  20. // 最后一次生产的订单号
  21. protected $_lastPartnerTradeNo;
  22. // 记录最后一次发送请求的结果对象
  23. protected $_lastResult;
  24. // 最后一次随机数
  25. protected $_lastRandNum;
  26. public function __construct($config)
  27. {
  28. $keys = array(
  29. 'wxappid',
  30. 'mch_id',
  31. 'key'
  32. );
  33. $files = array(
  34. 'api_cert',
  35. 'api_key',
  36. 'rootca'
  37. );
  38. foreach ($keys as $key) {
  39. try {
  40. $this->_keys[$key] = $config[$key];
  41. } catch (Exception $e) {
  42. throw new Exception('参数缺失:' . $key);
  43. }
  44. }
  45. foreach ($files as $file) {
  46. try {
  47. $cret_file = $config[$file];
  48. if (is_file($cret_file)) {
  49. $this->_cert[$file] = $cret_file;
  50. }
  51. } catch (Exception $e) {
  52. throw new Exception('证书错误');
  53. }
  54. }
  55. }
  56. public function transfers($parameters){
  57. $this->log($parameters, 'SEND_PARAM');
  58. $this->setParameter('mchid', $this->_keys['mch_id']);
  59. $this->setParameter('mch_appid', $this->_keys['wxappid']);
  60. $must = array(
  61. 'openid',
  62. 'check_name',
  63. 're_user_name',
  64. 'amount',
  65. 'desc',
  66. 'spbill_create_ip',
  67. );
  68. foreach ($must as $key) {
  69. if (isset($parameters[$key]) && $parameters[$key]) {
  70. $this->setParameter($key, $parameters[$key]);
  71. } else
  72. if (! isset($this->_parameters[$key]) || ! $this->_parameters[$key]) {
  73. $this->error = '参数缺损:' . $key;
  74. return false;
  75. }
  76. }
  77. if (! isset($parameters['partner_trade_no'])) {
  78. $parameters['partner_trade_no'] = $this->getPartnerTradeNo();
  79. }
  80. $this->setParameter('partner_trade_no', $parameters['partner_trade_no']);
  81. $this->setParameter('nonce_str', $this->getRand(30, 3));
  82. $postXml = $this->_createXml();
  83. if (! $postXml) {
  84. return false;
  85. }
  86. $this->log($postXml, 'SEND_XML');
  87. $result = $this->curl_post_ssl(self::TRANSFERS_URL, $postXml);
  88. $this->log($result, 'RESULT_XML');
  89. if (! $result) {
  90. return false;
  91. }
  92. $resultObj = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  93. $this->_lastResult = $resultObj;
  94. if ($resultObj->return_code == 'SUCCESS') { // 成功标识
  95. if ($resultObj->result_code == 'SUCCESS') {
  96. return $resultObj->send_listid;
  97. }
  98. if ($resultObj->return_msg) {
  99. $this->error = (string) $resultObj->return_msg;
  100. return false;
  101. }
  102. $this->error = (string) $resultObj->err_code_des;
  103. return false;
  104. }
  105. if ($resultObj->return_code != 'FAIL') {
  106. $this->error = '返回信息格式异常';
  107. return false;
  108. }
  109. $this->error = (string) $resultObj->return_msg;
  110. return false;
  111. }
  112. /**
  113. * 获取转账信息
  114. * @param unknown $partner_trade_no
  115. * @return boolean|SimpleXMLElement
  116. */
  117. public function getInfo($partner_trade_no){
  118. $param = array(
  119. 'nonce_str' => $this->getRand(30, 3),
  120. 'partner_trade_no'=> $partner_trade_no ,
  121. 'mch_id' => $this->_keys['mch_id'],
  122. 'appid' => $this->_keys['wxappid'],
  123. );
  124. ksort($param);
  125. $unSignParaString = $this->_formatQueryParaMap($param, false);
  126. $param['sign'] = $this->_sign($unSignParaString, $this->_keys['key']);
  127. $xml = $this->arrayToXml($param);
  128. $this->log($xml, 'GETINFO_XML');
  129. $result = $this->curl_post_ssl(self::GETINFO_URL, $xml);
  130. if(!$result){
  131. return false ;
  132. }
  133. $this->log($result, 'RESULT_XML');
  134. $resultObj = simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA);
  135. $this->_lastResult = $resultObj ;
  136. if($resultObj->return_code == 'SUCCESS'){//成功标识
  137. if($resultObj->result_code == 'SUCCESS'){
  138. return $resultObj ;
  139. }
  140. if($resultObj->return_msg){
  141. $this->error = $resultObj->return_msg ;
  142. return false ;
  143. }
  144. $this->error = $resultObj->err_code_des ;
  145. return false ;
  146. }
  147. if($resultObj->return_code != 'FAIL'){
  148. $this->error = '返回信息格式异常';
  149. return false ;
  150. }
  151. $this->error = $resultObj->return_msg ;
  152. return false ;
  153. }
  154. /**
  155. * 设置所需要的参数
  156. * @param $parameter 键值数组/键
  157. * @param $value 值
  158. * @return WxBonusApi
  159. */
  160. public function setParameter($parameter, $value = null)
  161. {
  162. if (! is_array($parameter)) {
  163. return $this->setParameter(array(
  164. $parameter => $value
  165. ));
  166. }
  167. foreach ($parameter as $key => $value) {
  168. $key = trim($key);
  169. $value = trim($value);
  170. $this->_parameters[$key] = $value;
  171. }
  172. return $this;
  173. }
  174. /**
  175. * 获取参数值
  176. * @param $parameter 键名
  177. * @return multitype:
  178. */
  179. public function getParameter($parameter)
  180. {
  181. return $this->_parameters[$parameter];
  182. }
  183. /**
  184. * 获取随机数
  185. * @param number $len 随机数的位数
  186. * @param number $type 取值范围 1表示数字 2小写字母 4大写字母
  187. * @return string
  188. */
  189. public function getRand($len = 30, $type = 0)
  190. {
  191. $str = '';
  192. $max = - 1;
  193. if (! $type) {
  194. $type = 3;
  195. }
  196. if ($type & 1) {
  197. $str .= '1234567890';
  198. $max += 10;
  199. }
  200. if ($type & 2) {
  201. $str .= 'abcdefghijklmnopqrstuvwxyz';
  202. $max += 26;
  203. }
  204. if ($type & 4) {
  205. $str .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  206. $max += 26;
  207. }
  208. $rand = '';
  209. for ($i = 0; $i < $len; $i ++) {
  210. $rand .= $str[rand(0, $max)];
  211. }
  212. return $rand;
  213. }
  214. /**
  215. * 生成商户的订单号
  216. * @return string
  217. */
  218. public function getPartnerTradeNo()
  219. {
  220. $this->_lastPartnerTradeNo = $this->_parameters['mch_id'] . date('YmdHis') . $this->getRand(4, 1); // $this->getRandNum();
  221. return $this->_lastPartnerTradeNo;
  222. }
  223. /**
  224. * 获取最后一次创建生成的订单号
  225. * @return string
  226. */
  227. public function getLastPartnerTradeNo()
  228. {
  229. return $this->_lastPartnerTradeNo;
  230. }
  231. /**
  232. * 创建XML的方法
  233. * @param number $retcode
  234. * @param string $reterrmsg
  235. * @return boolean|string
  236. */
  237. private function _createXml()
  238. {
  239. try {
  240. $sign = $this->_getSign();
  241. if (! $sign) {
  242. return false;
  243. }
  244. $this->setParameter('sign', $sign);
  245. return $this->arrayToXml($this->_parameters);
  246. } catch (Exception $e) {
  247. $this->error = $e->getMessage();
  248. return false;
  249. }
  250. }
  251. /**
  252. * 参数转换成XML
  253. * @param array $arr 参数数组
  254. * @return string
  255. */
  256. public function arrayToXml($arr)
  257. {
  258. $xml = "<xml>";
  259. foreach ($arr as $key => $val) {
  260. if (is_numeric($val)) {
  261. $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
  262. } else {
  263. $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
  264. }
  265. }
  266. $xml .= "</xml>";
  267. return $xml;
  268. }
  269. /**
  270. * 获得签名结果
  271. * @return boolean|Ambigous <string, boolean>
  272. */
  273. protected function _getSign()
  274. {
  275. try {
  276. if ($this->_checkSign() == false) { // 检查生成签名参数
  277. $this->error = '生成签名参数缺失!';
  278. $this->log(json_encode($this->_parameters, JSON_UNESCAPED_UNICODE), 'ERROR_Sign_XML');
  279. return false;
  280. }
  281. ksort($this->_parameters);
  282. $unSignParaString = $this->_formatQueryParaMap($this->_parameters, false);
  283. return $this->_sign($unSignParaString, $this->_keys['key']);
  284. } catch (Exception $e) {
  285. $this->error = $e->getMessage();
  286. return false;
  287. }
  288. }
  289. /**
  290. * 检查签名所需参数是否齐全
  291. * @return boolean
  292. */
  293. private function _checkSign()
  294. {
  295. // return true;
  296. if ($this->_parameters["mch_appid"] == null ||
  297. $this->_parameters["mchid"] == null ||
  298. //$this->_parameters["device_info"] == null || 设备id
  299. $this->_parameters["nonce_str"] == null ||
  300. $this->_parameters["partner_trade_no"] == null ||
  301. $this->_parameters["openid"] == null ||
  302. $this->_parameters["check_name"] == null ||
  303. $this->_parameters["re_user_name"] == null ||
  304. $this->_parameters["desc"] == null ||
  305. $this->_parameters["spbill_create_ip"] == null) {
  306. return false;
  307. }
  308. return true;
  309. }
  310. /**
  311. *
  312. * @param $paraMap
  313. * @param $urlencode
  314. * @return string
  315. */
  316. private function _formatQueryParaMap($paraMap,$urlencode)
  317. {
  318. $buff = "";
  319. ksort($paraMap);
  320. foreach ($paraMap as $k => $v) {
  321. if (null != $v && "null" != $v && "sign" != $k) {
  322. if ($urlencode) {
  323. $v = urlencode($v);
  324. }
  325. $buff .= $k . "=" . $v . "&";
  326. }
  327. }
  328. $reqPar;
  329. if (strlen($buff) > 0) {
  330. $reqPar = substr($buff, 0, strlen($buff) - 1);
  331. }
  332. return $reqPar;
  333. }
  334. /**
  335. * 签名
  336. * @param $content 签名的字符串
  337. * @param $key 密钥
  338. * @throws Exception
  339. * @return string|boolean
  340. */
  341. private function _sign($content, $key)
  342. {
  343. try {
  344. if (null == $key) {
  345. $this->error = '签名key不能为空!';
  346. return false;
  347. }
  348. if (null == $content) {
  349. $this->error = '签名内容不能为空';
  350. return false;
  351. }
  352. $signStr = $content . "&key=" . $key;
  353. return strtoupper(md5($signStr));
  354. } catch (Exception $e) {
  355. $this->error = $e->getMessage();
  356. return false;
  357. }
  358. }
  359. /**
  360. * cURL抓取
  361. *
  362. * @param $url 链接地址
  363. * @param $vars 参数
  364. * @param
  365. * $second
  366. * @param
  367. * $aHeader
  368. * @return mixed|boolean
  369. */
  370. function curl_post_ssl($url, $data, $second = 30, $aHeader = array())
  371. {
  372. $ch = curl_init();
  373. // 超时时间
  374. curl_setopt($ch, CURLOPT_TIMEOUT, $second);
  375. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  376. // 这里设置代理,如果有的话
  377. curl_setopt($ch, CURLOPT_URL, $url);
  378. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  379. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  380. // cert 与 key 分别属于两个.pem文件
  381. curl_setopt($ch, CURLOPT_SSLCERT, $this->_cert['api_cert']);
  382. curl_setopt($ch, CURLOPT_SSLKEY, $this->_cert['api_key']);
  383. curl_setopt($ch, CURLOPT_CAINFO, $this->_cert['rootca']);
  384. if (count($aHeader) >= 1) {
  385. curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
  386. }
  387. curl_setopt($ch, CURLOPT_POST, 1);
  388. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  389. $data = curl_exec($ch);
  390. if ($data) {
  391. curl_close($ch);
  392. return $data;
  393. } else {
  394. $this->log(json_encode($this->_cert));
  395. $this->error = 'aa:'.curl_errno($ch);
  396. curl_close($ch);
  397. return false;
  398. }
  399. }
  400. /**
  401. * 获取服务器ip
  402. *
  403. * @return string
  404. */
  405. public function getServerIp()
  406. {
  407. $server_ip = '127.0.0.1';
  408. if (isset($_SERVER)) {
  409. if (isset($_SERVER['SERVER_ADDR']) && $_SERVER['SERVER_ADDR']) {
  410. $server_ip = $_SERVER['SERVER_ADDR'];
  411. } elseif (isset($_SERVER['LOCAL_ADDR']) && $_SERVER['LOCAL_ADDR']) {
  412. $server_ip = $_SERVER['LOCAL_ADDR'];
  413. }
  414. } else {
  415. $server_ip = getenv('SERVER_ADDR');
  416. }
  417. return $server_ip;
  418. }
  419. /**
  420. * 设置日志目录文件
  421. *
  422. * @param unknown $file
  423. */
  424. public function setLogFile($file)
  425. {
  426. $this->log_file = $file;
  427. }
  428. /**
  429. * 写日志
  430. *
  431. * @param $msg 写入的信息
  432. * @param $type 日志类型作为查询标示
  433. */
  434. public function log($msg, $type)
  435. {
  436. if ($this->log_file) {
  437. $log = str_replace(array(
  438. "\r\n",
  439. "\r",
  440. "\n"
  441. ), array(
  442. "",
  443. "",
  444. ""
  445. ), $msg);
  446. error_log($type . ' ' . date('Y-m-d H:i:s') . ' ' . json_encode($log,JSON_UNESCAPED_UNICODE) . "\r\n", 3, $this->log_file);
  447. }
  448. }
  449. }
  450.  
  1. <?php
  2.  
  3. include 'WxTransfers.Api.php';
  4. class WxTransfers{
  5.  
  6. /**
  7. *调用方法即可测试
  8. */
  9. public function index(){
  10. $path = WxTransfersConfig::getRealPath(); // 证书文件路径
  11. $config['wxappid'] = WxTransfersConfig::APPID;
  12. $config['mch_id'] = WxTransfersConfig::MCHID;
  13. $config['key'] = WxTransfersConfig::KEY;
  14. $config['PARTNERKEY'] = WxTransfersConfig::KEY;
  15. $config['api_cert'] = $path . WxTransfersConfig::SSLCERT_PATH;
  16. $config['api_key'] = $path . WxTransfersConfig::SSLKEY_PATH;
  17. $config['rootca'] = $path . WxTransfersConfig::SSLROOTCA;
  18. $wxtran=new WxTransfers($config);
  19. $wxtran->setLogFile('D:\\transfers.log');//日志地址
  20. //转账
  21. $data=array(
  22. 'openid'=>'',//openid
  23. 'check_name'=>'NO_CHECK',//是否验证真实姓名参数
  24. 're_user_name'=>'11',//姓名
  25. 'amount'=>100,//最小1元 也就是100
  26. 'desc'=>'企业转账测试',//描述
  27. 'spbill_create_ip'=>$wxtran->getServerIp(),//服务器IP地址
  28. );
  29. var_dump(json_encode($wxtran->transfers($data),JSON_UNESCAPED_UNICODE));
  30. var_dump($wxtran->error);
  31. //获取转账信息
  32. var_dump($wxtran->getInfo('11111111'));
  33. var_dump($wxtran->error);
  34. }
  35. }
  36.  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号