PayPal.php 4.4 KB

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