AliPayService.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services;
  12. use Alipay\EasySDK\Payment\Wap\Models\AlipayTradeWapPayResponse;
  13. use app\services\pay\PayServices;
  14. use crmeb\utils\Hook;
  15. use think\facade\Event;
  16. use think\facade\Log;
  17. use think\facade\Route as Url;
  18. use Alipay\EasySDK\Kernel\Config;
  19. use Alipay\EasySDK\Kernel\Factory;
  20. use crmeb\exceptions\PayException;
  21. use app\services\pay\PayNotifyServices;
  22. use Alipay\EasySDK\Kernel\Util\ResponseChecker;
  23. /**
  24. * Class AliPayService
  25. * @package crmeb\services
  26. */
  27. class AliPayService
  28. {
  29. /**
  30. * 配置
  31. * @var array
  32. */
  33. protected $config = [
  34. 'appId' => '',
  35. 'merchantPrivateKey' => '',//应用私钥
  36. 'alipayPublicKey' => '',//支付宝公钥
  37. 'notifyUrl' => '',//可设置异步通知接收服务地址
  38. 'encryptKey' => '',//可设置AES密钥,调用AES加解密相关接口时需要(可选)
  39. ];
  40. /**
  41. * @var ResponseChecker
  42. */
  43. protected $response;
  44. /**
  45. * @var static
  46. */
  47. protected static $instance;
  48. /**
  49. * AliPayService constructor.
  50. * @param array $config
  51. */
  52. protected function __construct(array $config = [])
  53. {
  54. if (!$config) {
  55. $config = [
  56. 'appId' => sys_config('ali_pay_appid'),
  57. 'merchantPrivateKey' => sys_config('alipay_merchant_private_key'),
  58. 'alipayPublicKey' => sys_config('alipay_public_key'),
  59. 'notifyUrl' => sys_config('site_url') . Url::buildUrl('/api/pay/notify/alipay'),
  60. ];
  61. }
  62. $this->config = array_merge($this->config, $config);
  63. $this->initialize();
  64. $this->response = new ResponseChecker();
  65. }
  66. /**
  67. * 实例化
  68. * @param array $config
  69. * @return static
  70. */
  71. public static function instance(array $config = [])
  72. {
  73. if (is_null(self::$instance)) {
  74. self::$instance = new static($config);
  75. }
  76. return self::$instance;
  77. }
  78. /**
  79. * 初始化
  80. */
  81. protected function initialize()
  82. {
  83. Factory::setOptions($this->getOptions());
  84. }
  85. /**
  86. * 设置配置
  87. * @return Config
  88. */
  89. protected function getOptions()
  90. {
  91. $options = new Config();
  92. $options->protocol = 'https';
  93. $options->gatewayHost = 'openapi.alipay.com';
  94. $options->signType = 'RSA2';
  95. $options->appId = $this->config['appId'];
  96. // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
  97. $options->merchantPrivateKey = $this->config['merchantPrivateKey'];
  98. //注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可
  99. $options->alipayPublicKey = $this->config['alipayPublicKey'];
  100. //可设置异步通知接收服务地址(可选)
  101. $options->notifyUrl = $this->config['notifyUrl'];
  102. //可设置AES密钥,调用AES加解密相关接口时需要(可选)
  103. if ($this->config['encryptKey']) {
  104. $options->encryptKey = $this->config['encryptKey'];
  105. }
  106. return $options;
  107. }
  108. /**
  109. * 创建订单
  110. * @param string $title 商品名称
  111. * @param string $orderId 订单号
  112. * @param string $totalAmount 支付金额
  113. * @param string $passbackParams 备注
  114. * @param string $quitUrl 同步跳转地址
  115. * @param string $siteUrl
  116. * @param bool $isCode
  117. * @return AlipayTradeWapPayResponse
  118. */
  119. public function create(string $title, string $orderId, string $totalAmount, string $passbackParams, string $quitUrl = '', string $siteUrl = '', bool $isCode = false)
  120. {
  121. $title = trim($title);
  122. try {
  123. if ($isCode) {
  124. //二维码支付
  125. $result = Factory::payment()->faceToFace()->optional('passback_params', $passbackParams)->precreate($title, $orderId, $totalAmount);
  126. } else if (request()->isApp()) {
  127. //app支付
  128. $result = Factory::payment()->app()->optional('passback_params', $passbackParams)->pay($title, $orderId, $totalAmount);
  129. } else {
  130. //h5支付
  131. $result = Factory::payment()->wap()->optional('passback_params', $passbackParams)->pay($title, $orderId, $totalAmount, $quitUrl, $siteUrl);
  132. }
  133. if ($this->response->success($result)) {
  134. return $result->body ?? $result;
  135. } else {
  136. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  137. }
  138. } catch (\Exception $e) {
  139. throw new PayException($e->getMessage());
  140. }
  141. }
  142. /**
  143. * 订单退款
  144. * @param string $outTradeNo 订单号
  145. * @param string $totalAmount 退款金额
  146. * @param string $refund_id 退款单号
  147. * @return \Alipay\EasySDK\Payment\Common\Models\AlipayTradeRefundResponse
  148. */
  149. public function refund(string $outTradeNo, string $totalAmount, string $refund_id)
  150. {
  151. try {
  152. $result = Factory::payment()->common()->refund($outTradeNo, $totalAmount, $refund_id);
  153. if ($this->response->success($result)) {
  154. return $result;
  155. } else {
  156. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  157. }
  158. } catch (\Exception $e) {
  159. throw new PayException($e->getMessage());
  160. }
  161. }
  162. /**
  163. * 查询交易退款单号信息
  164. * @param string $outTradeNo
  165. * @param string $outRequestNo
  166. * @return \Alipay\EasySDK\Payment\Common\Models\AlipayTradeFastpayRefundQueryResponse
  167. */
  168. public function queryRefund(string $outTradeNo, string $outRequestNo)
  169. {
  170. try {
  171. $result = Factory::payment()->common()->queryRefund($outTradeNo, $outRequestNo);
  172. if ($this->response->success($result)) {
  173. return $result;
  174. } else {
  175. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  176. }
  177. } catch (\Exception $e) {
  178. throw new PayException($e->getMessage());
  179. }
  180. }
  181. /**
  182. * 支付异步回调
  183. * @return string
  184. */
  185. public static function handleNotify()
  186. {
  187. return self::instance()->notify(function ($notify) {
  188. if (isset($notify->out_trade_no)) {
  189. $data = [
  190. 'attach' => $notify->attach,
  191. 'out_trade_no' => $notify->out_trade_no,
  192. 'transaction_id' => $notify->trade_no
  193. ];
  194. return Event::until('pay.notify', [$data, PayServices::ALIAPY_PAY]);
  195. }
  196. return false;
  197. });
  198. }
  199. /**
  200. * 异步回调
  201. * @param callable $notifyFn
  202. * @return string
  203. */
  204. public function notify(callable $notifyFn)
  205. {
  206. app()->request->filter(['trim']);
  207. $paramInfo = app()->request->postMore([
  208. ['gmt_create', ''],
  209. ['charset', ''],
  210. ['seller_email', ''],
  211. ['subject', ''],
  212. ['sign', ''],
  213. ['buyer_id', ''],
  214. ['invoice_amount', ''],
  215. ['notify_id', ''],
  216. ['fund_bill_list', ''],
  217. ['notify_type', ''],
  218. ['trade_status', ''],
  219. ['receipt_amount', ''],
  220. ['buyer_pay_amount', ''],
  221. ['app_id', ''],
  222. ['seller_id', ''],
  223. ['sign_type', ''],
  224. ['gmt_payment', ''],
  225. ['notify_time', ''],
  226. ['passback_params', ''],
  227. ['version', ''],
  228. ['out_trade_no', ''],
  229. ['total_amount', ''],
  230. ['trade_no', ''],
  231. ['auth_app_id', ''],
  232. ['buyer_logon_id', ''],
  233. ['point_amount', ''],
  234. ], false, false);
  235. //商户订单号
  236. $postOrder['out_trade_no'] = $paramInfo['out_trade_no'] ?? '';
  237. //支付宝交易号
  238. $postOrder['trade_no'] = $paramInfo['trade_no'] ?? '';
  239. //交易状态
  240. $postOrder['trade_status'] = $paramInfo['trade_status'] ?? '';
  241. //备注
  242. $postOrder['attach'] = isset($paramInfo['passback_params']) ? urldecode($paramInfo['passback_params']) : '';
  243. if (in_array($paramInfo['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) && $this->verifyNotify($paramInfo)) {
  244. try {
  245. if ($notifyFn((object)$postOrder)) {
  246. return 'success';
  247. }
  248. } catch (\Exception $e) {
  249. Log::error($e->getMessage());
  250. Log::error('支付宝异步会回调成功,执行函数错误。错误单号:' . $postOrder['out_trade_no']);
  251. }
  252. }
  253. return 'fail';
  254. }
  255. /**
  256. * 验签
  257. * @return bool
  258. */
  259. protected function verifyNotify(array $param)
  260. {
  261. try {
  262. return Factory::payment()->common()->verifyNotify($param);
  263. } catch (\Exception $e) {
  264. Log::error('支付宝回调成功,验签发生错误,错误原因:' . $e->getMessage());
  265. }
  266. return false;
  267. }
  268. }