欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

php paypal支付

程序员文章站 2022-06-12 19:38:44
...

首先安装依赖:

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()
      ];
    }
  }
}

 

回调

$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);
    }

 

相关标签: php