AliPayService.php 8.8 KB

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