PayPal.php 11 KB

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