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 Php Laravel Package

stripe/stripe-php

Official Stripe PHP SDK for accessing the Stripe API. Install via Composer, configure your API key, and use resource classes that map to Stripe objects and endpoints. Supports PHP 7.2+ (older versions being phased out).

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require stripe/stripe-php

Ensure vendor/autoload.php is included in your project.

  1. Initialize Client:

    require_once 'vendor/autoload.php';
    \Stripe\Stripe::setApiKey('sk_test_...'); // Set API key globally
    // OR
    $stripe = new \Stripe\StripeClient('sk_test_...'); // Per-request client
    
  2. First Use Case: Create a customer and charge them:

    $customer = \Stripe\Customer::create([
        'email' => 'user@example.com',
        'name' => 'John Doe',
        'payment_method' => 'pm_123', // Pre-created payment method
    ]);
    $charge = \Stripe\Charge::create([
        'amount' => 1000, // $10.00
        'currency' => 'usd',
        'customer' => $customer->id,
    ]);
    

Key Entry Points

  • Legacy vs. Modern: Prefer \Stripe\StripeClient (v7.33.0+) over legacy \Stripe\Stripe for new projects. Example:

    $client = new \Stripe\StripeClient('sk_test_...');
    $customer = $client->customers->create([...]);
    
  • Service Objects: Use $client->customers, $client->charges, etc., for type-safe interactions.


Implementation Patterns

1. Service Layer Integration

Workflow:

  • Create a StripeService class to encapsulate Stripe logic.
  • Example:
    class StripeService {
        private $client;
    
        public function __construct() {
            $this->client = new \Stripe\StripeClient(config('stripe.key'));
        }
    
        public function createSubscription($userId, $planId) {
            $customer = $this->client->customers->create([
                'email' => $userId . '@example.com',
            ]);
            return $this->client->subscriptions->create([
                'customer' => $customer->id,
                'items' => [['price' => $planId]],
            ]);
        }
    }
    

Laravel-Specific:

  • Use Laravel's Service Providers to bind the StripeClient:
    // app/Providers/StripeServiceProvider.php
    public function register() {
        $this->app->singleton(\Stripe\StripeClient::class, function ($app) {
            return new \Stripe\StripeClient(config('stripe.key'));
        });
    }
    

2. Webhook Handling

Workflow:

  • Use Laravel's route:webhook or a dedicated controller.
  • Validate signatures and handle events:
    use Stripe\Webhook;
    
    Route::post('/stripe/webhook', function (Request $request) {
        $payload = $request->getContent();
        $sigHeader = $request->header('Stripe-Signature');
        $event = Webhook::constructEvent($payload, $sigHeader, config('stripe.webhook_secret'));
    
        // Handle the event
        switch ($event->type) {
            case 'payment_intent.succeeded':
                $paymentIntent = $event->data->object;
                // Fulfill the purchase...
                break;
        }
        return response('OK');
    });
    

Tip:

  • Store webhook secrets in .env:
    STRIPE_WEBHOOK_SECRET=whsec_...
    

3. Idempotency and Retries

Pattern:

  • Use idempotency keys for critical operations (e.g., charges, subscriptions).
  • Configure retries for transient failures:
    \Stripe\Stripe::setMaxNetworkRetries(3); // Global setting
    // OR per-request
    $charge = \Stripe\Charge::create([
        'amount' => 1000,
        'currency' => 'usd',
        'customer' => 'cus_123',
        'idempotency_key' => 'unique_key_for_this_request',
    ]);
    

4. Testing

Mocking Stripe:

  • Use stripe-mock for unit tests:
    composer require stripe/mock
    
    Example test:
    use Stripe\Mock\WebhookTestHelper;
    
    public function testWebhook() {
        $payload = file_get_contents(__DIR__ . '/fixtures/payment_intent_succeeded.json');
        $sig = 'whsec_...';
        $event = Webhook::constructEvent($payload, $sig, config('stripe.webhook_secret'));
        $this->assertEquals('payment_intent.succeeded', $event->type);
    }
    

Integration Tests:

  • Use Laravel's HttpTests with a test Stripe account (e.g., sk_test_...).

5. Error Handling

Pattern:

  • Catch \Stripe\Exception\ApiErrorException for API errors:
    try {
        $charge = \Stripe\Charge::create([...]);
    } catch (\Stripe\Exception\ApiErrorException $e) {
        Log::error('Stripe error: ' . $e->getMessage());
        return response()->json(['error' => 'Payment failed'], 402);
    }
    

Common Errors:

  • invalid_request_error: Validate input data.
  • authentication_error: Check API keys/secrets.
  • rate_limit_error: Implement exponential backoff.

Gotchas and Tips

1. API Key Management

  • Gotcha: Hardcoding keys in code violates security best practices. Fix: Use Laravel's .env and config('stripe.key'). Example .env:

    STRIPE_KEY=sk_test_...
    STRIPE_WEBHOOK_SECRET=whsec_...
    
  • Tip: Use Stripe Connect for multi-account setups:

    $client = new \Stripe\StripeClient('sk_test_...', [
        'stripe_account' => 'acct_123',
    ]);
    

2. Legacy vs. Modern API

  • Gotcha: Mixing legacy (\Stripe\Stripe) and modern (\Stripe\StripeClient) APIs can cause issues. Fix: Stick to one pattern per project. Migrate using the official guide.

  • Tip: Modern API supports dependency injection:

    $client = new \Stripe\StripeClient($apiKey, [
        'httpClient' => $customHttpClient,
    ]);
    

3. Webhook Delays

  • Gotcha: Webhooks can be delayed or retried by Stripe. Fix:
    • Use idempotency in your handler logic.
    • Implement a database-backed queue (e.g., Laravel Queues) for async processing.

4. Payment Method Attachment

  • Gotcha: Detached payment methods (e.g., pm_123) require re-attachment. Fix: Attach before use:
    $paymentMethod = \Stripe\PaymentMethod::attach('pm_123', [
        'customer' => 'cus_123',
    ]);
    

5. Undocumented Features

  • Tip: Use rawRequest for beta/undocumented endpoints (v16+):
    $response = $client->rawRequest('post', '/v1/beta_endpoint', [
        'data' => '...',
    ], [
        'stripe_version' => '2023-10-16',
    ]);
    

6. Performance Optimization

  • Tip: Reuse StripeClient instances (they are thread-safe). Example in Laravel:

    // app/Providers/AppServiceProvider.php
    public function boot() {
        \Stripe\Stripe::setApiKey(config('stripe.key'));
    }
    
  • Gotcha: Avoid creating new clients per request in high-traffic apps.


7. Debugging

  • Tip: Enable logging for API requests:

    \Stripe\Stripe::setLogger(new \Monolog\Logger('stripe', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/stripe.log')),
    ]));
    
  • Common Debug Commands:

    • List customers:
      $customers = \Stripe\Customer::all(['limit' => 10]);
      
    • Inspect last response:
      $customer = \Stripe\Customer::create([...]);
      $response = $customer->getLastResponse();
      

8. **TLS

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata