WechatMerchantTransferLogic.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop开源商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | gitee下载:https://gitee.com/likeshop_gitee
  7. // | github下载:https://github.com/likeshop-github
  8. // | 访问官网:https://www.likeshop.cn
  9. // | 访问社区:https://home.likeshop.cn
  10. // | 访问手册:http://doc.likeshop.cn
  11. // | 微信公众号:likeshop技术社区
  12. // | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用,未经许可不能去除前后端官方版权标识
  13. // | likeshop系列产品收费版本务必购买商业授权,购买去版权授权后,方可去除前后端官方版权标识
  14. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  15. // | likeshop团队版权所有并拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshop.cn.team
  18. // +----------------------------------------------------------------------
  19. namespace app\adminapi\logic\withdraw;
  20. use app\common\enum\WithdrawEnum;
  21. use app\common\model\WithdrawApply;
  22. /**
  23. * 功能: 商家转账到零钱
  24. * 用途:商户可以通过该接口同时向多个用户微信零钱进行转账操作。
  25. * 证书:需要
  26. * 请求URL:https://api.mch.weixin.qq.com/v3/transfer/batches
  27. * 失败后一定要用【原来的商户订单号】去重试,不然有可能存在重复支付的风险!!!
  28. * 转账批次单中涉及金额的字段单位为“分”
  29. * 成功受理商家转账请求后,可调用《商家明细单号查询明细单》接口来判断转账明细列表状态
  30. */
  31. class WechatMerchantTransferLogic
  32. {
  33. /**
  34. * @notes 商家转账到零钱
  35. * @param $withdrawApply
  36. * @param $userAuth
  37. * @param $config
  38. * @return bool
  39. * @throws \Exception
  40. * @author ljj
  41. * @date 2022/9/27 4:40 下午
  42. */
  43. public static function transfer($withdrawApply,$userAuth,$config)
  44. {
  45. //请求URL
  46. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches';
  47. //请求方式
  48. $http_method = 'POST';
  49. //请求参数
  50. $data = [
  51. 'appid' => $config['app_id'],//申请商户号的appid或商户号绑定的appid(企业号corpid即为此appid)
  52. 'out_batch_no' => $withdrawApply['batch_no'],//商户系统内部的商家批次单号,要求此参数只能由数字、大小写字母组成,在商户系统内部唯一
  53. 'batch_name' => '提现至微信零钱',//该笔批量转账的名称
  54. 'batch_remark' => '提现至微信零钱',//转账说明,UTF8编码,最多允许32个字符
  55. 'total_amount' => intval(bcmul(100, $withdrawApply->left_money)),//转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致,否则无法发起转账操作
  56. 'total_num' => 1,//一个转账批次单最多发起三千笔转账。转账总笔数必须与批次内所有明细之和保持一致,否则无法发起转账操作
  57. 'transfer_detail_list' => [
  58. [//发起批量转账的明细列表,最多三千笔
  59. 'out_detail_no' => $withdrawApply['sn'],//商户系统内部区分转账批次单下不同转账明细单的唯一标识,要求此参数只能由数字、大小写字母组成
  60. 'transfer_amount' => intval(bcmul(100, $withdrawApply->left_money)),//转账金额单位为分
  61. 'transfer_remark' => '提现至微信零钱',//单条转账备注(微信用户会收到该备注),UTF8编码,最多允许32个字符
  62. 'openid' => $userAuth['openid'],//openid是微信用户在公众号appid下的唯一用户标识(appid不同,则获取到的openid就不同),可用于永久标记一个用户
  63. ]]
  64. ];
  65. if ($withdrawApply['left_money'] >= 2000) {
  66. if (empty($withdrawApply['real_name'])) {
  67. throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
  68. }
  69. $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'],$config);
  70. }
  71. $token = self::token($url,$http_method,$data,$config);//获取token
  72. $result = self::https_request($url,json_encode($data),$token);//发送请求
  73. $result_arr = json_decode($result,true);
  74. if(!isset($result_arr['create_time'])) {//批次受理失败
  75. if (strpos($result_arr['message'],"产品权限异常") !== false) {
  76. throw new \Exception('产品权限异常 - 请在商户平台-商家转账产品设置中开通产品权限');
  77. }
  78. throw new \Exception($result_arr['message']);
  79. }
  80. //批次受理成功,更新提现申请单为提现中状态
  81. WithdrawApply::update([
  82. 'status' => WithdrawEnum::STATUS_ING,
  83. 'audit_remark' => $params['audit_remark'] ?? '',
  84. 'pay_desc' => $result,
  85. ],['id'=>$withdrawApply['id']]);
  86. return true;
  87. }
  88. /**
  89. * @notes 签名生成
  90. * @param $url
  91. * @param $http_method
  92. * @param $data
  93. * @param $config
  94. * @return string
  95. * @author ljj
  96. * @date 2022/9/27 4:14 下午
  97. */
  98. public static function token($url,$http_method,$data,$config)
  99. {
  100. $timestamp = time();//请求时间戳
  101. $url_parts = parse_url($url);//获取请求的绝对URL
  102. $nonce = $timestamp.rand('10000','99999');//请求随机串
  103. $body = empty($data) ? '' : json_encode((object)$data);//请求报文主体
  104. $stream_opts = [
  105. "ssl" => [
  106. "verify_peer"=>false,
  107. "verify_peer_name"=>false,
  108. ]
  109. ];
  110. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'],false, stream_context_create($stream_opts)));
  111. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  112. $mch_private_key = file_get_contents($config['key_path'],false, stream_context_create($stream_opts));//密钥
  113. $merchant_id = $config['mch_id'];//商户id
  114. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  115. $message = $http_method."\n".
  116. $canonical_url."\n".
  117. $timestamp."\n".
  118. $nonce."\n".
  119. $body."\n";
  120. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  121. $sign = base64_encode($raw_sign);//签名
  122. $schema = 'WECHATPAY2-SHA256-RSA2048';
  123. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  124. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  125. return $schema.' '.$token;
  126. }
  127. /**
  128. * @notes 发送请求
  129. * @param $url
  130. * @param $data
  131. * @param $token
  132. * @return bool|string
  133. * @author ljj
  134. * @date 2022/9/27 4:15 下午
  135. */
  136. public static function https_request($url,$data,$token)
  137. {
  138. $curl = curl_init();
  139. curl_setopt($curl, CURLOPT_URL, (string)$url);
  140. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  141. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  142. if (!empty($data)){
  143. curl_setopt($curl, CURLOPT_POST, 1);
  144. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  145. }
  146. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  147. //添加请求头
  148. $headers = [
  149. 'Authorization:'.$token,
  150. 'Accept: application/json',
  151. 'Content-Type: application/json; charset=utf-8',
  152. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  153. ];
  154. if(!empty($headers)){
  155. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  156. }
  157. $output = curl_exec($curl);
  158. curl_close($curl);
  159. return $output;
  160. }
  161. /**
  162. * @notes 敏感信息加解密
  163. * @param $str
  164. * @param $config
  165. * @return string
  166. * @throws \Exception
  167. * @author ljj
  168. * @date 2022/9/27 3:53 下午
  169. */
  170. public static function getEncrypt($str,$config)
  171. {
  172. //$str是待加密字符串
  173. $public_key = file_get_contents($config['cert_path']);
  174. $encrypted = '';
  175. if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  176. //base64编码
  177. $sign = base64_encode($encrypted);
  178. } else {
  179. throw new \Exception('encrypt failed');
  180. }
  181. return $sign;
  182. }
  183. /**
  184. * @notes 商家明细单号查询明细单API
  185. * @param $withdrawApply
  186. * @param $config
  187. * @return mixed
  188. * @author ljj
  189. * @date 2022/9/27 5:54 下午
  190. */
  191. public static function details($withdrawApply,$config)
  192. {
  193. //请求URL
  194. $url = 'https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/'.$withdrawApply['batch_no'].'/details/out-detail-no/'.$withdrawApply['sn'];
  195. //请求方式
  196. $http_method = 'GET';
  197. //请求参数
  198. $data = [];
  199. $token = self::token($url,$http_method,$data,$config);//获取token
  200. $result = self::https_request($url,$data,$token);//发送请求
  201. $result_arr = json_decode($result,true);
  202. return $result_arr;
  203. }
  204. }