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

avro/stripe-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require jdewit/stripe-bundle
    

    Enable the bundle in AppKernel.php:

    new Avro\StripeBundle\AvroStripeBundle(),
    
  2. Configure Stripe Keys Add to config.yml:

    avro_stripe:
        client_id: %stripe_client_id%
        secret_key: %stripe_secret_key%
        publishable_key: %stripe_publishable_key%
    
  3. Extend User Model Add Stripe fields to your User entity (e.g., stripeCustomerId, plan). Example:

    use Avro\StripeBundle\Document\Plan;
    /**
     * @ODM\ReferenceOne(targetDocument="Avro\StripeBundle\Document\Plan")
     */
    protected $plan;
    
  4. Import Routing Add to routing.yml:

    avro_stripe:
        resource: "@AvroStripeBundle/Resources/config/routing/routing.yml"
    
  5. Create a Plan Extend the base Plan class (e.g., Application\StripeBundle\Document\Plan):

    class Plan extends BasePlan { /* Custom logic */ }
    
  6. Run Schema Update

    php app/console doctrine:mongodb:schema:create --index
    

First Use Case: Subscribing a User to a Plan

Use the StripeManager service to create a subscription:

$stripeManager = $this->get('avro_stripe.manager');
$user = $this->getUser(); // FOSUser user
$plan = $stripeManager->findPlanById('monthly_plan_id'); // Your Stripe Plan ID

// Subscribe the user
$subscription = $stripeManager->subscribe($user, $plan);

// Redirect to payment page (handled by bundle routes)
return $this->redirect($this->generateUrl('avro_stripe_customer_new'));

Implementation Patterns

1. Workflow: Handling Payments

Frontend (Checkout)

  • Use the avro_stripe_customer_new route to render the Stripe checkout form.
  • Pre-fill user data via getStripeConnectionParameters() in your User model.
  • After submission, the bundle redirects to Stripe’s payment page.

Backend (Webhook Handling)

  • Configure Stripe webhooks to point to /stripe/hook.
  • Listen for events (e.g., avro_stripe.charge.succeeded) to update your database:
    // services.yml
    avro_stripe.listener.charge_succeeded:
        class: AppBundle\EventListener\StripeChargeListener
        tags:
            - { name: kernel.event_listener, event: avro_stripe.charge.succeeded, method: onChargeSucceeded }
    

Example Listener

use Avro\StripeBundle\Event\ChargeEvent;

class StripeChargeListener
{
    public function onChargeSucceeded(ChargeEvent $event)
    {
        $charge = $event->getCharge();
        $user = $this->getUserByStripeId($charge->customer);
        $user->setIsStripeCustomerActive(true);
        $user->getManager()->persist($user);
    }
}

2. Workflow: Plan Management

Create a Plan

Extend the base Plan class and sync with Stripe:

$plan = new Application\StripeBundle\Document\Plan();
$plan->setId('premium_plan');
$plan->setAmount(2999); // $29.99
$plan->setInterval('month');
$plan->setCurrency('usd');
$plan->setName('Premium Monthly');

$stripeManager = $this->get('avro_stripe.manager');
$stripeManager->createPlan($plan);

Update a User’s Plan

$user = $this->getUser();
$newPlan = $stripeManager->findPlanById('premium_plan_id');
$stripeManager->updateSubscription($user, $newPlan);

3. Workflow: Invoice Generation

Generate and send invoices via the StripeManager:

$invoice = $stripeManager->getInvoice($user->getStripeCustomerId(), 'in_123');
$pdf = $stripeManager->generateInvoicePdf($invoice);
return new Response($pdf, 200, ['Content-Type' => 'application/pdf']);

4. Integration with FOSUserBundle

  • Use the avro_stripe_customer_update route to let users update payment methods.
  • Redirect to /stripe/customer/update after login:
    return $this->redirect($this->generateUrl('avro_stripe_customer_update'));
    

Gotchas and Tips

Pitfalls

  1. Webhook Verification

    • Always verify Stripe webhook signatures. The bundle does not auto-verify by default.
    • Add this to your hook controller:
      use Stripe\Webhook;
      public function hookAction(Request $request)
      {
          $payload = $request->getContent();
          $sigHeader = $request->headers->get('stripe-signature');
          $event = Webhook::constructEvent($payload, $sigHeader, $this->getParameter('stripe_webhook_secret'));
          // Dispatch event...
      }
      
  2. MongoDB Indexes

    • Forgetting to run doctrine:mongodb:schema:create --index will cause slow queries on Plan and User collections.
  3. Plan ID Mismatch

    • The bundle uses Stripe’s plan.id as the Doctrine Plan entity’s @ODM\Id. Ensure IDs match exactly (case-sensitive).
  4. Hooks Not Triggering

    • If hooks_enabled: false in config.yml, events won’t dispatch. Enable with:
      avro_stripe:
          hooks_enabled: true
      
  5. Proration Issues

    • Set prorate: true in config.yml to handle partial-period charges when updating plans:
      avro_stripe:
          prorate: true
      

Debugging Tips

  1. Log Stripe Events Add a listener to log all events for debugging:

    public function onStripeEvent(StripeEvent $event)
    {
        $this->logger->debug('Stripe Event:', ['type' => $event->getType(), 'data' => $event->getData()]);
    }
    
  2. Test Webhooks Locally Use Stripe CLI to simulate webhooks:

    stripe listen --forward-to localhost:8000/stripe/hook
    
  3. Check Stripe Dashboard Verify charges/subscriptions in the Stripe Dashboard during development.


Extension Points

  1. Custom Plan Logic Override Application\StripeBundle\Document\Plan to add business rules (e.g., usage limits):

    public function isOverLimit(User $user)
    {
        return $user->getApiUsage() > $this->getLimit();
    }
    
  2. Custom Hooks Extend the bundle’s event system by creating your own listeners:

    // src/AppBundle/EventListener/CustomStripeListener.php
    class CustomStripeListener
    {
        public function onSubscriptionUpdated(SubscriptionEvent $event)
        {
            // Send Slack notification, etc.
        }
    }
    
  3. Override Templates The bundle uses Twig templates for checkout/invoice pages. Override them in app/Resources/AvroStripeBundle/views/:

    app/
    └── Resources/
        └── AvroStripeBundle/
            ├── views/
            │   ├── Customer/
            │   │   └── new.html.twig  # Override checkout form
            │   └── Invoice/
            │       └── show.html.twig # Override invoice template
    
  4. Add Custom Fields to Users Extend the getStripeConnectionParameters() method to include additional user data:

    public function getStripeConnectionParameters()
    {
        return [
            'stripe_user[email]' => $this->getEmail(),
            'stripe_user[custom_field]' => $this->getCustomField(),
        ];
    }
    

Configuration Quirks

  1. Redirect Routes Customize redirect routes in config.yml:

    avro_stripe:
        redirect_routes:
            customer_new: app_custom_checkout
            subscription_update: app_subscription_success
    
  2. Translations The bundle uses Symfony’s translator for emails/invoices. Ensure framework.translator is enabled:

    framework:
        translator: { fallbacks: ["%locale%"] }
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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