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

Cashier Paystack Laravel Package

veeqtoh/cashier-paystack

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require veeqtoh/cashier-paystack
    php artisan vendor:publish --provider="Veeqtoh\CashierPaystack\CashierPaystackServiceProvider" --tag="config"
    php artisan migrate
    
  2. Configure .env:

    PAYSTACK_SECRET_KEY=your_paystack_secret_key
    PAYSTACK_PUBLIC_KEY=your_paystack_public_key
    PAYSTACK_BASE_URL=https://api.paystack.co
    
  3. Make a Model Billable:

    use Veeqtoh\CashierPaystack\Billable;
    
    class User extends Authenticatable
    {
        use Billable;
    }
    
  4. First Use Case: Create a subscription for a user:

    $user->newSubscription('main', 'monthly-plan-id')
         ->create($paymentMethodId);
    

Where to Look First

  • README.md: Focus on the Usage section, especially Subscriptions.
  • Config File: config/cashier-paystack.php for customization.
  • Migrations: database/migrations/ for schema adjustments.

Implementation Patterns

Core Workflows

  1. Subscription Management:

    • Create:
      $user->newSubscription('main', 'plan_code')
           ->withDays(30) // Trial period
           ->create($paymentMethodId);
      
    • Update:
      $user->subscription('main')->swap('new_plan_code');
      
    • Cancel:
      $user->subscription('main')->cancel();
      
  2. Webhooks: Handle Paystack events via CashierPaystackServiceProvider:

    // In config/cashier-paystack.php
    'webhook' => [
        'enabled' => true,
        'secret' => env('PAYSTACK_WEBHOOK_SECRET'),
        'handler' => \App\Handlers\PaystackWebhookHandler::class,
    ],
    

    Implement handleEvent() in your handler:

    public function handleEvent($payload)
    {
        switch ($payload['event']) {
            case 'charge.success':
                // Logic for successful charge
                break;
        }
    }
    
  3. Payment Links: Generate pre-filled payment links:

    $paymentLink = $user->createPaymentLink(
        amount: 10000, // Amount in kobo (NGN)
        reference: 'user_123_payment',
        callback_url: route('payment.callback')
    );
    

Integration Tips

  • Laravel Cashier Compatibility: Leverage existing Cashier methods (e.g., invoices(), subscriptions()) alongside Paystack-specific features.

    $user->subscriptions()->where('ends_at', '>', now())->get();
    
  • Plan Management: Fetch Paystack plans dynamically:

    $plans = \Veeqtoh\CashierPaystack\Facades\Paystack::getPlans();
    
  • Multi-Currency: Configure default currency in .env:

    PAYSTACK_CURRENCY=NGN
    

    Override per subscription:

    $user->newSubscription('main', 'plan_code')
         ->withCurrency('USD')
         ->create($paymentMethodId);
    

Gotchas and Tips

Pitfalls

  1. Webhook Verification:

    • Always verify Paystack webhook signatures. Use the verifyWebhook helper:
      use Veeqtoh\CashierPaystack\Facades\Paystack;
      
      $isValid = Paystack::verifyWebhook($payload, $signature);
      
    • Gotcha: Forgetting to set PAYSTACK_WEBHOOK_SECRET in .env will break webhook handling.
  2. Currency Mismatch:

    • Paystack requires amounts in kobo (NGN) or the smallest unit of the currency. Hardcoding values in cents/dollars will fail.
    • Fix: Convert amounts explicitly:
      $amountInKobo = 10000; // NGN 100
      
  3. Plan Code vs. Plan ID:

    • Paystack uses plan codes (e.g., 'monthly-premium') for subscriptions, not IDs.
    • Gotcha: Passing a plan_id instead of plan_code will throw an error.
  4. Trial Periods:

    • Trials are configured in days, not timestamps. Ensure withDays() matches Paystack’s trial settings.
    • Debug: Check subscriptions table for trial_ends_at discrepancies.

Debugging

  • Log Webhook Payloads: Add logging in your webhook handler for debugging:

    \Log::debug('Paystack Webhook Payload', ['payload' => $payload]);
    
  • Paystack API Errors: Inspect the errors array in responses:

    try {
        $subscription = $user->newSubscription('main', 'plan_code')->create($paymentMethodId);
    } catch (\Exception $e) {
        \Log::error('Paystack Error:', $e->getMessage());
        // Check $e->getResponse() for Paystack-specific errors
    }
    

Extension Points

  1. Custom Fields: Attach metadata to subscriptions:

    $user->newSubscription('main', 'plan_code')
         ->withCustomFields(['custom_field' => 'value'])
         ->create($paymentMethodId);
    
  2. Middleware: Protect subscription routes:

    Route::middleware(['subscribed'])->group(function () {
        // Routes requiring active subscriptions
    });
    

    Add to app/Http/Kernel.php:

    protected $routeMiddleware = [
        'subscribed' => \Veeqtoh\CashierPaystack\Middleware\EnsureSubscription::class,
    ];
    
  3. Testing: Use Paystack’s test mode (PAYSTACK_BASE_URL=https://test.paystack.co) and mock webhooks:

    // In tests
    $this->actingAs($user)
         ->post('/subscribe', [
             'plan_code' => 'test-plan',
             'payment_method' => 'test_card_id',
         ]);
    
  4. Localization: Override Paystack’s default language:

    // In config/cashier-paystack.php
    'language' => 'fr', // French
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai