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

Stripe Bundle Laravel Package

bartpie/stripe-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require flosch/stripe-bundle
    

    For Symfony 4+, use the 2.0.0 branch/releases.

  2. Register the Bundle: Add to config/bundles.php (Symfony 4+) or AppKernel.php (Symfony 3):

    Flosch\Bundle\StripeBundle\FloschStripeBundle::class => ['all' => true],
    
  3. Configure API Key: Add to config/packages/flosch_stripe.yaml (Symfony 4+) or config.yml (Symfony 3):

    flosch_stripe:
        stripe_api_key: "%env(STRIPE_SECRET_KEY)%"
    

    Ensure STRIPE_SECRET_KEY is in your .env.

  4. First Use Case: Inject the stripe.client service into a controller/service:

    use Flosch\Bundle\StripeBundle\Stripe\StripeClient;
    
    class PaymentController extends AbstractController
    {
        public function createCustomer(StripeClient $stripe): Response
        {
            $customer = $stripe->customers()->create([
                'email' => 'user@example.com',
                'name' => 'John Doe',
            ]);
            // Handle response...
        }
    }
    

Implementation Patterns

Core Workflows

  1. Service Injection: Prefer dependency injection over manual service retrieval:

    public function __construct(private StripeClient $stripe) {}
    
  2. Common API Operations:

    • Customers:
      $customer = $stripe->customers()->create(['email' => 'user@example.com']);
      $customer->update(['name' => 'Updated Name']);
      
    • Payments:
      $charge = $stripe->charges()->create([
          'amount' => 1000,
          'currency' => 'usd',
          'source' => 'tok_visa',
          'customer' => $customer->id,
      ]);
      
    • Subscriptions (via flosch.stripe.subscription helper):
      $subscription = $stripe->subscriptions()->create([
          'customer' => $customer->id,
          'items' => [['price' => 'price_123']],
      ]);
      
  3. Stripe Connect: Use the flosch.stripe.connect service for platform integrations:

    $account = $stripe->connect()->accounts()->create([
        'type' => 'express',
        'country' => 'US',
    ]);
    
  4. Webhooks: Register a controller to handle Stripe events:

    # config/routes.yaml
    stripe_webhook:
        path: /stripe/webhook
        controller: App\Controller\StripeWebhookController::handle
    
    public function handle(Request $request, StripeClient $stripe): Response
    {
        $payload = $request->getContent();
        $sigHeader = $request->headers->get('Stripe-Signature');
        $event = $stripe->webhooks()->constructEvent($payload, $sigHeader, 'whsec_yourwebhooksecret');
    
        // Handle event...
    }
    

Integration Tips

  • Environment-Specific Keys: Use Symfony’s %env() in config.yml to switch keys per environment:

    flosch_stripe:
        stripe_api_key: "%env(STRIPE_KEY_%kernel.environment%)%"
    
  • Testing: Mock the StripeClient service in tests:

    $this->container->set('flosch.stripe.client', $this->createMock(StripeClient::class));
    
  • Idempotency: Leverage Stripe’s idempotency keys for safe retries:

    $charge = $stripe->charges()->create([
        'amount' => 1000,
        'currency' => 'usd',
        'idempotency_key' => 'unique_key_here',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Symfony Version Mismatch:

    • Issue: Using 1.x with Symfony 4+ or 2.x with Symfony 3.
    • Fix: Explicitly target the correct branch/release in composer.json:
      "require": {
          "flosch/stripe-bundle": "2.*"
      }
      
  2. API Key Exposure:

    • Issue: Hardcoding keys in config.yml.
    • Fix: Always use %env() and restrict .env to gitignore.
  3. Webhook Verification:

    • Issue: Silent failures if Stripe-Signature header is missing or invalid.
    • Fix: Validate headers explicitly:
      if (!$sigHeader) {
          throw new \RuntimeException('Stripe signature header missing');
      }
      
  4. Deprecated Methods:

Debugging

  • Enable Stripe Logging: Configure the underlying SDK to log requests/responses:

    flosch_stripe:
        stripe_api_key: "%env(STRIPE_SECRET_KEY)%"
        options:
            api_version: '2023-08-16'
            log_level: debug  # Options: quiet, body, verbose
    
  • Test Mode: Use Stripe’s test mode (pk_test_..., sk_test_...) in development:

    flosch_stripe:
        stripe_api_key: "%env(STRIPE_TEST_KEY)%"
    

Extension Points

  1. Custom Helpers: Extend the StripeClient by creating a decorator:

    // src/Service/StripeClientDecorator.php
    class StripeClientDecorator implements StripeClientInterface
    {
        public function __construct(private StripeClient $client) {}
    
        public function createCustomerWithDefaultPlan(array $data): Customer
        {
            $data['subscription'] = 'default_plan_id';
            return $this->client->customers()->create($data);
        }
    }
    

    Register as a service:

    services:
        App\Service\StripeClientDecorator:
            decorates: 'flosch.stripe.client'
            arguments: ['@App\Service\StripeClientDecorator.inner']
    
  2. Event Listeners: Subscribe to Stripe events via Symfony’s event dispatcher:

    $stripe->on('charge.succeeded', function (Charge $charge) {
        // Custom logic (e.g., update user record)
    });
    
  3. Configuration Overrides: Override bundle config per environment:

    # config/packages/dev/flosch_stripe.yaml
    flosch_stripe:
        options:
            api_version: '2023-08-16'
            idempotency: true
    
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