php paypal支付

首先安装依赖:

composer require paypal/rest-api-sdk-php
class PaypalTool 
{
  private $baseUrl;
  private $apiContext;
  private $key;
  private $secret;
  private $host;

  public function __construct()
  {
    $this->baseUrl = env('PAY_PAL_URL');
    $this->key = env('PAY_PAL_KEY');
    $this->secret = env('PAY_PAL_SECRET');
    $this->host = env('APP_URL');
    $this->apiContext = new ApiContext(new OAuthTokenCredential($this->key, $this->secret));
  }

  public function getToken()
  {
    // 'https://api-m.sandbox.paypal.com/v1/oauth2/token';
    $client = new \GuzzleHttp\Client([
      'base_uri' => $this->baseUrl,
      'timeout' => 60
    ]);
    $key = env('PAY_PAL_KEY');
    $password = env('PAY_PAL_PASSWORD');

    $auth = [$key, $password];
    $postBody = [
      'grant_type' => 'client_credentials'
    ];
    try {
      $response = $client->post('/v1/oauth2/token', ['auth' => $auth, 'form_params' => $postBody]);
      $code = $response->getStatusCode();
      if ($code == 200) {
        $body = json_decode($response->getBody()->getContents(), true);
        return [
          'code' => 0,
          'scope' =>$body['scope'],
          'access_token' =>$body['access_token'],
          'token_type' =>$body['token_type'],
          'app_id' =>$body['app_id'],
          'expires_in' =>$body['expires_in'],
          'nonce' =>$body['nonce']
        ];
      }
      return [
        'code' => 1,
        'msg' => ''
      ];
    } catch(RequestException $e) {
      return [
        'code' => 1,
        'msg' => $e->getMessage()
      ];
    }
  }

  public function pay($type, $payAmount, $orderId, $productName)
  {
    $payer = new Payer();
    $payer->setPaymentMethod('paypal');

    $item = new Item();
    $item->setName($productName)->setSku($type)->setCurrency('USD')->setQuantity(1)->setPrice($payAmount);

    $itemList = new ItemList();
    $itemList->setItems([$item]);

    $amount = new Amount();
    $amount->setCurrency('USD')->setTotal($payAmount);

    $transaction = new Transaction();
    $transaction->setItemList($itemList)->setAmount($amount)->setInvoiceNumber($orderId);
    //$transaction->setAmount($amount)->setInvoiceNumber($orderId);

    $redirectUrls = new RedirectUrls();
    $redirectUrls->setReturnUrl($this->host."/respond")
        ->setCancelUrl($this->host."/cancel");

    $payment = new Payment();
    $payment->setIntent('sale')
        ->setPayer($payer)
        ->setTransactions(array($transaction))
        ->setRedirectUrls($redirectUrls);

    //$payment->create($this->apiContext);
    //var_dump($payment);
    //exit;

    try {
        $payment->create($this->apiContext);
        //echo "\n\nRedirect user to approval_url: " . $payment->getApprovalLink() . "\n";
        $approvalUrl = $payment->getApprovalLink();
        return [
          'error' => 0,
          'payment_id' => $payment->getId(),
          'payment_url' => $payment->getApprovalLink()
        ];
    }
    catch (PayPalConnectionException $ex) {
        // This will print the detailed information on the exception.
        //REALLY HELPFUL FOR DEBUGGING
        // echo $ex->getData();
        return [
          'error' => 1,
          'msg' => $ex->getMessage()
        ];
    }
   
  }

  public function notify($paymentId, $payerID)
  {
    $payment = Payment::get($paymentId, $this->apiContext);
    $execution = new PaymentExecution();
    $execution->setPayerId($payerID);

    try {
      $result = $payment->execute($execution, $this->apiContext);
      return [
        'error' => 0,
        'msg' => __('front.pay_success'),
        'data' => $result,
      ];
    } catch(\Exception $e) {
      return [
        'error' => 1,
        'msg' => __('front.pay_fail') . ':' .$e->getMessage()
      ];
    }
  }
}

 

使用

 $pay = new PaypalTool();
          $res = $pay->pay('order', $payAmount, $order->id, $order->order_content);
          if ($res['error'] == 1) {
            return view('front.alert.index', ['error' => $res['msg'], 'url' => url(session('prefix') . '/member/order'), 'url_title' =>  __('front.my_order')]);
          } else {
            $url = $res['payment_url'];
            $paymentId = $res['payment_id'];
            // 更新回传id
            PayTaskRepository::updateReturnIdAndAmount($order->id, 'order', $paymentId, $payAmount,null,'paypal');
            
            DB::commit();
            header('Location: ' . $url);
          }

回调

$paymentId = $request->get('paymentId', '');
    $payerID = $request->get('PayerID', '');
   
   

    $payPal = new PaypalTool();
    $res = $payPal->notify($paymentId, $payerID);
    if ($res['error'] == 0) {
      $data = $res['data'];
      var_dump($data);
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值