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

Laravel Stripe Server Laravel Package

lab404/laravel-stripe-server

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require lab404/laravel-stripe-server
    

    Publish the config file:

    php artisan vendor:publish --provider="Lab404\LaravelStripeServer\StripeServerServiceProvider"
    
  2. Configuration Update .env with Stripe keys:

    STRIPE_SECRET=your_stripe_secret_key
    STRIPE_WEBHOOK_SECRET=your_webhook_signing_secret
    
  3. First Use Case: Handling Webhooks Register the webhook route in routes/web.php:

    Route::post('/stripe/webhook', [StripeServerController::class, 'handleWebhook']);
    
  4. Verify Stripe Signature In your controller, ensure the webhook payload is verified:

    use Lab404\LaravelStripeServer\Facades\StripeServer;
    
    public function handleWebhook(Request $request) {
        $payload = $request->getContent();
        $sigHeader = $request->header('Stripe-Signature');
    
        if (!StripeServer::verifyWebhook($payload, $sigHeader)) {
            abort(401, 'Invalid signature');
        }
    
        // Process the event
        $event = StripeServer::retrieveWebhookEvent($payload);
        // Handle event logic here
    }
    

Implementation Patterns

Workflow: Strong Customer Authentication (SCA) Checkout

  1. Initialize Checkout Session Use Stripe’s API to create a checkout session:

    $session = \Stripe\Checkout\Session::create([
        'payment_method_types' => ['card'],
        'line_items' => [[
            'price' => 'price_123',
            'quantity' => 1,
        ]],
        'mode' => 'payment',
        'success_url' => route('checkout.success'),
        'cancel_url' => route('checkout.cancel'),
    ]);
    
  2. Handle SCA Redirect Redirect the user to Stripe’s checkout:

    return redirect()->away($session->url);
    
  3. Webhook Handling for SCA Listen for checkout.session.completed events:

    if ($event->type === 'checkout.session.completed') {
        $session = $event->data->object;
        // Verify SCA status
        if ($session->payment_status === 'paid' && $session->client_reference_id) {
            // Mark order as paid in your DB
        }
    }
    

Integration Tips

  • Middleware for Authenticated Requests Protect webhook routes with middleware to ensure only Stripe can trigger them:

    Route::post('/stripe/webhook', [StripeServerController::class, 'handleWebhook'])
         ->middleware('stripe.webhook');
    

    Add this middleware in app/Http/Kernel.php:

    'stripe.webhook' => \Lab404\LaravelStripeServer\Http\Middleware\VerifyStripeWebhook::class,
    
  • Event Dispatching Dispatch custom events for business logic:

    event(new StripePaymentCompleted($session));
    
  • Testing Webhooks Use Stripe’s CLI to test locally:

    stripe listen --forward-to localhost:8000/stripe/webhook
    

Gotchas and Tips

Pitfalls

  1. Webhook Signature Mismatch

    • Issue: StripeServer::verifyWebhook() fails due to incorrect STRIPE_WEBHOOK_SECRET.
    • Fix: Ensure the secret in .env matches the one in Stripe Dashboard under Developers > Webhooks.
  2. Outdated Stripe PHP Library

    • Issue: The package relies on the stripe/stripe-php library. Conflicts may arise if versions are mismatched.
    • Fix: Pin the Stripe PHP library version in composer.json:
      "require": {
          "stripe/stripe-php": "^7.0"
      }
      
  3. SCA Compliance Failures

    • Issue: Stripe may reject payments due to missing SCA parameters (e.g., return_url or customer_email).
    • Fix: Always include required fields in the checkout session:
      'customer_email' => auth()->user()->email,
      'return_url' => route('stripe.return', ['session_id' => '{CHECKOUT_SESSION_ID}']),
      
  4. Idempotency Keys

    • Issue: Duplicate webhook events can cause double-processing.
    • Fix: Use Stripe’s idempotency_key in webhook handling:
      if ($event->idempotency) {
          // Skip if already processed
      }
      

Debugging

  • Log Webhook Events Add logging to debug payloads:

    \Log::debug('Stripe Webhook Event', ['event' => $event->toArray()]);
    
  • Test in Sandbox Mode Use Stripe’s test mode to avoid production issues:

    STRIPE_SECRET=sk_test_...
    STRIPE_WEBHOOK_SECRET=whsec_...
    

Extension Points

  1. Custom Event Handlers Extend the package by creating a service to handle specific events:

    namespace App\Services;
    
    use Lab404\LaravelStripeServer\Events\StripeEvent;
    
    class StripeEventHandler {
        public function handle(StripeEvent $event) {
            switch ($event->type) {
                case 'payment_intent.succeeded':
                    // Custom logic
                    break;
            }
        }
    }
    
  2. Override Webhook Verification Extend the VerifyStripeWebhook middleware for custom logic:

    namespace App\Http\Middleware;
    
    use Lab404\LaravelStripeServer\Http\Middleware\VerifyStripeWebhook as BaseMiddleware;
    
    class CustomVerifyStripeWebhook extends BaseMiddleware {
        protected function validateSignature($payload, $sigHeader) {
            // Custom validation logic
        }
    }
    
  3. Add Custom Metadata Attach metadata to Stripe objects for tracking:

    $session = \Stripe\Checkout\Session::create([
        'metadata' => [
            'user_id' => auth()->id(),
            'order_id' => $order->id,
        ],
        // ... other params
    ]);
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope