WechatMerchantTransferLogic.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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\UserAuth;
  22. use app\common\model\WithdrawApply;
  23. use app\common\service\WeChatConfigService;
  24. /**
  25. * 功能: 商家转账到零钱
  26. * 用途:商户可以通过该接口同时向多个用户微信零钱进行转账操作。
  27. * 证书:需要
  28. * 请求URL:https://api.mch.weixin.qq.com/v3/transfer/batches
  29. * 失败后一定要用【原来的商户订单号】去重试,不然有可能存在重复支付的风险!!!
  30. * 转账批次单中涉及金额的字段单位为“分”
  31. * 成功受理商家转账请求后,可调用《商家明细单号查询明细单》接口来判断转账明细列表状态
  32. */
  33. class WechatMerchantTransferLogic
  34. {
  35. /**
  36. * @notes 商家转账到零钱
  37. * @param $withdrawApply
  38. * @return bool
  39. * @throws \Exception
  40. * @author ljj
  41. * @date 2022/9/27 4:40 下午
  42. */
  43. public static function transfer($withdrawApply)
  44. {
  45. // 用户授权信息
  46. $userAuth = UserAuth::where(['user_id'=>$withdrawApply['user_id'],'terminal'=>$withdrawApply['terminal']])->findOrEmpty();
  47. if($userAuth->isEmpty()) {
  48. throw new \Exception('查询不到该用户的微信授权信息');
  49. }
  50. // 获取微信配置
  51. $config = WeChatConfigService::getWechatConfigByTerminal($userAuth->terminal);
  52. //请求URL
  53. $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
  54. //请求方式
  55. $http_method = 'POST';
  56. //请求参数
  57. $data = [
  58. 'appid' => $config['app_id'],
  59. 'out_bill_no' => $withdrawApply['sn'],
  60. 'transfer_scene_id' => '1005',
  61. 'transfer_remark' => '提现',
  62. 'openid' => $userAuth['openid'],
  63. 'transfer_amount' => intval(bcmul($withdrawApply['left_money'], 100)),
  64. 'transfer_scene_report_infos' => [
  65. [ 'info_type' => '岗位类型', 'info_content' => '邀请者' ],
  66. [ 'info_type' => '报酬说明', 'info_content' => '邀请奖励提现' ],
  67. ],
  68. ];
  69. if ($withdrawApply['left_money'] >= 2000) {
  70. if (empty($withdrawApply['real_name'])) {
  71. throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
  72. }
  73. $data['transfer_detail_list'][0]['user_name'] = self::getEncrypt($withdrawApply['real_name'],$config);
  74. }
  75. $token = self::token($url,$http_method,$data,$config);//获取token
  76. $result = self::https_request($url,json_encode($data),$token);//发送请求
  77. $result_arr = json_decode($result,true);
  78. if(!isset($result_arr['create_time'])) {//批次受理失败
  79. if (strpos($result_arr['message'],"产品权限异常") !== false) {
  80. throw new \Exception('产品权限异常 - 请在商户平台-商家转账产品设置中开通产品权限');
  81. }
  82. throw new \Exception($result_arr['message'] ?? $result['fail_reason'] ?? '零钱提现请求失败');
  83. }
  84. //批次受理成功,更新提现申请单为提现中状态
  85. WithdrawApply::update([
  86. 'status' => WithdrawEnum::STATUS_ING,
  87. 'audit_remark' => $params['audit_remark'] ?? '',
  88. 'pay_desc' => $result,
  89. ],['id'=>$withdrawApply['id']]);
  90. return true;
  91. }
  92. /**
  93. * @notes 签名生成
  94. * @param $url
  95. * @param $http_method
  96. * @param $data
  97. * @param $config
  98. * @return string
  99. * @author ljj
  100. * @date 2022/9/27 4:14 下午
  101. */
  102. public static function token($url,$http_method,$data,$config)
  103. {
  104. $timestamp = time();//请求时间戳
  105. $url_parts = parse_url($url);//获取请求的绝对URL
  106. $nonce = $timestamp.rand('10000','99999');//请求随机串
  107. $body = empty($data) ? '' : json_encode((object)$data);//请求报文主体
  108. $stream_opts = [
  109. "ssl" => [
  110. "verify_peer"=>false,
  111. "verify_peer_name"=>false,
  112. ]
  113. ];
  114. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'],false, stream_context_create($stream_opts)));
  115. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  116. $mch_private_key = file_get_contents($config['key_path'],false, stream_context_create($stream_opts));//密钥
  117. $merchant_id = $config['mch_id'];//商户id
  118. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  119. $message = $http_method."\n".
  120. $canonical_url."\n".
  121. $timestamp."\n".
  122. $nonce."\n".
  123. $body."\n";
  124. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  125. $sign = base64_encode($raw_sign);//签名
  126. $schema = 'WECHATPAY2-SHA256-RSA2048';
  127. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  128. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  129. return $schema.' '.$token;
  130. }
  131. /**
  132. * @notes 发送请求
  133. * @param $url
  134. * @param $data
  135. * @param $token
  136. * @return bool|string
  137. * @author ljj
  138. * @date 2022/9/27 4:15 下午
  139. */
  140. public static function https_request($url,$data,$token)
  141. {
  142. $curl = curl_init();
  143. curl_setopt($curl, CURLOPT_URL, (string)$url);
  144. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  145. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  146. if (!empty($data)){
  147. curl_setopt($curl, CURLOPT_POST, 1);
  148. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  149. }
  150. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  151. //添加请求头
  152. $headers = [
  153. 'Authorization:'.$token,
  154. 'Accept: application/json',
  155. 'Content-Type: application/json; charset=utf-8',
  156. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  157. ];
  158. if(!empty($headers)){
  159. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  160. }
  161. $output = curl_exec($curl);
  162. curl_close($curl);
  163. return $output;
  164. }
  165. /**
  166. * @notes 敏感信息加解密
  167. * @param $str
  168. * @param $config
  169. * @return string
  170. * @throws \Exception
  171. * @author ljj
  172. * @date 2022/9/27 3:53 下午
  173. */
  174. public static function getEncrypt($str,$config)
  175. {
  176. //$str是待加密字符串
  177. $public_key = file_get_contents($config['cert_path']);
  178. $encrypted = '';
  179. if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  180. //base64编码
  181. $sign = base64_encode($encrypted);
  182. } else {
  183. throw new \Exception('encrypt failed');
  184. }
  185. return $sign;
  186. }
  187. /**
  188. * @notes 商家明细单号查询明细单API
  189. * @param $withdrawApply
  190. * @return mixed
  191. * @author ljj
  192. * @date 2022/9/27 5:54 下午
  193. */
  194. public static function details($withdrawApply)
  195. {
  196. // 获取微信配置
  197. $config = WeChatConfigService::getWechatConfigByTerminal($withdrawApply['terminal']);
  198. //请求URL
  199. $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/out-bill-no/'.$withdrawApply['sn'];
  200. //请求方式
  201. $http_method = 'GET';
  202. //请求参数
  203. $data = [];
  204. $token = self::token($url,$http_method,$data,$config);//获取token
  205. $result = self::https_request($url,$data,$token);//发送请求
  206. $result_arr = json_decode($result,true);
  207. return $result_arr;
  208. }
  209. }