WechatMerchantTransferLogic.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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\admin\logic;
  20. use app\common\enum\NoticeEnum;
  21. use app\common\model\Pay;
  22. use app\common\model\user\User;
  23. use app\common\server\WeChatServer;
  24. use think\facade\Db;
  25. /**
  26. * 功能: 商家转账到零钱
  27. * 用途:商户可以通过该接口同时向多个用户微信零钱进行转账操作。
  28. * 证书:需要
  29. * 请求URL:https://api.mch.weixin.qq.com/v3/transfer/batches
  30. * 失败后一定要用【原来的商户订单号】去重试,不然有可能存在重复支付的风险!!!
  31. * 转账批次单中涉及金额的字段单位为“分”
  32. * 成功受理商家转账请求后,可调用《商家明细单号查询明细单》接口来判断转账明细列表状态
  33. */
  34. class WechatMerchantTransferLogic
  35. {
  36. /**
  37. * @notes 商家转账到零钱
  38. * @param $withdrawApply
  39. * @return array
  40. * @throws \Exception
  41. * @author ljj
  42. * @date 2022/9/27 4:40 下午
  43. */
  44. public static function transfer($withdrawApply)
  45. {
  46. // 微信零钱最小提现金额 1元
  47. if($withdrawApply['left_money'] < 1) {
  48. return [
  49. 'code' => 0,
  50. 'msg' => '扣除手续费后提现金额不能小于1元'
  51. ];
  52. }
  53. // 每天最多可向同一用户付款7次
  54. $count = Db::name('withdraw_apply')
  55. ->whereTime('update_time', 'd') // 今天
  56. ->where('user_id', $withdrawApply['user_id'])
  57. ->where('type', 2) // 微信零钱
  58. ->where('status', '>=', 2) // 提现中、提现成功、提现失败
  59. ->count();
  60. if($count >= 7) {
  61. return [
  62. 'code' => 0,
  63. 'msg' => '同一个用户一天最多可付款7次'
  64. ];
  65. }
  66. // 一个商户默认同一日付款总额限额10万元
  67. $sum = Db::name('withdraw_apply')
  68. ->whereTime('update_time', 'd') // 今天
  69. ->where('type', 2) // 微信零钱
  70. ->where('status', 'in', [2, 3]) // 提现中、提现成功
  71. ->sum('left_money');
  72. $sum = $sum + $withdrawApply['left_money'];
  73. if($sum > 100000) {
  74. return [
  75. 'code' => 0,
  76. 'msg' => '一个商户默认同一日付款总额限额10万元'
  77. ];
  78. }
  79. // 用户授权信息(同一个用户可能有多条,取client最小的一条)
  80. $userAuth = Db::name('user_auth')
  81. ->where('user_id', $withdrawApply['user_id'])
  82. ->order('client', 'asc')
  83. ->where('client', $withdrawApply['client'])
  84. ->find();
  85. if(!$userAuth) {
  86. // 无授权记录
  87. return [
  88. 'code'=> 0,
  89. 'msg' => '查询不到该用户的openid'
  90. ];
  91. }
  92. //获取配置信息
  93. $config = WeChatServer::getPayConfigBySource($userAuth['client'])['config'];
  94. //请求URL
  95. $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills';
  96. //请求方式
  97. $http_method = 'POST';
  98. //请求参数
  99. $data = [
  100. 'appid' => $config['app_id'],
  101. 'out_bill_no' => $withdrawApply['sn'],
  102. 'transfer_scene_id' => '1005',
  103. 'transfer_remark' => '提现',
  104. 'openid' => $userAuth['openid'],
  105. 'transfer_amount' => intval(bcmul($withdrawApply['left_money'], 100)),
  106. 'transfer_scene_report_infos' => [
  107. [ 'info_type' => '岗位类型', 'info_content' => '邀请者' ],
  108. [ 'info_type' => '报酬说明', 'info_content' => '邀请奖励提现' ],
  109. ],
  110. ];
  111. if ($withdrawApply['left_money'] >= 2000) {
  112. if (empty($withdrawApply['real_name'])) {
  113. throw new \Exception('转账金额 >= 2000元,收款用户真实姓名必填');
  114. }
  115. $data['user_name'] = $withdrawApply['real_name'];
  116. }
  117. //获取token
  118. $token = self::token($url,$http_method,$data,$config);
  119. //发送请求
  120. $result = self::https_request($url, json_encode($data),$token);
  121. $result_arr = json_decode($result,true);
  122. if(!isset($result_arr['create_time'])) {
  123. //批次受理失败
  124. throw new \Exception($result_arr['message'] ?? $result['fail_reason'] ?? '零钱提现请求失败');
  125. }
  126. $user = User::find($withdrawApply['user_id']);
  127. //批次受理成功,更新提现申请单为提现中状态
  128. Db::name('withdraw_apply')
  129. ->where('id', $withdrawApply['id'])
  130. ->update([
  131. 'status' => 2, // 提现中
  132. 'update_time' => time(),
  133. 'pay_desc' => $result
  134. ]);
  135. //发送通知
  136. event('Notice', [
  137. 'scene' => NoticeEnum::GET_EARNINGS_NOTICE,
  138. 'mobile' => $user['mobile'],
  139. 'params' => [
  140. 'user_id' => $user['id'],
  141. 'withdraw_money' => bcadd($withdrawApply['left_money'], 0, 2),
  142. 'nickname' => $user['nickname'],
  143. 'withdraw_time' => $withdrawApply['create_time'],
  144. ]
  145. ]);
  146. return [
  147. 'code' => 1,
  148. 'msg' => '零钱提现中'
  149. ];
  150. }
  151. /**
  152. * @notes 签名生成
  153. * @param $url
  154. * @param $http_method
  155. * @param $data
  156. * @param $config
  157. * @return string
  158. * @author ljj
  159. * @date 2022/9/27 4:14 下午
  160. */
  161. public static function token($url,$http_method,$data,$config)
  162. {
  163. $timestamp = time();//请求时间戳
  164. $url_parts = parse_url($url);//获取请求的绝对URL
  165. $nonce = $timestamp.rand('10000','99999');//请求随机串
  166. $body = empty($data) ? '' : json_encode((object)$data);//请求报文主体
  167. $stream_opts = [
  168. "ssl" => [
  169. "verify_peer"=>false,
  170. "verify_peer_name"=>false,
  171. ]
  172. ];
  173. $apiclient_cert_arr = openssl_x509_parse(file_get_contents($config['cert_path'],false, stream_context_create($stream_opts)));
  174. $serial_no = $apiclient_cert_arr['serialNumberHex'];//证书序列号
  175. $mch_private_key = file_get_contents($config['key_path'],false, stream_context_create($stream_opts));//密钥
  176. $merchant_id = $config['mch_id'];//商户id
  177. $canonical_url = ($url_parts['path'] . (!empty($url_parts['query']) ? "?${url_parts['query']}" : ""));
  178. $message = $http_method."\n".
  179. $canonical_url."\n".
  180. $timestamp."\n".
  181. $nonce."\n".
  182. $body."\n";
  183. openssl_sign($message, $raw_sign, $mch_private_key, 'sha256WithRSAEncryption');
  184. $sign = base64_encode($raw_sign);//签名
  185. $schema = 'WECHATPAY2-SHA256-RSA2048';
  186. $token = sprintf('mchid="%s",nonce_str="%s",timestamp="%d",serial_no="%s",signature="%s"',
  187. $merchant_id, $nonce, $timestamp, $serial_no, $sign);//微信返回token
  188. return $schema.' '.$token;
  189. }
  190. /**
  191. * @notes 发送请求
  192. * @param $url
  193. * @param $data
  194. * @param $token
  195. * @return bool|string
  196. * @author ljj
  197. * @date 2022/9/27 4:15 下午
  198. */
  199. public static function https_request($url,$data,$token)
  200. {
  201. $curl = curl_init();
  202. curl_setopt($curl, CURLOPT_URL, (string)$url);
  203. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  204. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  205. if (!empty($data)){
  206. curl_setopt($curl, CURLOPT_POST, 1);
  207. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  208. }
  209. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  210. //添加请求头
  211. $headers = [
  212. 'Authorization:'.$token,
  213. 'Accept: application/json',
  214. 'Content-Type: application/json; charset=utf-8',
  215. 'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
  216. ];
  217. if(!empty($headers)){
  218. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  219. }
  220. $output = curl_exec($curl);
  221. curl_close($curl);
  222. return $output;
  223. }
  224. /**
  225. * @notes 敏感信息加解密
  226. * @param $str
  227. * @param $config
  228. * @return string
  229. * @throws \Exception
  230. * @author ljj
  231. * @date 2022/9/27 3:53 下午
  232. */
  233. public static function getEncrypt($str,$config)
  234. {
  235. //$str是待加密字符串
  236. $public_key = file_get_contents($config['cert_path']);
  237. $encrypted = '';
  238. if (openssl_public_encrypt($str, $encrypted, $public_key, OPENSSL_PKCS1_OAEP_PADDING)) {
  239. //base64编码
  240. $sign = base64_encode($encrypted);
  241. } else {
  242. throw new \Exception('encrypt failed');
  243. }
  244. return $sign;
  245. }
  246. /**
  247. * @notes 商家明细单号查询明细单API
  248. * @param $withdrawApply
  249. * @return mixed
  250. * @author ljj
  251. * @date 2022/9/27 5:54 下午
  252. */
  253. public static function details($withdrawApply)
  254. {
  255. $userAuth = Db::name('user_auth')
  256. ->where('user_id', $withdrawApply['user_id'])
  257. ->where('client', $withdrawApply['client'])
  258. ->order('client', 'asc')
  259. ->find();
  260. if(!$userAuth) {
  261. // 无授权记录
  262. return [
  263. 'code'=> 0,
  264. 'msg' => '查询不到该用户的openid'
  265. ];
  266. }
  267. //获取配置信息
  268. $pay = Pay::where(['code' => 'wechat'])->find()->toArray();
  269. $config = [
  270. 'mch_id' => $pay['config']['mch_id'] ?? '',
  271. 'cert_path' => dirname(__FILE__, 2).'/../../public/'.$pay['config']['apiclient_cert'] ?? '',
  272. 'key_path' => dirname(__FILE__, 2).'/../../public/'.$pay['config']['apiclient_key'] ?? '',
  273. ];
  274. //请求URL
  275. $url = 'https://api.mch.weixin.qq.com/v3/fund-app/mch-transfer/transfer-bills/transfer-bill-no/'.$withdrawApply['sn'];
  276. //请求方式
  277. $http_method = 'GET';
  278. //请求参数
  279. $data = [];
  280. $token = self::token($url,$http_method,$data,$config);//获取token
  281. $result = self::https_request($url,$data,$token);//发送请求
  282. $result_arr = json_decode($result,true);
  283. return $result_arr;
  284. }
  285. }