## 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' })
});
}
});
4242 4242 4242 4242) and test mode keys.STRIPE_PRIVATE_KEY and STRIPE_PUBLIC_KEY in .env:
STRIPE_PRIVATE_KEY=sk_test_...
STRIPE_PUBLIC_KEY=pk_test_...
Limited Scope:
$charge = \Stripe\Charge::create([
'amount' => 1000,
'currency' => 'usd',
'source' => $token,
'customer' => $customerId,
]);
Missing Features:
$subscription = \Stripe\Subscription::update($subscriptionId, ['plan' => 'new_plan_id']);
Configuration Quirks:
stripe_private_key is correctly set in config/packages/driveop_stripe.yaml. If missing, the service will fail to initialize.%env(STRIPE_PRIVATE_KEY)% for environment variables.Webhook Handling:
# config/routes.yaml
stripe_webhook:
path: /stripe/webhook
methods: POST
controller: App\Controller\StripeWebhookController::handleWebhook
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)
debug isn’t supported, use Stripe’s built-in logging:
\Stripe\Stripe::setApiKey($privateKey);
\Stripe\Stripe::setLogLevel(\Stripe\Log::DEBUG); // Enable debug logs
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).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.
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']
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.
Repository Pattern: Create a repository class to abstract Stripe operations:
// src/Repository/StripeCustomerRepository.php
class StripeCustomerRepository
{
private $stripeClient;
How can I help you explore Laravel packages today?