PayPal.php 5.2 KB

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