Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Paypal Checkout Sdk Laravel Package

paypal/paypal-checkout-sdk

Deprecated PayPal PHP SDK for REST APIs v2 (Checkout Orders and Payments). Provides model objects and HTTP call blueprints for server-side integrations. PHP 5.6+ and TLS 1.2 required. PayPal recommends migrating to the new Server SDK.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require paypal/paypal-checkout-sdk
    

    Ensure your composer.json includes "paypal/paypal-checkout-sdk": "^1.0" (or latest compatible version).

  2. Environment Configuration:

    • Register a REST API app to obtain Client ID and Client Secret.
    • Use Sandbox for testing or Live for production:
      use PayPalCheckoutSdk\Core\SandboxEnvironment; // or LiveEnvironment
      $environment = new SandboxEnvironment('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
      $client = new PayPalHttpClient($environment);
      
  3. First Use Case: Create an Order

    use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
    
    $request = new OrdersCreateRequest();
    $request->body = [
        "intent" => "CAPTURE",
        "purchase_units" => [[
            "amount" => ["currency_code" => "USD", "value" => "10.00"]
        ]],
        "application_context" => [
            "return_url" => route('paypal.return'),
            "cancel_url" => route('paypal.cancel')
        ]
    ];
    $response = $client->execute($request);
    $orderId = $response->result->id;
    

Implementation Patterns

Core Workflows

  1. Order Creation & Capture

    • Create Order: Use OrdersCreateRequest to generate a PayPal approval link.
    • Capture Payment: After user approval, call OrdersCaptureRequest($orderId).
    • Refunds: Use OrdersRefundRequest for partial/full refunds.
  2. Webhook Handling

    • Subscribe to PayPal webhooks for real-time events (e.g., PAYMENT.CAPTURE.COMPLETED).
    • Validate signatures using PayPalHttpClient:
      use PayPalCheckoutSdk\Webhooks\Events\CheckoutEvent;
      use PayPalCheckoutSdk\Webhooks\VerifyWebhookSignature;
      
      $signature = VerifyWebhookSignature::verify(
          $webhookBody,
          $webhookHeader['PAYPAL-WEBHOOK-SIGNATURE'],
          $webhookHeader['PAYPAL-WEBHOOK-ID'],
          $clientId
      );
      
  3. Error Handling

    • Catch HttpException for API errors:
      try {
          $response = $client->execute($request);
      } catch (HttpException $ex) {
          Log::error("PayPal Error: " . $ex->getMessage(), ['status' => $ex->statusCode]);
          return redirect()->route('payment.failed');
      }
      

Integration Tips

  • Laravel Service Provider: Bind the client to the container for dependency injection:

    $this->app->singleton(PayPalHttpClient::class, function ($app) {
        return new PayPalHttpClient(new LiveEnvironment(
            config('services.paypal.client_id'),
            config('services.paypal.secret')
        ));
    });
    
  • Request Validation: Use Laravel’s FormRequest to validate order data before SDK calls:

    public function rules() {
        return [
            'price' => 'required|numeric|min:0.01',
            'currency' => 'required|in:USD,EUR,GBP',
        ];
    }
    
  • Testing: Use the Sandbox environment for unit/integration tests. Mock PayPalHttpClient:

    $mockClient = Mockery::mock(PayPalHttpClient::class);
    $mockClient->shouldReceive('execute')
               ->andReturn(new OrdersCreateResponse(new OrdersData()));
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning:

    • This SDK is deprecated. Migrate to PayPal Server SDK for long-term support.
    • Key differences: New SDK uses PayPalHttpClient with Environment (Sandbox/Live), while this SDK uses PayPalHttpClient with SandboxEnvironment.
  2. TLS 1.2 Requirement:

    • Ensure your server supports TLS 1.2. Configure PHP:
      ; php.ini
      openssl.cafile=/path/to/cacert.pem
      
  3. Order Lifecycle:

    • CAPTURE Intent: Payment is authorized and captured immediately.
    • AUTHORIZE Intent: Requires explicit capture via OrdersCaptureRequest. Uncaptured orders expire after 3 days.
  4. Webhook Verification:

    • Always verify webhook signatures. Use VerifyWebhookSignature to prevent replay attacks.

Debugging

  • Enable Logging: Configure the HTTP client to log requests/responses:

    $client = new PayPalHttpClient($environment, [
        'logger' => new PayPalHttpLogger(
            new FileHandler('/path/to/paypal.log'),
            PayPalHttpLogger::DEBUG
        )
    ]);
    
  • Common Errors:

    • 400 Bad Request: Validate request body (e.g., intent, currency_code).
    • 401 Unauthorized: Check Client ID/Secret and environment (Sandbox/Live).
    • 403 Forbidden: Ensure your app has the correct permissions in the PayPal Developer Dashboard.

Extension Points

  1. Custom Headers: Add headers to requests:

    $request->headers = ["X-Custom-Header" => "value"];
    
  2. Retry Logic: Implement exponential backoff for transient failures:

    use PayPalCheckoutSdk\Core\PayPalHttpClient;
    use GuzzleHttp\Exception\RequestException;
    
    try {
        $response = $client->execute($request);
    } catch (RequestException $e) {
        if ($e->hasResponse() && $e->getResponse()->getStatusCode() === 429) {
            sleep(2); // Retry after 2 seconds
            return $client->execute($request);
        }
        throw $e;
    }
    
  3. Localization: Support multiple currencies/languages by dynamically setting purchase_units.amount.currency_code and application_context.locale.

Configuration Quirks

  • Environment Variables: Avoid hardcoding credentials. Use Laravel’s .env:

    PAYPAL_CLIENT_ID=your_id
    PAYPAL_SECRET=your_secret
    

    Access via config('services.paypal').

  • Sandbox vs. Live:

    • Sandbox uses https://api.sandbox.paypal.com.
    • Live uses https://api.paypal.com. Always test in Sandbox first.
  • Idempotency: Use the idempotency-key header to prevent duplicate transactions:

    $request->headers = ["Idempotency-Key" => Str::uuid()->toString()];
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime