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 Laravel Package

srmklive/paypal

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require srmklive/paypal
    

    For Laravel, publish the config:

    php artisan vendor:publish --provider="Srmklive\PayPal\Providers\PayPalServiceProvider" --tag="config"
    
  2. Configuration Update .env with PayPal credentials:

    PAYPAL_CLIENT_ID=your_client_id
    PAYPAL_SECRET=your_secret
    PAYPAL_MODE=sandbox  # or 'live'
    
  3. First Use Case: Create a Payment

    use Srmklive\PayPal\Services\PayPal;
    
    $paypal = app('paypal');
    $payment = $paypal->payment()->create([
        'intent' => 'sale',
        'payer' => [
            'payment_method' => 'paypal',
        ],
        'transactions' => [
            [
                'amount' => [
                    'total' => '10.00',
                    'currency' => 'USD',
                ],
                'description' => 'Test Payment',
            ],
        ],
        'redirect_urls' => [
            'return_url' => route('paypal.success'),
            'cancel_url' => route('paypal.cancel'),
        ],
    ]);
    
  4. Redirect User

    return redirect()->away($payment->getApprovalLink());
    

Implementation Patterns

Common Workflows

1. Handling Payments (Express Checkout)

  • Create Payment → Redirect user → Execute Payment on return.
    // After user returns from PayPal
    $paymentId = request('paymentID');
    $payerId = request('PayerID');
    
    $payment = $paypal->payment()->get($paymentId);
    $execution = $paypal->payment()->execute($paymentId, [
        'payer_id' => $payerId,
    ]);
    

2. Subscriptions (Billing Plans)

  • Create Plan:
    $plan = $paypal->plan()->create([
        'name' => 'Premium',
        'description' => 'Monthly Subscription',
        'billing_cycles' => [
            'price' => '9.99',
            'frequency' => 'MONTH',
            'tenure_type' => 'REGULAR',
            'sequence' => 1,
        ],
    ]);
    
  • Create Subscription:
    $subscription = $paypal->subscription()->create([
        'plan_id' => $plan->getId(),
        'start_time' => now()->addDay()->format('Y-m-d\TH:i:s\Z'),
        'subscriber' => [
            'name' => 'John Doe',
            'email_address' => 'john@example.com',
        ],
    ]);
    

3. Refunds and Captures

  • Capture Payment:
    $capture = $paypal->capture()->create($paymentId, [
        'amount' => '5.00',
    ]);
    
  • Refund:
    $refund = $paypal->refund()->create($capture->getId(), [
        'amount' => [
            'total' => '2.50',
            'currency' => 'USD',
        ],
    ]);
    

4. Webhooks (IPN)

  • Listen for Events:
    use Srmklive\PayPal\Services\Webhook;
    
    $webhook = app(Webhook::class);
    $event = $webhook->verifyAndParse(request()->all());
    
  • Route Webhook:
    Route::post('/paypal/webhook', [PayPalController::class, 'handleWebhook']);
    

Integration Tips

  • Use Laravel Facades for cleaner code:
    use Srmklive\PayPal\Facades\PayPal;
    
    $payment = PayPal::payment()->create([...]);
    
  • Store PayPal IDs in your database (e.g., payment_id, subscription_id) for later reference.
  • Leverage Laravel Events to trigger actions post-webhook (e.g., payment.succeeded).
  • Mock PayPal in Tests:
    $this->mock(PayPal::class)->shouldReceive('payment()->create')->andReturn($mockPayment);
    

Gotchas and Tips

Pitfalls

  1. Sandbox vs. Live Mode

    • Always test in sandbox first. Use PAYPAL_MODE=sandbox in .env.
    • Sandbox credentials are different from live credentials. Never mix them.
  2. Redirect URLs Must Match

    • PayPal strictly validates return_url and cancel_url. Ensure they are HTTPS and accessible.
    • Use absolute URLs (e.g., https://yourdomain.com/paypal/success).
  3. Idempotency Keys

    • For subscriptions or payments, use idempotency_key to avoid duplicate processing:
      $paypal->subscription()->create([...], 'unique_key_123');
      
  4. Webhook Verification

    • Always verify webhook signatures using Webhook::verify() to prevent spoofing.
    • PayPal sends events as POST requests to your configured webhook URL.
  5. Currency and Amount Formatting

    • PayPal expects 3 decimal places for amounts (e.g., 10.00 not 10).
    • Use number_format($amount, 2, '.', '') to ensure consistency.
  6. Rate Limits

    • PayPal API has rate limits (e.g., 3000 calls/hour for sandbox). Cache responses where possible.
  7. Deprecated Methods

    • Avoid createOrder() (older method). Use payment()->create() for classic PayPal flows or order()->create() for newer PayPal Checkout.

Debugging Tips

  1. Enable Logging Add to config/paypal.php:

    'log' => [
        'enabled' => true,
        'file' => storage_path('logs/paypal.log'),
    ],
    

    Logs API requests/responses for troubleshooting.

  2. Check HTTP Status Codes

    • PayPal returns 400 for invalid requests, 401 for auth issues, and 403 for forbidden actions.
    • Use try-catch to handle exceptions:
      try {
          $payment = $paypal->payment()->create([...]);
      } catch (\Srmklive\PayPal\Exceptions\PayPalConnectionException $e) {
          Log::error($e->getMessage());
      }
      
  3. PayPal Developer Dashboard

  4. Common Errors

    • "Invalid parameter: items": Ensure transactions array includes item_list if selling items.
    • "Invalid Payer": Verify payer object structure (e.g., payment_method must be paypal).
    • "Redirect URI Not Allowed": Add your redirect URLs in PayPal Developer Portal.

Extension Points

  1. Customize Requests/Responses Override the PayPal service binding in AppServiceProvider:

    $this->app->bind('paypal', function () {
        $paypal = new \Srmklive\PayPal\Services\PayPal();
        $paypal->setConfig(['timeout' => 30]); // Custom timeout
        return $paypal;
    });
    
  2. Add Custom API Endpoints Extend the PayPal class to support unsupported endpoints:

    $paypal->custom()->post('/v1/custom-endpoint', $data);
    
  3. Webhook Middleware Create middleware to process webhooks before they reach your controller:

    public function handle($request, Closure $next) {
        $event = Webhook::verifyAndParse($request->all());
        // Process event (e.g., update DB, send notifications)
        return $next($request);
    }
    
  4. Laravel Cashier Integration Use PayPal subscriptions with Cashier for unified billing:

    $user->newSubscription('premium', $planId)->create($paypalToken);
    
  5. Standalone PHP Usage Initialize PayPal without Laravel:

    $paypal = new \Srmklive\PayPal\Services\PayPal();
    $paypal->setConfig([
        'mode' => 'sandbox',
        'client_id' => 'your_client_id',
        'secret' => 'your_secret',
    ]);
    
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