AliPayService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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 app\services\system\SystemPemServices;
  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 Alipay\EasySDK\Kernel\Util\ResponseChecker;
  22. /**
  23. * Class AliPayService
  24. * @package crmeb\services
  25. */
  26. class AliPayService
  27. {
  28. /**
  29. * 配置
  30. * @var array
  31. */
  32. protected $config = [
  33. 'appId' => '',
  34. 'merchantPrivateKey' => '',//应用私钥
  35. 'alipayPublicKey' => '',//支付宝公钥
  36. 'notifyUrl' => '',//可设置异步通知接收服务地址
  37. 'encryptKey' => '',//可设置AES密钥,调用AES加解密相关接口时需要(可选)
  38. 'alipayCertPath' => '',//支付宝证书路径(可选)
  39. 'alipayRootCertPath' => '',//支付宝根证书路径(可选)
  40. 'merchantCertPath' => '',//商户证书路径(可选)
  41. ];
  42. /**
  43. * @var ResponseChecker
  44. */
  45. protected $response;
  46. /**
  47. * @var static
  48. */
  49. protected static $instance;
  50. /**
  51. * AliPayService constructor.
  52. * @param array $config
  53. */
  54. protected function __construct(array $config = [])
  55. {
  56. if (!$config) {
  57. $config = [
  58. 'appId' => sys_config('ali_pay_appid'),
  59. 'merchantPrivateKey' => sys_config('alipay_merchant_private_key'),
  60. 'alipayPublicKey' => sys_config('alipay_public_key'),
  61. 'notifyUrl' => sys_config('site_url') . Url::buildUrl('/api/pay/notify/alipay'),
  62. 'alipayCertPath' => $this->getPemPath('alipay_cert_path'),
  63. 'alipayRootCertPath' => $this->getPemPath('alipay_root_cert_path'),
  64. 'merchantCertPath' => $this->getPemPath('merchant_cert_path'),
  65. ];
  66. }
  67. $this->config = array_merge($this->config, $config);
  68. $this->initialize();
  69. $this->response = new ResponseChecker();
  70. }
  71. public function getPemPath(string $name)
  72. {
  73. $systemPemServices = app()->make(SystemPemServices::class);
  74. $path = $systemPemServices->getPemPath($name);
  75. if ($path) return $path;
  76. $path = sys_config($name);
  77. if (strstr($path, 'http://') || strstr($path, 'https://')) {
  78. $path = parse_url($path)['path'] ?? '';
  79. }
  80. $path = root_path('runtime/pem') . ltrim($path, '/');
  81. if (!file_exists($path)) {
  82. $path = public_path('uploads') . ltrim($path, '/');
  83. }
  84. return $path;
  85. }
  86. /**
  87. * 实例化
  88. * @param array $config
  89. * @return static
  90. */
  91. public static function instance(array $config = [])
  92. {
  93. if (is_null(self::$instance)) {
  94. self::$instance = new static($config);
  95. }
  96. return self::$instance;
  97. }
  98. /**
  99. * 初始化
  100. */
  101. protected function initialize()
  102. {
  103. Factory::setOptions($this->getOptions());
  104. }
  105. /**
  106. * 设置配置
  107. * @return Config
  108. */
  109. protected function getOptions()
  110. {
  111. $options = new Config();
  112. $options->protocol = 'https';
  113. $options->gatewayHost = 'openapi.alipay.com';
  114. $options->signType = 'RSA2';
  115. $options->appId = $this->config['appId'];
  116. // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中
  117. $options->merchantPrivateKey = $this->config['merchantPrivateKey'];
  118. if (sys_config('alipay_sign_type') == 0) {
  119. // 密钥模式
  120. $options->alipayPublicKey = $this->config['alipayPublicKey'];
  121. } else {
  122. // 证书模式
  123. $options->alipayCertPath = $this->config['alipayCertPath'];
  124. $options->alipayRootCertPath = $this->config['alipayRootCertPath'];
  125. $options->merchantCertPath = $this->config['merchantCertPath'];
  126. $options->alipayPublicKey = '';
  127. }
  128. //可设置异步通知接收服务地址(可选)
  129. $options->notifyUrl = $this->config['notifyUrl'];
  130. //可设置AES密钥,调用AES加解密相关接口时需要(可选)
  131. if ($this->config['encryptKey']) {
  132. $options->encryptKey = $this->config['encryptKey'];
  133. }
  134. return $options;
  135. }
  136. /**
  137. * 创建订单
  138. * @param string $title 商品名称
  139. * @param string $orderId 订单号
  140. * @param string $totalAmount 支付金额
  141. * @param string $passbackParams 备注
  142. * @param string $quitUrl 同步跳转地址
  143. * @param string $returnUrl
  144. * @param bool $isCode
  145. * @return AlipayTradeWapPayResponse
  146. */
  147. public function create(string $title, string $orderId, string $totalAmount, string $passbackParams, string $quitUrl = '', string $returnUrl = '', bool $isCode = false)
  148. {
  149. $title = trim($title);
  150. try {
  151. if ($isCode) {
  152. //二维码支付
  153. $result = Factory::payment()->faceToFace()->optional('passback_params', $passbackParams)->precreate($title, $orderId, $totalAmount);
  154. } else if (request()->isApp()) {
  155. //app支付
  156. $result = Factory::payment()->app()->optional('passback_params', $passbackParams)->pay($title, $orderId, $totalAmount);
  157. } else {
  158. //h5支付
  159. $result = Factory::payment()->wap()->optional('passback_params', $passbackParams)->pay($title, $orderId, $totalAmount, $quitUrl, $returnUrl);
  160. }
  161. if ($this->response->success($result)) {
  162. return $result->body ?? $result;
  163. } else {
  164. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  165. }
  166. } catch (\Exception $e) {
  167. throw new PayException($e->getMessage());
  168. }
  169. }
  170. /**
  171. * 订单退款
  172. * @param string $outTradeNo 订单号
  173. * @param string $totalAmount 退款金额
  174. * @param string $refund_id 退款单号
  175. * @return \Alipay\EasySDK\Payment\Common\Models\AlipayTradeRefundResponse
  176. */
  177. public function refund(string $outTradeNo, string $totalAmount, string $refund_id)
  178. {
  179. try {
  180. $result = Factory::payment()->common()->refund($outTradeNo, $totalAmount, $refund_id);
  181. if ($this->response->success($result)) {
  182. return $result;
  183. } else {
  184. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  185. }
  186. } catch (\Exception $e) {
  187. throw new PayException($e->getMessage());
  188. }
  189. }
  190. /**
  191. * 查询交易退款单号信息
  192. * @param string $outTradeNo
  193. * @param string $outRequestNo
  194. * @return \Alipay\EasySDK\Payment\Common\Models\AlipayTradeFastpayRefundQueryResponse
  195. */
  196. public function queryRefund(string $outTradeNo, string $outRequestNo)
  197. {
  198. try {
  199. $result = Factory::payment()->common()->queryRefund($outTradeNo, $outRequestNo);
  200. if ($this->response->success($result)) {
  201. return $result;
  202. } else {
  203. throw new PayException('失败原因:' . $result->msg . ',' . $result->subMsg);
  204. }
  205. } catch (\Exception $e) {
  206. throw new PayException($e->getMessage());
  207. }
  208. }
  209. /**
  210. * 支付异步回调
  211. * @return string
  212. */
  213. public static function handleNotify()
  214. {
  215. return self::instance()->notify(function ($notify) {
  216. if (isset($notify->out_trade_no)) {
  217. $data = [
  218. 'attach' => $notify->attach,
  219. 'out_trade_no' => $notify->out_trade_no,
  220. 'transaction_id' => $notify->trade_no
  221. ];
  222. return Event::until('NotifyListener', [$data, PayServices::ALIAPY_PAY]);
  223. }
  224. return false;
  225. });
  226. }
  227. /**
  228. * 异步回调
  229. * @param callable $notifyFn
  230. * @return string
  231. */
  232. public function notify(callable $notifyFn)
  233. {
  234. app()->request->filter(['trim']);
  235. $paramInfo = app()->request->param();
  236. if (isset($paramInfo['type'])) {
  237. unset($paramInfo['type']);
  238. }
  239. //商户订单号
  240. $postOrder['out_trade_no'] = $paramInfo['out_trade_no'] ?? '';
  241. //支付宝交易号
  242. $postOrder['trade_no'] = $paramInfo['trade_no'] ?? '';
  243. //交易状态
  244. $postOrder['trade_status'] = $paramInfo['trade_status'] ?? '';
  245. //备注
  246. $postOrder['attach'] = isset($paramInfo['passback_params']) ? urldecode($paramInfo['passback_params']) : '';
  247. if (in_array($paramInfo['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) && $this->verifyNotify($paramInfo)) {
  248. try {
  249. if ($notifyFn((object)$postOrder)) {
  250. return 'success';
  251. }
  252. } catch (\Exception $e) {
  253. Log::error($e->getMessage());
  254. Log::error('支付宝异步会回调成功,执行函数错误。错误单号:' . $postOrder['out_trade_no']);
  255. }
  256. }
  257. return 'fail';
  258. }
  259. /**
  260. * 验签
  261. * @return bool
  262. */
  263. protected function verifyNotify(array $param)
  264. {
  265. try {
  266. return Factory::payment()->common()->verifyNotify($param);
  267. } catch (\Exception $e) {
  268. Log::error('支付宝回调成功,验签发生错误,错误原因:' . $e->getMessage());
  269. }
  270. return false;
  271. }
  272. /**
  273. * 商家支付接口
  274. *
  275. * @param array $bizParams 业务参数
  276. * @return mixed|false 支付结果或者false
  277. * @throws PayException 支付异常
  278. */
  279. public function merchantPay(array $bizParams, $alipaySignType = 0)
  280. {
  281. try {
  282. // 调用工厂类的通用方法执行支付宝转账操作
  283. $method = $alipaySignType == 0 ? 'alipay.fund.trans.toaccount.transfer' : 'alipay.fund.trans.uni.transfer';
  284. $result = Factory::util()->generic()->execute($method, [], $bizParams);
  285. // 判断支付是否成功
  286. if ($this->response->success($result)) {
  287. return $result;
  288. } else {
  289. Log::error('支付宝转账失败,失败原因:' . $result->msg . ' | ' . $result->subCode . ' | ' . $result->subMsg);
  290. return false;
  291. }
  292. } catch (\Exception $e) {
  293. // 记录日志并返回false
  294. Log::error('支付宝转账失败,失败原因:' . $e->getMessage());
  295. return false;
  296. }
  297. }
  298. }