V2.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\common\library\payment\gateway\driver\wechat;
  13. use EasyWeChat\Factory;
  14. use EasyWeChat\Payment\Notify\Paid;
  15. use app\common\enum\Client as ClientEnum;
  16. use app\common\library\Log;
  17. use app\common\library\helper;
  18. use cores\traits\ErrorTrait;
  19. use cores\exception\BaseException;
  20. /**
  21. * 微信支付驱动 [V2]
  22. * Class Wechat
  23. * @package app\common\library\payment\gateway\driver
  24. */
  25. class V2
  26. {
  27. use ErrorTrait;
  28. // 统一下单API的返回结果
  29. private array $result;
  30. // 异步通知的请求参数 (由第三方支付发送)
  31. private array $notifyParams;
  32. /**
  33. * 异步通知回调结果
  34. * @var Paid $notifyPaid
  35. */
  36. private Paid $notifyPaid;
  37. /**
  38. * 支付的客户端
  39. * @var string|null
  40. */
  41. protected ?string $client = null;
  42. /**
  43. * 支付配置参数
  44. * @var array
  45. */
  46. protected array $options = [];
  47. /**
  48. * 设置支付配置参数
  49. * @param array $options 配置信息
  50. * @param string $client 下单客户端
  51. * @return static|null
  52. */
  53. public function setOptions(array $options, string $client): ?V2
  54. {
  55. $this->client = $client ?: null;
  56. $this->options = $options;
  57. return $this;
  58. }
  59. /**
  60. * 统一下单API
  61. * @param string $outTradeNo 交易订单号
  62. * @param string $totalFee 实际付款金额
  63. * @param array $extra 附加的数据 (需要携带openid)
  64. * @return bool
  65. * @throws BaseException
  66. */
  67. public function unify(string $outTradeNo, string $totalFee, array $extra = []): bool
  68. {
  69. // 下单的参数
  70. $params = [
  71. 'body' => $outTradeNo,
  72. 'out_trade_no' => $outTradeNo,
  73. 'total_fee' => (int)helper::bcmul($totalFee, 100),
  74. 'notify_url' => $this->notifyUrl(), // 支付结果异步通知地址
  75. 'trade_type' => $this->tradeType(),
  76. ];
  77. // 用户的openid (只有JSAPI支付时需要)
  78. if ($this->tradeType() === 'JSAPI') {
  79. $params[$this->isProvider() ? 'sub_openid' : 'openid'] = $extra['openid'];
  80. }
  81. try {
  82. // 实例化微信支付sdk
  83. $app = $this->getApp();
  84. // 统一下单API
  85. // https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_20&index=1
  86. $unifyResult = $app->order->unify($params);
  87. // 判断请求是否失败
  88. $this->resultError($unifyResult);
  89. // 记录统一下单api返回的数据
  90. $this->result = $unifyResult;
  91. // 生成app支付的配置
  92. if ($this->client === ClientEnum::APP) {
  93. $this->result = $app->jssdk->appConfig($unifyResult['prepay_id']);
  94. }
  95. // 生成jssdk支付的配置
  96. if (in_array($this->client, [ClientEnum::MP_WEIXIN])) {
  97. $this->result = $app->jssdk->bridgeConfig($unifyResult['prepay_id'], false);
  98. }
  99. // 记录商户订单号
  100. $this->result['out_trade_no'] = $outTradeNo;
  101. // 记录日志
  102. Log::append('Wechat-unify', [
  103. 'client' => $this->client,
  104. 'params' => $params,
  105. 'extra' => $extra,
  106. 'result' => $this->result
  107. ]);
  108. return true;
  109. } catch (\Throwable $e) {
  110. $this->throwError('unify', '微信支付API下单失败:' . $e->getMessage());
  111. }
  112. return false;
  113. }
  114. /**
  115. * 交易查询 (主动查询订单支付状态)
  116. * @param string $outTradeNo 交易订单号
  117. * @return array|null
  118. * @throws BaseException
  119. */
  120. public function tradeQuery(string $outTradeNo): ?array
  121. {
  122. try {
  123. // 微信支付订单的查询
  124. // https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_2&index=2
  125. $result = $this->getApp()->order->queryByOutTradeNumber($outTradeNo);
  126. // 判断请求是否失败
  127. $this->resultError($result);
  128. // 记录日志
  129. Log::append('Wechat-tradeQuery', ['outTradeNo' => $outTradeNo, 'result' => $result]);
  130. // 判断订单支付成功
  131. return [
  132. // 支付状态: true成功 false失败
  133. 'paySuccess' => $result['trade_state'] === 'SUCCESS',
  134. // 第三方交易流水号
  135. 'tradeNo' => $result['transaction_id'] ?? ''
  136. ];
  137. } catch (\Throwable $e) {
  138. $this->throwError('tradeQuery', '微信支付交易查询失败:' . $e->getMessage());
  139. }
  140. return null;
  141. }
  142. /**
  143. * 支付成功后的异步通知
  144. * @return bool
  145. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  146. */
  147. public function notify(): bool
  148. {
  149. // 异步通知管理类
  150. $this->notifyPaid = new Paid($this->getApp());
  151. try {
  152. // 异步通知的数据
  153. $this->notifyParams = $this->notifyPaid->getMessage();
  154. // 记录日志
  155. Log::append('Wechat-notify', ['params' => $this->notifyParams]);
  156. // 通信状态是否成功
  157. if ($this->notifyParams['return_code'] !== 'SUCCESS') {
  158. $this->notifyPaidError('通信失败');
  159. return false;
  160. }
  161. // 用户支付失败
  162. if ($this->notifyParams['result_code'] !== 'SUCCESS') {
  163. $this->notifyPaidError('订单支付失败', false);
  164. return false;
  165. }
  166. // 记录日志
  167. Log::append('Wechat-notify', ['message' => '微信异步回调验证成功']);
  168. } catch (\EasyWeChat\Payment\Kernel\Exceptions\InvalidSignException $e) {
  169. // 签名验证错误
  170. $this->notifyPaidError('签名验证错误');
  171. return false;
  172. } catch (\Throwable $e) {
  173. // 其他异常
  174. $this->notifyPaidError('异步通知错误:' . $e->getMessage());
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * 微信支付退款API
  181. * @param string $outTradeNo 第三方交易单号
  182. * @param string $refundAmount 退款金额
  183. * @param array $extra 附加数据 (需要携带订单付款总金额)
  184. * @return bool
  185. * @throws BaseException
  186. */
  187. public function refund(string $outTradeNo, string $refundAmount, array $extra = []): bool
  188. {
  189. try {
  190. // 微信支付订单退款
  191. // https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=9_4&index=4
  192. $refundNumber = time() . '-' . uniqid();
  193. $result = $this->getApp()->refund->byOutTradeNumber(
  194. $outTradeNo,
  195. $refundNumber,
  196. (int)helper::bcmul($extra['totalFee'], 100),
  197. (int)helper::bcmul($refundAmount, 100)
  198. );
  199. // 判断请求是否失败
  200. $this->resultError($result);
  201. // 记录日志
  202. Log::append('Wechat-refund', [
  203. 'outTradeNo' => $outTradeNo,
  204. 'refundAmount' => $refundAmount,
  205. 'result' => $result
  206. ]);
  207. // 请求成功
  208. return true;
  209. } catch (\Throwable $e) {
  210. $this->throwError('refund', '微信退款api请求失败:' . $e->getMessage());
  211. }
  212. return false;
  213. }
  214. /**
  215. * 企业付款到零钱API [已废弃]
  216. * @param string $outTradeNo 交易订单号
  217. * @param string $totalFee 实际付款金额
  218. * @param array $extra 附加的数据 (需要携带openid、desc)
  219. * @return bool
  220. * @throws BaseException
  221. */
  222. public function transfers(string $outTradeNo, string $totalFee, array $extra = []): bool
  223. {
  224. try {
  225. // 请求的参数
  226. $params = [
  227. 'partner_trade_no' => $outTradeNo, // 商户订单号,需保持唯一性(只能是字母或者数字,不能包含有符号)
  228. 'openid' => $extra['openid'], // 用户的openid
  229. 'check_name' => 'NO_CHECK', // NO_CHECK:不校验真实姓名, FORCE_CHECK:强校验真实姓名
  230. // 're_user_name' => '王小帅', // 如果 check_name 设置为FORCE_CHECK,则必填用户真实姓名
  231. 'amount' => (int)helper::bcmul($totalFee, 100), // 企业付款金额,单位为分
  232. 'desc' => $extra['desc'], // 企业付款操作说明信息。必填
  233. ];
  234. // 微信支付订单退款
  235. // https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2
  236. $result = $this->getApp()->transfer->toBalance($params);
  237. // 判断请求是否失败
  238. $this->resultError($result);
  239. // 记录日志
  240. Log::append('Wechat-transfers', ['outTradeNo' => $outTradeNo, 'result' => $result]);
  241. // 请求成功
  242. return true;
  243. } catch (\Throwable $e) {
  244. $this->throwError('transfers', '企业付款到零钱api请求失败:' . $e->getMessage());
  245. }
  246. return false;
  247. }
  248. /**
  249. * 获取异步回调的请求参数
  250. * @return array
  251. */
  252. public function getNotifyParams(): array
  253. {
  254. return [
  255. // 第三方交易流水号
  256. 'tradeNo' => $this->notifyParams['transaction_id']
  257. ];
  258. }
  259. /**
  260. * 返回异步通知结果的输出内容
  261. * @return string
  262. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  263. */
  264. public function getNotifyResponse(): string
  265. {
  266. return $this->notifyPaid->toResponse()->getContent();
  267. }
  268. /**
  269. * 返回统一下单API的结果 (用于前端)
  270. * @return array
  271. * @throws BaseException
  272. */
  273. public function getUnifyResult(): array
  274. {
  275. if (empty($this->result)) {
  276. $this->throwError('getUnifyResult', '当前没有unify结果');
  277. }
  278. // 允许输出的字段 (防止泄露敏感信息)
  279. $result = helper::pick($this->result, [
  280. 'out_trade_no',
  281. 'nonce_str', 'prepay_id', 'sign', 'trade_type', 'mweb_url',
  282. 'appid', 'partnerid', 'noncestr', 'prepayid', 'timestamp', 'package', 'sign',
  283. 'appId', 'timeStamp', 'nonceStr', 'package', 'signType', 'paySign',
  284. ]);
  285. // 当前的时间戳
  286. $result['time_stamp'] = (string)time();
  287. return $result;
  288. }
  289. /**
  290. * 设置异步通知的错误信息
  291. * @param string $error 错误信息
  292. * @param bool $outputFail 是否输出fail信息 (会使微信服务器重复发起通知)
  293. */
  294. private function notifyPaidError(string $error, bool $outputFail = true)
  295. {
  296. $this->error = $error;
  297. $outputFail && $this->notifyPaid->fail($error);
  298. Log::append('Wechat-notify', ['errMessage' => $error]);
  299. }
  300. /**
  301. * 输出错误信息
  302. * @param string $action 当前的操作
  303. * @param string $errMessage 错误信息
  304. * @throws BaseException
  305. */
  306. private function throwError(string $action, string $errMessage)
  307. {
  308. $this->error = $errMessage;
  309. Log::append("Wechat-{$action}", ['errMessage' => $errMessage]);
  310. throwError($errMessage);
  311. }
  312. /**
  313. * 根据客户端选择对应的微信支付方式
  314. * @return string
  315. * @throws BaseException
  316. */
  317. private function tradeType(): string
  318. {
  319. $tradeTypes = [
  320. ClientEnum::H5 => 'MWEB',
  321. ClientEnum::MP_WEIXIN => 'JSAPI',
  322. ClientEnum::APP => 'APP'
  323. ];
  324. if (!isset($tradeTypes[$this->client])) {
  325. $this->throwError('tradeType', '未找到当前客户端适配的微信支付方式');
  326. }
  327. return $tradeTypes[$this->client];
  328. }
  329. /**
  330. * 请求错误时错误信息
  331. * @throws BaseException
  332. */
  333. private function resultError(array $result)
  334. {
  335. // 无请求结果
  336. empty($result) && throwError('API无返回结果');
  337. // 请求失败
  338. if ($result['return_code'] === 'FAIL') {
  339. $this->throwError('resultError', $result['return_msg'] ?: 'return_code 未知错误');
  340. }
  341. if ($result['result_code'] === 'FAIL') {
  342. $this->throwError('resultError', $result['err_code_des'] ?: 'result_code 未知错误');
  343. }
  344. }
  345. /**
  346. * 获取微信支付应用类
  347. * @return \EasyWeChat\Payment\Application
  348. */
  349. private function getApp(): \EasyWeChat\Payment\Application
  350. {
  351. $config = $this->getConfig();
  352. return Factory::payment($config);
  353. }
  354. /**
  355. * 构建微信支付配置
  356. * @return string[]
  357. */
  358. private function getConfig(): array
  359. {
  360. if ($this->isProvider()) {
  361. $config = [
  362. 'app_id' => $this->options['provider']['spAppId'],
  363. 'mch_id' => $this->options['provider']['spMchId'],
  364. 'key' => $this->options['provider']['spApiKey'],
  365. 'cert_path' => $this->options['provider']['spApiclientCertPath'],
  366. 'key_path' => $this->options['provider']['spApiclientKeyPath'],
  367. 'sub_mch_id' => $this->options['provider']['subMchId'],
  368. 'sub_appid' => $this->options['provider']['subAppId'],
  369. ];
  370. } else {
  371. $config = [
  372. 'app_id' => $this->options['normal']['appId'],
  373. 'mch_id' => $this->options['normal']['mchId'],
  374. 'key' => $this->options['normal']['apiKey'],
  375. 'cert_path' => $this->options['normal']['apiclientCertPath'],
  376. 'key_path' => $this->options['normal']['apiclientKeyPath'],
  377. ];
  378. }
  379. // 微信支付异步回调地址
  380. // $config['notify_url'] = $this->notifyUrl();
  381. return $config;
  382. }
  383. /**
  384. * 异步回调地址
  385. * @return string
  386. */
  387. private function notifyUrl(): string
  388. {
  389. // 例如:https://www.xxxx.com/wxpayNoticeV2.php
  390. return base_url() . 'wxpayNoticeV2.php';
  391. }
  392. /**
  393. * 当前是否为服务商模式
  394. * @return bool
  395. */
  396. private function isProvider(): bool
  397. {
  398. return $this->options['mchType'] === 'provider';
  399. }
  400. }