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

driveop/stripe-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started
### Minimal Steps
1. **Installation**:
   - Add the bundle via Composer:
     ```bash
     composer require driveop/stripe-bundle
     ```
   - Enable the bundle in `config/bundles.php` (Symfony 4+) or `AppKernel.php` (Symfony 3):
     ```php
     DriveOp\StripeBundle\DriveOpStripeBundle::class => ['all' => true],
     ```
   - Configure Stripe keys in `config/packages/driveop_stripe.yaml` (Symfony 4+) or `config.yml` (Symfony 3):
     ```yaml
     driveop:
         stripe:
             stripe_private_key: '%env(STRIPE_PRIVATE_KEY)%'
     ```

2. **First Use Case**:
   - Inject the `stripe_client` service into a controller/service:
     ```php
     use Symfony\Component\HttpFoundation\Request;
     use Symfony\Component\HttpFoundation\Response;

     class StripeController extends AbstractController
     {
         public function createCustomer(Request $request): Response
         {
             $stripeClient = $this->get('stripe_client');
             $token = $request->request->get('stripeToken');
             $email = $request->request->get('email');

             $customer = $stripeClient->createCustomer($token, $email, null, null);
             // Handle response (e.g., save customer ID to DB)
             return $this->json(['customerId' => $customer->id]);
         }
     }
     ```
   - Ensure your frontend (e.g., Stripe.js) collects the token and sends it to this endpoint.

---

## Implementation Patterns
### Core Workflows
1. **Customer Management**:
   - **Create**: Use `createCustomer($token, $email, $name, $phone)` to onboard users.
     ```php
     $customer = $stripeClient->createCustomer($token, 'user@example.com', 'John Doe', '+1234567890');
     ```
   - **Retrieve**: Fetch customer details via Stripe’s API (not directly supported by the bundle; use raw Stripe SDK or extend the bundle):
     ```php
     $customer = \Stripe\Customer::retrieve($customerId);
     ```
   - **Update**: Use Stripe’s `update` method (e.g., for email/name changes):
     ```php
     $customer->email = 'new@example.com';
     $customer->save();
     ```

2. **Subscriptions**:
   - **Create**: Attach a plan to a customer:
     ```php
     $subscription = $stripeClient->createSubscription($customerId, 'monthly_plan_id');
     ```
   - **Cancel/Switch**: Use Stripe’s subscription methods:
     ```php
     $subscription = \Stripe\Subscription::retrieve($subscriptionId);
     $subscription->cancel(); // or $subscription->pause();
     ```
   - **Webhooks**: Set up Symfony event listeners for Stripe webhooks (e.g., `invoice.payment_succeeded`):
     ```yaml
     # config/services.yaml
     services:
         App\EventListener\StripeWebhookListener:
             tags:
                 - { name: kernel.event_listener, event: stripe.webhook, method: onWebhook }
     ```

3. **Payments**:
   - **One-Time Charges**: Use Stripe’s `PaymentIntent` or `Charge` (extend the bundle or use raw SDK):
     ```php
     $charge = \Stripe\Charge::create([
         'amount' => 1000,
         'currency' => 'usd',
         'source' => $token,
         'description' => 'Product purchase',
     ]);
     ```

4. **Error Handling**:
   - Wrap Stripe calls in try-catch blocks to handle `Stripe\Exception\ApiErrorException`:
     ```php
     try {
         $customer = $stripeClient->createCustomer($token, $email);
     } catch (\Stripe\Exception\CardException $e) {
         // Handle card errors (e.g., invalid number)
         return $this->json(['error' => $e->getError()->message], 400);
     }
     ```

