PayPal.php 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. protected $provider;
  14. protected $exChange;
  15. public function __construct() {
  16. $this->provider = new ExpressCheckout();
  17. $config = [
  18. 'mode' => 'live',
  19. 'live' => [
  20. 'username' => sysConfig('paypal_username'),
  21. 'password' => sysConfig('paypal_password'),
  22. 'secret' => sysConfig('paypal_secret'),
  23. 'certificate' => sysConfig('paypal_certificate'),
  24. 'app_id' => sysConfig('paypal_app_id'),
  25. ],
  26. 'payment_action' => 'Sale',
  27. 'currency' => 'USD',
  28. 'billing_type' => 'MerchantInitiatedBilling',
  29. 'notify_url' => (sysConfig('website_callback_url')?: sysConfig('website_url')).'/callback/notify?method=paypal',
  30. 'locale' => 'zh_CN',
  31. 'validate_ssl' => true,
  32. ];
  33. $this->provider->setApiCredentials($config);
  34. $this->exChange = 7;
  35. $client = new Client(['timeout' => 15]);
  36. $exChangeRate = json_decode($client->get('http://api.k780.com/?app=finance.rate&scur=USD&tcur=CNY&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4')
  37. ->getBody(), true);
  38. if($exChangeRate && $exChangeRate['success']){
  39. $this->exChange = $exChangeRate['result']['rate'];
  40. }
  41. }
  42. public function purchase($request): JsonResponse {
  43. $payment = $this->creatNewPayment(Auth::id(), $request->input('id'), $request->input('amount'));
  44. $data = $this->getCheckoutData($payment->trade_no, $payment->amount);
  45. try{
  46. $response = $this->provider->setExpressCheckout($data);
  47. if(!$response['paypal_link']){
  48. Log::error('Paypal处理错误:'.var_export($response, true));
  49. return Response::json(['status' => 'fail', 'message' => '创建订单失败,请使用其他方式或通知管理员!']);
  50. }
  51. $payment->update(['url' => $response['paypal_link']]);
  52. return Response::json(['status' => 'success', 'url' => $response['paypal_link'], 'message' => '创建订单成功!']);
  53. }catch(Exception $e){
  54. Log::error("【PayPal】错误: ".$e->getMessage());
  55. exit;
  56. }
  57. }
  58. protected function getCheckoutData($trade_no, $amount): array {
  59. $amount = 0.3 + ceil($amount / $this->exChange * 100) / 100;
  60. return [
  61. 'invoice_id' => $trade_no,
  62. 'items' => [
  63. [
  64. 'name' => sysConfig('subject_name')?: sysConfig('website_name'),
  65. 'price' => $amount,
  66. 'desc' => 'Description for'.(sysConfig('subject_name')?: sysConfig('website_name')),
  67. 'qty' => 1
  68. ]
  69. ],
  70. 'invoice_description' => $trade_no,
  71. 'return_url' => sysConfig('website_url').'/callback/checkout',
  72. 'cancel_url' => sysConfig('website_url').'/invoices',
  73. 'total' => $amount,
  74. ];
  75. }
  76. public function getCheckout(Request $request) {
  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::error("Error processing PayPal payment for Order $payment->id!");
  92. }
  93. }
  94. return redirect('/invoices');
  95. }
  96. public function notify($request): void {
  97. $request->merge(['cmd' => '_notify-validate']);
  98. foreach($request->input() as $key => $value){
  99. if($value == null){
  100. $request->request->set($key, '');
  101. }
  102. }
  103. $post = $request->all();
  104. $response = (string) $this->provider->verifyIPN($post);
  105. if($response === 'VERIFIED' && $request['invoice']){
  106. $payment = Payment::whereTradeNo($request['invoice'])->first();
  107. if($payment && $payment->status == 0){
  108. $ret = $payment->order->update(['status' => 2]);
  109. if($ret){
  110. exit('success');
  111. }
  112. }
  113. }
  114. exit("fail");
  115. }
  116. }