Notify.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2025 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\api\service;
  13. use app\api\model\Payment as PaymentModel;
  14. use app\api\model\PaymentTrade as PaymentTradeModel;
  15. use app\api\model\PaymentTemplate as PaymentTemplateModel;
  16. use app\api\service\order\PaySuccess as OrderPaySuccessService;
  17. use app\api\service\recharge\PaySuccess as RechargePaySuccessService;
  18. use app\common\enum\OrderType as OrderTypeEnum;
  19. use app\common\enum\payment\Method as PaymentMethodEnum;
  20. use app\common\library\Log;
  21. use app\common\library\helper;
  22. use app\common\library\payment\gateway\Driver;
  23. use app\common\library\payment\Facade as PaymentFacade;
  24. use app\common\library\payment\gateway\driver\wechat\V3 as WechatPaymentV3;
  25. use cores\exception\BaseException;
  26. /**
  27. * 服务类:第三方支付异步通知
  28. * Class Notify
  29. * @package app\api\service
  30. */
  31. class Notify
  32. {
  33. // 异步通知的请求参数 (由第三方支付发送)
  34. private array $notifyParams;
  35. /**
  36. * 支付成功异步通知 (微信支付V2)
  37. * @return string
  38. */
  39. public function wechatV2(): string
  40. {
  41. try {
  42. // 获取第三方交易记录
  43. $tradeInfo = $this->getTradeInfo(PaymentMethodEnum::WECHAT, 'v2');
  44. // 构建支付模块
  45. $Payment = $this->getPayment($tradeInfo);
  46. // 验证异步通知参数是否合法
  47. if (!$Payment->notify()) {
  48. throwError($Payment->getError() ?: '微信支付V2异步通知验证未通过');
  49. }
  50. // 订单支付成功事件
  51. $this->orderPaySuccess($tradeInfo, $Payment->getNotifyParams());
  52. } catch (\Throwable $e) {
  53. // 记录错误日志
  54. Log::append('Notify-wechat', ['errMessage' => $e->getMessage()]);
  55. }
  56. return isset($Payment) ? $Payment->getNotifyResponse() : 'FAIL';
  57. }
  58. /**
  59. * 支付成功异步通知 (微信支付V3)
  60. * @return string
  61. */
  62. public function wechatV3(): string
  63. {
  64. try {
  65. // 微信支付V3异步回调验证
  66. $this->wechatV3Notify();
  67. // 获取异步回调的请求参数
  68. $notifyParams = $this->getNotifyParams();
  69. // 获取第三方交易记录
  70. $tradeInfo = PaymentTradeModel::detailByOutTradeNo($notifyParams['outTradeNo']);
  71. // 订单支付成功事件
  72. $this->orderPaySuccess($tradeInfo, $notifyParams);
  73. } catch (\Throwable $e) {
  74. // 记录错误日志
  75. Log::append('Notify-wechat', ['errMessage' => $e->getMessage()]);
  76. }
  77. return '';
  78. }
  79. /**
  80. * 微信支付V3异步回调验证
  81. * @return void
  82. * @throws BaseException
  83. */
  84. private function wechatV3Notify()
  85. {
  86. // 通过微信支付v3平台证书序号或微信支付公钥ID 获取支付模板
  87. $platformCertificateSerialOrPublicKeyId = \request()->header('wechatpay-serial');
  88. $templateInfo = PaymentTemplateModel::findByWechatpaySerial($platformCertificateSerialOrPublicKeyId);
  89. empty($templateInfo) && throwError("未找到该平台证书序号或微信支付公钥ID:$platformCertificateSerialOrPublicKeyId");
  90. // 从支付模板中取出v3apikey 用于解密异步通知的密文
  91. $apiV3Key = $templateInfo['config']['wechat']['mchType'] === 'provider'
  92. ? $templateInfo['config']['wechat']['provider']['spApiKey']
  93. : $templateInfo['config']['wechat']['normal']['apiKey'];
  94. // 获取「微信支付平台证书」或者「微信支付平台公钥」的路径
  95. $platformCertificateOrPublicKeyFilePath = $this->getPlatformCertificateOrPublicKeyFilePath($templateInfo);
  96. // 验证异步通知参数是否合法
  97. $V3 = new WechatPaymentV3();
  98. if (!$V3->notify($apiV3Key, $platformCertificateOrPublicKeyFilePath)) {
  99. throwError($V3->getError() ?: '异步通知验证未通过');
  100. }
  101. // 获取异步回调的请求参数
  102. $this->notifyParams = $V3->getNotifyParams();
  103. }
  104. /**
  105. * 获取异步回调的请求参数
  106. * @return array
  107. */
  108. public function getNotifyParams(): array
  109. {
  110. return $this->notifyParams;
  111. }
  112. /**
  113. * 获取「微信支付平台证书」或者「微信支付平台公钥」的路径
  114. * @param $templateInfo
  115. * @return false|string
  116. */
  117. private function getPlatformCertificateOrPublicKeyFilePath($templateInfo)
  118. {
  119. // $fileName = $templateInfo['config']['wechat'][$templateInfo['config']['wechat']['mchType']]['platformCert'];
  120. $mchType = $templateInfo['config']['wechat']['mchType'];
  121. $field1 = $mchType == 'normal' ? 'signatureMethod' : 'spSignatureMethod';
  122. $field2 = $mchType == 'normal' ? 'publicKey' : 'spPublicKey';
  123. $fileName = $templateInfo['config']['wechat'][$mchType][$field1] == 'publicKey'
  124. ? $templateInfo['config']['wechat'][$mchType][$field2]
  125. : $templateInfo['config']['wechat'][$mchType]['platformCert'];
  126. return PaymentTemplateModel::realPathCertFile(
  127. PaymentMethodEnum::WECHAT, $fileName, $templateInfo['store_id']
  128. );
  129. }
  130. /**
  131. * 支付成功异步通知 (支付宝)
  132. * @return string
  133. */
  134. public function alipay(): string
  135. {
  136. try {
  137. // 获取第三方交易记录
  138. $tradeInfo = $this->getTradeInfo(PaymentMethodEnum::ALIPAY);
  139. // 构建支付模块
  140. $Payment = $this->getPayment($tradeInfo);
  141. // 验证异步通知参数是否合法
  142. if (!$Payment->notify()) {
  143. throwError($Payment->getError() ?: '支付宝异步通知验证未通过');
  144. }
  145. // 订单支付成功事件
  146. $this->orderPaySuccess($tradeInfo, $Payment->getNotifyParams());
  147. } catch (\Throwable $e) {
  148. // 记录错误日志
  149. Log::append('Notify-alipay', ['errMessage' => $e->getMessage()]);
  150. }
  151. return isset($Payment) ? $Payment->getNotifyResponse() : 'FAIL';
  152. }
  153. /**
  154. * 订单支付成功事件
  155. * @param PaymentTradeModel $tradeInfo
  156. * @param array $paymentData 第三方支付异步回调的
  157. */
  158. private function orderPaySuccess(PaymentTradeModel $tradeInfo, array $paymentData)
  159. {
  160. // 记录日志
  161. Log::append('Notify-orderPaySucces', [
  162. 'orderType' => OrderTypeEnum::data()[$tradeInfo['order_type']]['name'],
  163. 'tradeInfo' => $tradeInfo->toArray(),
  164. ]);
  165. try {
  166. // 订单支付成功业务处理 (商城订单)
  167. if ($tradeInfo['order_type'] == OrderTypeEnum::ORDER) {
  168. $service = new OrderPaySuccessService;
  169. $service->setOrderNo($tradeInfo['order_no'])
  170. ->setMethod($tradeInfo['pay_method'])
  171. ->setTradeId($tradeInfo['trade_id'])
  172. ->setPaymentData($paymentData)
  173. ->handle();
  174. }
  175. // 订单支付成功业务处理 (余额充值订单)
  176. if ($tradeInfo['order_type'] == OrderTypeEnum::RECHARGE) {
  177. $service = new RechargePaySuccessService;
  178. $service->setOrderNo($tradeInfo['order_no'])
  179. ->setMethod($tradeInfo['pay_method'])
  180. ->setTradeId($tradeInfo['trade_id'])
  181. ->setPaymentData($paymentData)
  182. ->handle();
  183. }
  184. Log::append('Notify-orderPaySucces', ['message' => '订单支付成功']);
  185. } catch (\Throwable $e) {
  186. // 记录错误日志
  187. Log::append('Notify-orderPaySucces', ['errMessage' => $e->getMessage()]);
  188. }
  189. }
  190. /**
  191. * 获取当前异步请求参数中的交易订单号
  192. * @param string $method 支付方式
  193. * @param string $wxapyVersion 微信支付版本号 v2或v3
  194. * @return string|null
  195. */
  196. private function getOutTradeNo(string $method, string $wxapyVersion = 'v2'): ?string
  197. {
  198. if ($method === PaymentMethodEnum::WECHAT) {
  199. if ($wxapyVersion === 'v2') {
  200. $xml = \file_get_contents('php://input');
  201. $data = helper::xmlToArray($xml);
  202. return $data['out_trade_no'];
  203. }
  204. if ($wxapyVersion === 'v3') {
  205. }
  206. }
  207. if ($method === PaymentMethodEnum::ALIPAY) {
  208. return \request()->post('out_trade_no');
  209. }
  210. return null;
  211. }
  212. /**
  213. * 获取第三方交易记录
  214. * @param string $method 支付方式
  215. * @param string $wxapyVersion 微信支付版本号 v2或v3
  216. * @return PaymentTradeModel|null
  217. * @throws BaseException
  218. */
  219. private function getTradeInfo(string $method, string $wxapyVersion = 'v2'): ?PaymentTradeModel
  220. {
  221. // 获取第三方交易记录
  222. $outTradeNo = $this->getOutTradeNo($method, $wxapyVersion);
  223. return PaymentTradeModel::detailByOutTradeNo($outTradeNo);
  224. }
  225. /**
  226. * 获取支付模块
  227. * @param PaymentTradeModel $tradeInfo 第三方交易记录
  228. * @return Driver|null
  229. * @throws BaseException
  230. * @throws \think\db\exception\DataNotFoundException
  231. * @throws \think\db\exception\DbException
  232. * @throws \think\db\exception\ModelNotFoundException
  233. */
  234. private function getPayment(PaymentTradeModel $tradeInfo): ?Driver
  235. {
  236. // 获取支付方式的配置信息
  237. $options = $this->getPaymentConfig($tradeInfo['pay_method'], $tradeInfo['client'], $tradeInfo['store_id']);
  238. // 构建支付模块
  239. return PaymentFacade::store($tradeInfo['pay_method'])->setOptions($options, $tradeInfo['client']);
  240. }
  241. /**
  242. * 获取支付方式的配置信息
  243. * @param string $method 支付方式
  244. * @param string $client 下单客户端
  245. * @return mixed
  246. * @throws BaseException
  247. * @throws \think\db\exception\DataNotFoundException
  248. * @throws \think\db\exception\DbException
  249. * @throws \think\db\exception\ModelNotFoundException
  250. */
  251. private function getPaymentConfig(string $method, string $client, int $storeId = null)
  252. {
  253. $PaymentModel = new PaymentModel;
  254. $templateInfo = $PaymentModel->getPaymentInfo($method, $client, $storeId);
  255. return $templateInfo['template']['config'][$method];
  256. }
  257. }