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

Rest Api Sdk Php Laravel Package

paypal/rest-api-sdk-php

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   **Deprecated Warning**: This SDK (v1.14.0) is **archived** and **deprecated**. Migrate to [PayPal’s official PHP SDK v1.15.0+](https://github.com/paypal/PayPal-PHP-SDK) for long-term support.
   If forced to use this version, install via Composer:
   ```bash
   composer require paypal/rest-api-sdk-php:1.14.0

Verify composer.json for conflicts with newer PayPal SDKs or Laravel dependencies.

  1. First Use Case: Basic API Call Initialize the client with updated logging and PHP version support (7.1+):

    use PayPal\Api\Amount;
    use PayPal\Api\Payer;
    use PayPal\Api\Payment;
    use PayPal\Api\Transaction;
    use PayPal\Rest\ApiContext;
    use PayPal\Auth\OAuthTokenCredential;
    
    // Config (use .env for secrets)
    $apiContext = new ApiContext(
        new OAuthTokenCredential(
            config('services.paypal.client_id'),
            config('services.paypal.secret'),
            config('services.paypal.access_token')
        ),
        config('services.paypal.env') // 'sandbox' or 'live'
    );
    $apiContext->setConfig([
        'log.LogEnabled' => true,
        'log.FileName' => storage_path('logs/paypal.log'),
        'log.LogLevel' => 'DEBUG', // Updated in 1.14.0 (see #983)
        'cache.Directory' => storage_path('paypal_cache'), // Fixed in #1062
    ]);
    
    // Example: Create a payment with idempotency key
    $payment = new Payment();
    $payment->setIntent('sale')
            ->setIdempotencyKey(strtolower(Uuid::generate())) // Best practice
            ->setPayer((new Payer())->setPaymentMethod('paypal'))
            ->setTransactions([(new Transaction())
                ->setAmount((new Amount())->setCurrency('USD')->setTotal('10.00'))
                ->setDescription('Test Payment')]);
    
    try {
        $createdPayment = $payment->create($apiContext);
        echo "Payment ID: " . $createdPayment->getId();
    } catch (\PayPal\Exception\PayPalConnectionException $ex) {
        // Parse error data (now consistently formatted as array in #1034)
        $errorData = json_decode($ex->getData(), true);
        echo $errorData['name'] ?? 'Unknown error';
    }
    
  2. Key Files to Reference


Implementation Patterns

Workflows

  1. OAuth Flow (Updated)

    • Token Refresh: Use the built-in refresh mechanism (tested with PHP 7.1/7.2 in #1061):
      $credential = new OAuthTokenCredential(
          config('services.paypal.client_id'),
          config('services.paypal.secret')
      );
      $apiContext = new ApiContext($credential);
      $apiContext->getAccessToken(); // Auto-refreshes if expired
      
    • Cache Tokens: Store in Laravel’s cache or database with a TTL (tokens expire ~1 hour).
  2. Payment Lifecycle (1.14.0 Fixes)

    • Refunds/Captures: Updated RefundCapture class (#998) supports:
      $sale = Sale::get($saleId, $apiContext);
      $refund = new Refund();
      $refund->setAmountWithBreakdown($amount);
      $sale->refund($refund);
      
    • Direct Credit Cards: Note restriction updates (#1019). Use PayPal.js or PayPal Checkout for PCI compliance.
  3. Laravel Integration (Best Practices)

    • Service Provider: Bind ApiContext with PHP 7.1+ support:
      $this->app->singleton('paypal.apiContext', function ($app) {
          $credential = new OAuthTokenCredential(
              $app['config']['services.paypal.client_id'],
              $app['config']['services.paypal.secret']
          );
          $apiContext = new ApiContext($credential, $app['config']['services.paypal.env']);
          $apiContext->setConfig([
              'log.LogEnabled' => app()->environment('local'),
              'cache.Directory' => storage_path('paypal_cache'),
          ]);
          return $apiContext;
      });
      
    • Facade: Create a PayPal facade with updated error handling:
      PayPal::payment()
            ->setIdempotencyKey($key)
            ->create();
      
  4. Logging and Debugging

    • Log Levels: Updated in #983. Use:
      $apiContext->setConfig(['log.LogLevel' => 'DEBUG']); // or 'INFO', 'WARN', 'ERROR'
      
    • Cache Directory: Fixed in #1062. Ensure storage_path('paypal_cache') is writable.
  5. Testing

    • PHP Versions: Test with PHP 7.1/7.2 (#1061).
    • Mocking: Updated test patterns (#1011):
      $mockContext = $this->createMock(ApiContext::class);
      $mockContext->method('getConfig')->willReturn(['log' => []]);
      

Gotchas and Tips

Pitfalls

  1. Deprecation and Migration

    • Critical: This SDK is end-of-life. Plan to migrate to PayPal’s official SDK v1.15.0+ for:
      • PHP 8.0+ support.
      • Simplified OAuth flow.
      • Native webhook support.
    • Migration Checklist:
      • Replace OAuthTokenCredential with PayPal\Auth\OAuthTokenCredential (updated in v1.15.0).
      • Update RefundCapture usage (#998 in this version).
      • Replace custom logging with PayPal’s built-in logger.
  2. Token and Cache Issues

    • Cache Directory: Fixed in #1062. Ensure:
      $apiContext->setConfig(['cache.Directory' => storage_path('paypal_cache')]);
      
      is writable. Fallback to system temp dir if needed.
    • Token Expiry: Implement a refresh mechanism (tokens expire ~1 hour). Example:
      $credential = new OAuthTokenCredential($clientId, $secret);
      $apiContext = new ApiContext($credential);
      $apiContext->getAccessToken(); // Auto-refreshes
      
  3. Error Handling (Updated)

    • Error Data Format: Fixed in #1034. Parse errors as arrays:
      catch (\PayPal\Exception\PayPalConnectionException $ex) {
          $error = json_decode($ex->getData(), true);
          if (isset($error['details'][0]['issue'])) {
              Log::error($error['details'][0]['issue']);
          }
      }
      
    • Common Errors:
      • INSTRUMENT_DECLINED: Direct credit card restrictions (#1019).
      • VALIDATION_ERROR: Check error_data for field-specific issues.
  4. Idempotency

    • Best Practice: Always set an idempotency key to avoid duplicate payments:
      $payment->setIdempotencyKey(strtolower(Uuid::generate()));
      
    • Note: PayPal’s server-side idempotency is limited to 24 hours.
  5. Webhooks

  6. PHP Version Support

    • Minimum: PHP 7.1 (added in #1061). Avoid PHP 7.0 or below.
    • Compatibility: Test with Laravel 5.8+ (older versions may have autoloading issues).

Tips

  1. Configuration (Updated) Store credentials in .env:
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky