PayClient.php 14 KB

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