Notify.php 10 KB

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