PayPal.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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\common\library\paypal;
  13. use Alipay\EasySDK\Kernel\Config;
  14. use Alipay\EasySDK\Kernel\Factory;
  15. use Alipay\EasySDK\Kernel\Util\ResponseChecker;
  16. use app\common\enum\Client as ClientEnum;
  17. use app\common\library\Log;
  18. use app\common\library\payment\gateway\Driver;
  19. use cores\exception\BaseException;
  20. use cores\Request;
  21. use PayPal\Api\Amount;
  22. use PayPal\Api\Order;
  23. use PayPal\Api\Payer;
  24. use PayPal\Api\Payment;
  25. use PayPal\Api\PaymentExecution;
  26. use PayPal\Api\RedirectUrls;
  27. use PayPal\Api\Transaction;
  28. use PayPal\Api\VerifyWebhookSignature;
  29. use PayPal\Auth\OAuthTokenCredential;
  30. use PayPal\Exception\PayPalConnectionException;
  31. use PayPal\Rest\ApiContext;
  32. use think\Exception;
  33. use think\exception\HttpException;
  34. /**
  35. * paypal驱动
  36. * Class PayPal
  37. * @package app\common\library\payment\gateway\driver
  38. */
  39. class PayPal
  40. {
  41. // 统一下单API的返回结果
  42. private $result;
  43. // 异步通知的请求参数 (由第三方支付发送)
  44. private $notifyParams;
  45. protected $config;
  46. protected $notifyWebHookId;// 3NP026061E6858914
  47. // 异步通知的验证结果
  48. private $notifyResult;
  49. public $apiContext;
  50. public function __construct($config)
  51. {
  52. // 秘钥配置
  53. $this->config = $config;
  54. $this->notifyWebHookId = $this->config['web_hook_id'];
  55. $this->apiContext = new ApiContext(
  56. new OAuthTokenCredential(
  57. $this->config['client_id'],
  58. $this->config['secret']
  59. )
  60. );
  61. $this->apiContext->setConfig([
  62. 'mode' => $this->config['mode'],//sandbox, live
  63. 'log.LogEnabled' => true,
  64. 'log.FileName' => app()->getRootPath() . 'runtime/log/PayPal.log', // 记录日志
  65. 'log.LogLevel' => 'debug', // 在live上用info
  66. 'cache.enable' => true,
  67. ]);
  68. }
  69. /**
  70. * 统一下单API
  71. * @param string $outTradeNo 交易订单号
  72. * @param string $totalFee 实际付款金额
  73. * @param array $extra 附加的数据 (需要携带H5端支付成功后跳转的url)
  74. * @return bool|array
  75. * @throws BaseException
  76. */
  77. public function unify(string $outTradeNo, string $totalFee, array $extra = [], $currency = 'USD')
  78. {
  79. $apiContext = new ApiContext(
  80. new OAuthTokenCredential(
  81. $this->config['client_id'], // ClientID
  82. $this->config['secret'] // ClientSecret
  83. )
  84. );
  85. // After Step 2
  86. $payer = new Payer();
  87. $payer->setPaymentMethod('paypal');
  88. $amount = new Amount();
  89. $amount->setTotal($totalFee);
  90. $amount->setCurrency($currency);
  91. $transaction = new Transaction();
  92. $transaction->setAmount($amount);
  93. $redirectUrls = new RedirectUrls();
  94. //live
  95. //$return_url = config('app.app_host') . $this->config['return_url'] . $outTradeNo;
  96. //$cancel_Url = config('app.app_host').$this->config['cancel_url'];
  97. //sandbox
  98. $return_url = 'https://lar.lmm.gold/api/index/index';
  99. $cancel_url = 'https://lar.lmm.gold/store/index.html';
  100. $redirectUrls->setReturnUrl($return_url)
  101. ->setCancelUrl($cancel_url);
  102. $payment = new Payment();
  103. $payment->setIntent('sale')
  104. ->setPayer($payer)
  105. ->setTransactions(array($transaction))
  106. ->setRedirectUrls($redirectUrls);
  107. $this->result = $payment->create($apiContext);// This will print the detailed information on the exception.
  108. //REALLY HELPFUL FOR DEBUGGING
  109. //echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
  110. return ['approval_link' => $payment->getApprovalLink()];
  111. }
  112. /**
  113. * 交易查询 (主动查询订单支付状态)
  114. * @param string $outTradeNo 交易订单号
  115. * @return array|null
  116. * @throws BaseException
  117. */
  118. public function tradeQuery(string $outTradeNo): ?array
  119. {
  120. try {
  121. $payment = Payment::get($outTradeNo, $this->apiContext);
  122. // 记录日志
  123. Log::append('Paypal-tradeQuery', ['outTradeNo' => $outTradeNo, 'result' => json_encode($result)]);
  124. // 处理响应或异常
  125. //$this->throwError($result->msg . "," . $result->subMsg);
  126. // 返回查询成功的结果
  127. return $result->toArray();
  128. } catch (\Throwable $e) {
  129. $this->throwError('支付宝API交易查询失败:' . $e->getMessage(), true, 'tradeQuery');
  130. }
  131. return null;
  132. }
  133. public function executePayment($paymentId)
  134. {
  135. try {
  136. $payment = Payment::get($paymentId, $this->apiContext);
  137. $execution = new PaymentExecution();
  138. $execution->setPayerId($payment->getPayer()->getPayerInfo()->getPayerId());
  139. // 执行付款
  140. $payment->execute($execution, $this->apiContext);
  141. $payment::get($payment->getId(), $this->apiContext);
  142. $transactions = $payment->getTransactions();
  143. \think\facade\Log::error('$transactions::' . json_encode($transactions));
  144. if ($payment->getState() == 'approved' && $payment->getId() == $paymentId) {
  145. //related_resources->sale->id
  146. return true;
  147. }
  148. return false;
  149. } catch (\Exception $e) {
  150. \think\facade\Log::error('executePayment', ['paymentId' => $paymentId, 'errMsg' => $e->getMessage()]);
  151. $this->throwError('执行失败:' . $e->getMessage(), true, 'tradeQuery');
  152. return false;
  153. }
  154. }
  155. /**
  156. * 支付成功后的异步通知
  157. * @return bool
  158. */
  159. public function notify(Request $request, $webHookId): bool
  160. {
  161. // 接收表单数据
  162. try {
  163. $headers = $request->header();
  164. $headers = array_change_key_case($headers, CASE_UPPER);
  165. $content = $request->getContent();
  166. \think\facade\Log::error('notify::' . json_encode($headers));
  167. // 如果是laravel,这里获请求头的方法可能要变,现在是$headers['PAYPAL-AUTH-ALGO'],去到laravel的话可能要$headers['PAYPAL-AUTH-ALGO'][0],到时试试就知道了,实在不行打日志看看数据结构再确定如何获取
  168. $signatureVerification = new VerifyWebhookSignature();
  169. $signatureVerification->setAuthAlgo($headers['PAYPAL-AUTH-ALGO']);
  170. $signatureVerification->setTransmissionId($headers['PAYPAL-TRANSMISSION-ID']);
  171. $signatureVerification->setCertUrl($headers['PAYPAL-CERT-URL']);
  172. $signatureVerification->setWebhookId($webHookId ?: $this->notifyWebHookId);
  173. $signatureVerification->setTransmissionSig($headers['PAYPAL-TRANSMISSION-SIG']);
  174. $signatureVerification->setTransmissionTime($headers['PAYPAL-TRANSMISSION-TIME']);
  175. $signatureVerification->setRequestBody($content);
  176. $result = clone $signatureVerification;
  177. $output = $signatureVerification->post($this->apiContext);
  178. \think\facade\Log::error('notify' . json_encode($output));
  179. if ($output->getVerificationStatus() == 'SUCCESS') {
  180. return true;
  181. }
  182. throw new HttpException(400, 'Verify Failed.');
  183. } catch (HttpException $exception) {
  184. \think\facade\Log::error('PayPal Notification Verify Failed' . $exception->getMessage());
  185. return false;
  186. }
  187. }
  188. /**
  189. * PAYPAL退款API
  190. * @param string $outTradeNo 第三方交易单号
  191. * @param string $refundAmount 退款金额
  192. * @param array $extra 附加的数据
  193. * @return bool
  194. * @throws BaseException
  195. */
  196. public function refund(string $outTradeNo, string $refundAmount, array $extra = []): bool
  197. {
  198. try {
  199. // 发起API调用
  200. $outRequestNo = (string)time();
  201. return true;
  202. } catch (\Throwable $e) {
  203. $this->throwError('支付宝API退款请求:' . $e->getMessage(), true, 'refund');
  204. }
  205. return false;
  206. }
  207. /**
  208. * 单笔转账接口
  209. * @param string $outTradeNo 交易订单号
  210. * @param string $totalFee 实际付款金额
  211. * @param array $extra 附加的数据 (ALIPAY_LOGON_ID支付宝登录号,支持邮箱和手机号格式; name参与方真实姓名)
  212. * @return bool
  213. */
  214. public function transfers(string $outTradeNo, string $totalFee, array $extra = []): bool
  215. {
  216. return false;
  217. }
  218. /**
  219. * 获取异步回调的请求参数
  220. * @return array
  221. */
  222. public function getNotifyParams(): array
  223. {
  224. return [
  225. // 第三方交易流水号
  226. 'buyerId' => $this->notifyParams['PayerID'],
  227. 'paymentId' => $this->notifyParams['paymentId']
  228. ];
  229. }
  230. /**
  231. * 返回异步通知结果的输出内容
  232. * @return string
  233. */
  234. public function getNotifyResponse(): string
  235. {
  236. return $this->notifyResult ? 'success' : 'FAIL';
  237. }
  238. public function getUnifyResult(): array
  239. {
  240. if (empty($this->result->getApprovalLink())) {
  241. $this->throwError('paypal当前没有unify结果', true, 'getUnifyResult');
  242. return [];
  243. }
  244. // 整理返回的数据
  245. return ['approval_link' => $this->result->getApprovalLink(), 'id' => $this->result->getId()];
  246. }
  247. /**
  248. * 设置支付宝配置信息(全局只需设置一次)
  249. * @param array $options 支付宝配置信息
  250. * @param string $client 下单客户端
  251. * @return null
  252. */
  253. public function setOptions(array $options, string $client)
  254. {
  255. return $this;
  256. }
  257. /**
  258. * 输出错误信息
  259. * @param string $errMessage 错误信息
  260. * @param bool $isLog 是否记录日志
  261. * @param string $action 当前的操作
  262. * @throws BaseException
  263. */
  264. private function throwError(string $errMessage, bool $isLog = false, string $action = '')
  265. {
  266. $this->error = $errMessage;
  267. $isLog && Log::append("Alipay-{$action}", ['errMessage' => $errMessage]);
  268. throwError($errMessage);
  269. }
  270. /**
  271. * 获取和验证下单接口所需的附加数据
  272. * @param array $extra
  273. * @return array
  274. * @throws BaseException
  275. */
  276. private function extraAsUnify(array $extra): array
  277. {
  278. if (!array_key_exists('returnUrl', $extra)) {
  279. $this->throwError('returnUrl参数不存在');
  280. }
  281. return $extra;
  282. }
  283. /**
  284. * 异步回调地址
  285. * @return string
  286. */
  287. private function notifyUrl(): string
  288. {
  289. // 例如:https://www.xxxx.com/alipayNotice.php
  290. return base_url() . 'alipayNotice.php';
  291. }
  292. }