### Integration Tips
- **Frontend**: Use Stripe.js to collect payment details and send the token to your backend.
  ```javascript
  Stripe('pk_test_...').createToken(cardElement).then(function(result) {
      if (result.error) {
          // Show error
      } else {
          fetch('/create-customer', {
              method: 'POST',
              body: JSON.stringify({ stripeToken: result.token.id, email: 'user@example.com' })
          });
      }
  });
  • Testing: Use Stripe test cards (e.g., 4242 4242 4242 4242) and test mode keys.
  • Environment Variables: Store STRIPE_PRIVATE_KEY and STRIPE_PUBLIC_KEY in .env:
    STRIPE_PRIVATE_KEY=sk_test_...
    STRIPE_PUBLIC_KEY=pk_test_...
    

Gotchas and Tips

Pitfalls

  1. Limited Scope:

    • The bundle only supports SMS/WhatsApp payments (as per the README). For other payment methods (e.g., cards, SEPA), you’ll need to use the raw Stripe SDK or extend the bundle.
    • Example workaround for cards:
      $charge = \Stripe\Charge::create([
          'amount' => 1000,
          'currency' => 'usd',
          'source' => $token,
          'customer' => $customerId,
      ]);
      
  2. Missing Features:

    • No built-in support for:
      • Subscription updates (e.g., changing plans).
      • Invoices (retrieve/cancel).
      • Refunds.
    • Solution: Extend the bundle or use the Stripe PHP SDK directly:
      $subscription = \Stripe\Subscription::update($subscriptionId, ['plan' => 'new_plan_id']);
      
  3. Configuration Quirks:

    • Ensure stripe_private_key is correctly set in config/packages/driveop_stripe.yaml. If missing, the service will fail to initialize.
    • For Symfony 4+, use %env(STRIPE_PRIVATE_KEY)% for environment variables.
  4. Webhook Handling:

    • The bundle doesn’t include webhook routing out of the box. Manually set up a route and listener:
      # config/routes.yaml
      stripe_webhook:
          path: /stripe/webhook
          methods: POST
          controller: App\Controller\StripeWebhookController::handleWebhook
      

Debugging Tips

  1. Enable Stripe Logging: Add to config/packages/driveop_stripe.yaml:

    driveop:
        stripe:
            stripe_private_key: '%env(STRIPE_PRIVATE_KEY)%'
            debug: true  # Enable if supported (check bundle docs)
    
    • If debug isn’t supported, use Stripe’s built-in logging:
      \Stripe\Stripe::setApiKey($privateKey);
      \Stripe\Stripe::setLogLevel(\Stripe\Log::DEBUG); // Enable debug logs
      
  2. Common Errors:

    • InvalidRequestError: Ensure the token/email is valid and the Stripe keys are correct.
    • AuthenticationError: Verify stripe_private_key is set and correct.
    • MissingParameter: Check all required parameters (e.g., $token cannot be null).
  3. Testing Webhooks Locally: Use tools like ngrok to expose your local server to Stripe’s webhook endpoint:

    ngrok http 8000  # Forward localhost:8000 to a public URL
    

    Then configure the webhook URL in the Stripe Dashboard.

Extension Points

  1. Custom Services: Create a decorator or child service to extend functionality:

    // src/Service/StripeClientDecorator.php
    class StripeClientDecorator extends DriveOp\StripeBundle\Service\StripeClient
    {
        public function createCustomerWithMetadata($token, $email, array $metadata)
        {
            $customer = parent::createCustomer($token, $email);
            $customer->metadata = $metadata;
            $customer->save();
            return $customer;
        }
    }
    

    Register it as a service in config/services.yaml:

    services:
        App\Service\StripeClientDecorator:
            decorates: 'stripe_client'
            arguments: ['@App\Service\StripeClientDecorator.inner']
    
  2. Event Dispatching: Trigger Symfony events after Stripe operations (e.g., customer.created):

    // Inside your service
    $dispatcher->dispatch(new CustomerCreatedEvent($customer));
    

    Listen to events in controllers or other services.

  3. Repository Pattern: Create a repository class to abstract Stripe operations:

    // src/Repository/StripeCustomerRepository.php
    class StripeCustomerRepository
    {
        private $stripeClient;
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle