PayPal.php 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. <?php
  2. namespace App\Http\Controllers\Gateway;
  3. use App\Models\Payment;
  4. use Auth;
  5. use Exception;
  6. use Http;
  7. use Illuminate\Http\JsonResponse;
  8. use Illuminate\Http\Request;
  9. use Log;
  10. use Response;
  11. use Srmklive\PayPal\Services\ExpressCheckout;
  12. class PayPal extends AbstractPayment
  13. {
  14. protected $provider;
  15. protected $exChange;
  16. public function __construct()
  17. {
  18. $this->provider = new ExpressCheckout();
  19. $config = [
  20. 'mode' => 'live',
  21. 'live' => [
  22. 'username' => sysConfig('paypal_username'),
  23. 'password' => sysConfig('paypal_password'),
  24. 'secret' => sysConfig('paypal_secret'),
  25. 'certificate' => sysConfig('paypal_certificate'),
  26. 'app_id' => sysConfig('paypal_app_id'),
  27. ],
  28. 'payment_action' => 'Sale',
  29. 'currency' => 'USD',
  30. 'billing_type' => 'MerchantInitiatedBilling',
  31. 'notify_url' => route('payment.notify', ['method' => 'paypal']),
  32. 'locale' => 'zh_CN',
  33. 'validate_ssl' => true,
  34. ];
  35. $this->provider->setApiCredentials($config);
  36. $response = Http::timeout(15)->get('http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4');
  37. $this->exChange = $response->json()['result']['rate'] ?? 7;
  38. }
  39. public function purchase($request): JsonResponse
  40. {
  41. $payment = $this->creatNewPayment(Auth::id(), $request->input('id'), $request->input('amount'));
  42. $data = $this->getCheckoutData($payment->trade_no, $payment->amount);
  43. try {
  44. $response = $this->provider->setExpressCheckout($data);
  45. if (! $response['paypal_link']) {
  46. Log::error('Paypal处理错误:'.var_export($response, true));
  47. return Response::json(['status' => 'fail', 'message' => '创建订单失败,请使用其他方式或通知管理员!']);
  48. }
  49. $payment->update(['url' => $response['paypal_link']]);
  50. return Response::json(['status' => 'success', 'url' => $response['paypal_link'], 'message' => '创建订单成功!']);
  51. } catch (Exception $e) {
  52. Log::error('【PayPal】错误: '.$e->getMessage());
  53. exit;
  54. }
  55. }
  56. protected function getCheckoutData($trade_no, $amount): array
  57. {
  58. $amount = 0.3 + ceil($amount / $this->exChange * 100) / 100;
  59. return [
  60. 'invoice_id' => $trade_no,
  61. 'items' => [
  62. [
  63. 'name' => sysConfig('subject_name') ?: sysConfig('website_name'),
  64. 'price' => $amount,
  65. 'desc' => 'Description for'.(sysConfig('subject_name') ?: sysConfig('website_name')),
  66. 'qty' => 1,
  67. ],
  68. ],
  69. 'invoice_description' => $trade_no,
  70. 'return_url' => route('paypal.checkout'),
  71. 'cancel_url' => route('invoice'),
  72. 'total' => $amount,
  73. ];
  74. }
  75. public function getCheckout(Request $request)
  76. {
  77. $token = $request->get('token');
  78. $PayerID = $request->get('PayerID');
  79. // Verify Express Checkout Token
  80. $response = $this->provider->getExpressCheckoutDetails($token);
  81. if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
  82. $payment = Payment::whereTradeNo($response['INVNUM'])->firstOrFail();
  83. $data = $this->getCheckoutData($payment->trade_no, $payment->amount);
  84. // Perform transaction on PayPal
  85. $payment_status = $this->provider->doExpressCheckoutPayment($data, $token, $PayerID);
  86. $status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
  87. if (! strcasecmp($status, 'Completed') || ! strcasecmp($status, 'Processed')) {
  88. Log::info("Order $payment->order_id has been paid successfully!");
  89. $payment->order->update(['status' => 1]);
  90. } else {
  91. Log::warning("Error processing PayPal payment for Order $payment->id!");
  92. }
  93. }
  94. return redirect(route('invoice'));
  95. }
  96. public function notify($request): void
  97. {
  98. $request->merge(['cmd' => '_notify-validate']);
  99. foreach ($request->input() as $key => $value) {
  100. if ($value === null) {
  101. $request->request->set($key, '');
  102. }
  103. }
  104. $post = $request->all();
  105. $response = (string) $this->provider->verifyIPN($post);
  106. if ($response === 'VERIFIED' && $request['invoice']) {
  107. $payment = Payment::whereTradeNo($request['invoice'])->first();
  108. if ($payment && $payment->status === 0) {
  109. $ret = $payment->order->update(['status' => 2]);
  110. if ($ret) {
  111. exit('success');
  112. }
  113. }
  114. }
  115. exit('fail');
  116. }
  117. }