PayClient.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace crmeb\services\easywechat\v3pay;
  14. use crmeb\exceptions\PayException;
  15. use crmeb\services\wechat\Payment;
  16. use EasyWeChat\Payment\Order;
  17. /**
  18. * v3支付
  19. * Class PayClient
  20. * @package crmeb\services\easywechat\v3pay
  21. */
  22. class PayClient extends BaseClient
  23. {
  24. //app支付
  25. const API_APP_APY_URL = 'v3/pay/transactions/app';
  26. //app支付-服务商模式
  27. const API_APP_APY_PARTNER_URL = 'v3/pay/partner/transactions/app';
  28. //Native下单API
  29. const API_NATIVE_URL = 'v3/pay/transactions/native';
  30. //Native下单API-服务商模式
  31. const API_NATIVE_PARTNER_URL = 'v3/pay/partner/transactions/native';
  32. //h5支付接口
  33. const API_H5_URL = 'v3/pay/transactions/h5';
  34. //h5支付接口-服务商模式
  35. const API_H5_PARTNER_URL = 'v3/pay/partner/transactions/h5';
  36. //jsapi支付接口
  37. const API_JSAPI_URL = 'v3/pay/transactions/jsapi';
  38. //jsapi支付接口-服务商模式
  39. const API_JSAPI_PARTNER_URL = 'v3/pay/partner/transactions/jsapi';
  40. //发起商家转账API
  41. const API_BATCHES_URL = 'v3/transfer/batches';
  42. //退款
  43. const API_REFUND_URL = 'v3/refund/domestic/refunds';
  44. //退款查询接口
  45. const API_REFUND_QUERY_URL = 'v3/refund/domestic/refunds/{out_refund_no}';
  46. /**
  47. * @var string
  48. */
  49. protected $type = Order::JSAPI;
  50. /**
  51. * @param string $type
  52. * @return $this
  53. * @author 等风来
  54. * @email 136327134@qq.com
  55. * @date 2023/2/10
  56. */
  57. public function setType(string $type)
  58. {
  59. $this->type = $type;
  60. return $this;
  61. }
  62. /**
  63. * 公众号jsapi支付下单
  64. * @param string $outTradeNo
  65. * @param string $total
  66. * @param string $description
  67. * @param string $attach
  68. * @return mixed
  69. */
  70. public function jsapiPay(string $openid, string $outTradeNo, string $total, string $description, string $attach)
  71. {
  72. $appId = $this->app['config']['wechat']['appid'];
  73. $res = $this->pay('jsapi', $appId, $outTradeNo, $total, $description, $attach, ['openid' => $openid]);
  74. return $this->configForJSSDKPayment($appId, $res['prepay_id']);
  75. }
  76. /**
  77. * 小程序支付
  78. * @param string $outTradeNo
  79. * @param string $total
  80. * @param string $description
  81. * @param string $attach
  82. * @return array|false|string
  83. */
  84. public function miniprogPay(string $openid, string $outTradeNo, string $total, string $description, string $attach)
  85. {
  86. $appId = $this->app['config']['miniprog']['appid'];
  87. $res = $this->pay('jsapi', $appId, $outTradeNo, $total, $description, $attach, ['openid' => $openid]);
  88. return $this->configForJSSDKPayment($appId, $res['prepay_id']);
  89. }
  90. /**
  91. * APP支付下单
  92. * @param string $outTradeNo
  93. * @param string $total
  94. * @param string $description
  95. * @param string $attach
  96. * @return mixed
  97. */
  98. public function appPay(string $outTradeNo, string $total, string $description, string $attach)
  99. {
  100. $res = $this->pay('app', $this->app['config']['app']['appid'], $outTradeNo, $total, $description, $attach);
  101. return $this->configForAppPayment($res['prepay_id']);
  102. }
  103. /**
  104. * native支付下单
  105. * @param string $outTradeNo
  106. * @param string $total
  107. * @param string $description
  108. * @param string $attach
  109. * @return mixed
  110. */
  111. public function nativePay(string $outTradeNo, string $total, string $description, string $attach)
  112. {
  113. return $this->pay('native', $this->app['config']['web']['appid'], $outTradeNo, $total, $description, $attach);
  114. }
  115. /**
  116. * h5支付下单
  117. * @param string $outTradeNo
  118. * @param string $total
  119. * @param string $description
  120. * @param string $attach
  121. * @return mixed
  122. */
  123. public function h5Pay(string $outTradeNo, string $total, string $description, string $attach)
  124. {
  125. return $this->pay('h5', $this->app['config']['wechat']['appid'], $outTradeNo, $total, $description, $attach);
  126. }
  127. /**
  128. * 下单
  129. * @param string $type
  130. * @param string $appid
  131. * @param string $outTradeNo
  132. * @param string $total
  133. * @param string $description
  134. * @param string $attach
  135. * @param array $payer
  136. * @return mixed
  137. */
  138. public function pay(string $type, string $appid, string $outTradeNo, string $total, string $description, string $attach, array $payer = [])
  139. {
  140. $totalFee = (int)bcmul($total, '100');
  141. $data = [
  142. 'appid' => $appid,
  143. 'mchid' => $this->app['config']['v3_payment']['mchid'],
  144. 'out_trade_no' => $outTradeNo,
  145. 'attach' => $attach,
  146. 'description' => $description,
  147. 'notify_url' => $this->app['config']['v3_payment']['notify_url'],
  148. 'amount' => [
  149. 'total' => $totalFee,
  150. 'currency' => 'CNY'
  151. ],
  152. ];
  153. if ($payer) {
  154. $data['payer'] = $payer;
  155. }
  156. //服务商支付模式
  157. if ($this->app['config']['v3_payment']['mer_type']) {
  158. $mchid = $data['mchid'];
  159. $appid = $data['appid'];
  160. unset($data['mchid'], $data['appid'], $data['payer']);
  161. $data['sp_appid'] = $this->app['config']['v3_payment']['sp_appid'];
  162. $data['sp_mchid'] = $mchid;
  163. $data['sub_mchid'] = $this->app['config']['v3_payment']['sub_mch_id'];
  164. if (!empty($payer['openid'])) {
  165. $data['payer']['sub_openid'] = $payer['openid'];
  166. $data['sub_appid'] = $appid;
  167. }
  168. $url = '';
  169. switch ($type) {
  170. case 'h5':
  171. $url = self::API_H5_PARTNER_URL;
  172. $data['scene_info'] = [
  173. 'payer_client_ip' => request()->ip(),
  174. 'h5_info' => [
  175. 'type' => 'Wap'
  176. ]
  177. ];
  178. break;
  179. case 'native':
  180. $url = self::API_NATIVE_PARTNER_URL;
  181. break;
  182. case 'app':
  183. $url = self::API_APP_APY_PARTNER_URL;
  184. break;
  185. case 'jsapi':
  186. $url = self::API_JSAPI_PARTNER_URL;
  187. break;
  188. }
  189. } else {
  190. $url = '';
  191. switch ($type) {
  192. case 'h5':
  193. $url = self::API_H5_URL;
  194. $data['scene_info'] = [
  195. 'payer_client_ip' => request()->ip(),
  196. 'h5_info' => [
  197. 'type' => 'Wap'
  198. ]
  199. ];
  200. break;
  201. case 'native':
  202. $url = self::API_NATIVE_URL;
  203. break;
  204. case 'app':
  205. $url = self::API_APP_APY_URL;
  206. break;
  207. case 'jsapi':
  208. $url = self::API_JSAPI_URL;
  209. break;
  210. }
  211. }
  212. if (!$url) {
  213. throw new PayException('缺少请求地址');
  214. }
  215. $res = $this->request($url, 'POST', ['json' => $data]);
  216. if (!$res) {
  217. throw new PayException('微信支付:下单失败');
  218. }
  219. if (isset($res['code']) && isset($res['message'])) {
  220. throw new PayException($res['message']);
  221. }
  222. return $res;
  223. }
  224. /**
  225. * 发起商家转账API
  226. * @param string $outBatchNo
  227. * @param string $amount
  228. * @param string $batchName
  229. * @param string $remark
  230. * @param array $transferDetailList
  231. * @return mixed
  232. */
  233. public function batches(string $outBatchNo, string $amount, string $batchName, string $remark, array $transferDetailList)
  234. {
  235. $totalFee = '0';
  236. $amount = bcadd($amount, '0', 2);
  237. foreach ($transferDetailList as &$item) {
  238. if ($item['transfer_amount'] >= 2000 && empty($item['user_name'])) {
  239. throw new PayException('明细金额大于等于2000时,收款人姓名必须填写');
  240. }
  241. $totalFee = bcadd($totalFee, $item['transfer_amount'], 2);
  242. $item['transfer_amount'] = (int)bcmul($item['transfer_amount'], 100, 0);
  243. if (isset($item['user_name'])) {
  244. $item['user_name'] = $this->encryptor($item['user_name']);
  245. }
  246. }
  247. if ($totalFee !== $amount) {
  248. throw new PayException('转账明细金额总和和转账总金额不一致');
  249. }
  250. $amount = (int)bcmul($amount, 100, 0);
  251. $appid = null;
  252. if ($this->type === Order::JSAPI) {
  253. $appid = $this->app['config']['wechat']['appid'];
  254. } else if ($this->type === 'mini') {
  255. $appid = $this->app['config']['miniprog']['appid'];
  256. } else if ($this->type === Order::APP) {
  257. $appid = $this->app['config']['app']['appid'];
  258. }
  259. if (!$appid) {
  260. throw new PayException('暂时只支持微信用户、小程序用户、APP微信登录用户提现');
  261. }
  262. $data = [
  263. 'appid' => $appid,
  264. 'out_batch_no' => $outBatchNo,
  265. 'batch_name' => $batchName,
  266. 'batch_remark' => $remark,
  267. 'total_amount' => $amount,
  268. 'total_num' => count($transferDetailList),
  269. 'transfer_detail_list' => $transferDetailList
  270. ];
  271. $res = $this->request(self::API_BATCHES_URL, 'POST', ['json' => $data]);
  272. if (!$res) {
  273. throw new PayException('微信支付:发起商家转账失败');
  274. }
  275. if (isset($res['code']) && isset($res['message'])) {
  276. throw new PayException($res['message']);
  277. }
  278. return $res;
  279. }
  280. /**
  281. * 退款
  282. * @param string $outTradeNo
  283. * @param array $options
  284. * @return mixed
  285. */
  286. public function refund(string $outTradeNo, array $options = [])
  287. {
  288. if (!isset($options['pay_price'])) {
  289. throw new PayException(400730);
  290. }
  291. $totalFee = floatval(bcmul($options['pay_price'], 100, 0));
  292. $refundFee = isset($options['refund_price']) ? floatval(bcmul($options['refund_price'], 100, 0)) : null;
  293. $refundReason = $options['desc'] ?? '';
  294. $refundNo = $options['refund_id'] ?? $outTradeNo;
  295. /*仅针对老资金流商户使用
  296. REFUND_SOURCE_UNSETTLED_FUNDS---未结算资金退款(默认使用未结算资金退款)
  297. REFUND_SOURCE_RECHARGE_FUNDS---可用余额退款
  298. */
  299. $refundAccount = $opt['refund_account'] ?? 'AVAILABLE';
  300. $data = [
  301. 'transaction_id' => $outTradeNo,
  302. 'out_refund_no' => $refundNo,
  303. 'amount' => [
  304. 'refund' => (int)$refundFee,
  305. 'currency' => 'CNY',
  306. 'total' => (int)$totalFee
  307. ],
  308. 'funds_account' => $refundAccount
  309. ];
  310. if ($refundReason) {
  311. $data['reason'] = $refundReason;
  312. }
  313. //服务商支付退款
  314. $merType = $this->app['config']['v3_payment']['mer_type'];
  315. if ($merType) {
  316. $data['sub_mchid'] = $this->app['config']['v3_payment']['sub_mch_id'];
  317. }
  318. $res = $this->request(self::API_REFUND_URL, 'POST', ['json' => $data]);
  319. if (!$res) {
  320. throw new PayException('微信支付:发起退款失败');
  321. }
  322. if (isset($res['code']) && isset($res['message'])) {
  323. throw new PayException($res['message']);
  324. }
  325. return $res;
  326. }
  327. /**
  328. * 查询退款
  329. * @param string $outRefundNo
  330. * @return mixed
  331. */
  332. public function queryRefund(string $outRefundNo)
  333. {
  334. $res = $this->request($this->getApiUrl(self::API_REFUND_QUERY_URL, ['out_refund_no'], [$outRefundNo]), 'GET');
  335. if (!$res) {
  336. throw new PayException(500000);
  337. }
  338. if (isset($res['code']) && isset($res['message'])) {
  339. throw new PayException($res['message']);
  340. }
  341. return $res;
  342. }
  343. /**
  344. * jsapi支付
  345. * @param string $appid
  346. * @param string $prepayId
  347. * @param bool $json
  348. * @return array|false|string
  349. */
  350. public function configForPayment(string $appid, string $prepayId, bool $json = true)
  351. {
  352. $params = [
  353. 'appId' => $appid,
  354. 'timeStamp' => strval(time()),
  355. 'nonceStr' => uniqid(),
  356. 'package' => "prepay_id=$prepayId",
  357. 'signType' => 'RSA',
  358. ];
  359. $message = $params['appId'] . "\n" .
  360. $params['timeStamp'] . "\n" .
  361. $params['nonceStr'] . "\n" .
  362. $params['package'] . "\n";
  363. openssl_sign($message, $raw_sign, $this->getPrivateKey(), 'sha256WithRSAEncryption');
  364. $sign = base64_encode($raw_sign);
  365. $params['paySign'] = $sign;
  366. return $json ? json_encode($params) : $params;
  367. }
  368. /**
  369. * Generate app payment parameters.
  370. * @param string $prepayId
  371. * @return array
  372. */
  373. public function configForAppPayment(string $prepayId): array
  374. {
  375. $params = [
  376. 'appid' => $this->app['config']['app']['appid'],
  377. 'partnerid' => $this->app['config']['v3_payment']['mchid'],
  378. 'prepayid' => $prepayId,
  379. 'noncestr' => uniqid(),
  380. 'timestamp' => time(),
  381. 'package' => 'Sign=WXPay',
  382. ];
  383. $message = $params['appid'] . "\n" .
  384. $params['timestamp'] . "\n" .
  385. $params['noncestr'] . "\n" .
  386. $params['prepayid'] . "\n";
  387. openssl_sign($message, $raw_sign, $this->getPrivateKey(), 'sha256WithRSAEncryption');
  388. $sign = base64_encode($raw_sign);
  389. $params['sign'] = $sign;
  390. return $params;
  391. }
  392. /**
  393. * 小程序支付
  394. * @param string $appid
  395. * @param string $prepayId
  396. * @return array|false|string
  397. */
  398. public function configForJSSDKPayment(string $appid, string $prepayId)
  399. {
  400. $config = $this->configForPayment($appid, $prepayId, false);
  401. $config['timestamp'] = $config['timeStamp'];
  402. unset($config['timeStamp']);
  403. return $config;
  404. }
  405. /**
  406. * @param $callback
  407. * @return \think\Response
  408. */
  409. public function handleNotify($callback)
  410. {
  411. $request = request();
  412. $success = $request->post('event_type') === 'TRANSACTION.SUCCESS';
  413. $data = $this->decrypt($request->post('resource', []));
  414. $handleResult = call_user_func_array($callback, [json_decode($data), $success]);
  415. if (is_bool($handleResult) && $handleResult) {
  416. $response = [
  417. 'code' => 'SUCCESS',
  418. 'message' => 'OK',
  419. ];
  420. } else {
  421. $response = [
  422. 'code' => 'FAIL',
  423. 'message' => $handleResult,
  424. ];
  425. }
  426. return response($response, 200, [], 'json');
  427. }
  428. }