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

Lara Paystack Laravel Package

sdkcodes/lara-paystack

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require sdkcodes/lara-paystack
    

    Publish the config file (optional, but recommended for customization):

    php artisan vendor:publish --provider="Sdkcodes\LaraPaystack\LaraPaystackServiceProvider"
    
  2. Configure .env Add your Paystack API keys:

    PAYSTACK_SECRET_KEY=your_secret_key
    PAYSTACK_PUBLIC_KEY=your_public_key
    
  3. First Use Case: Initialize a Transaction In a controller or service, initialize a transaction with minimal data:

    use Sdkcodes\LaraPaystack\Facades\LaraPaystack;
    
    $paymentData = [
        'email' => 'customer@example.com',
        'amount' => 10000, // Amount in kobo (10000 = ₦100)
        'reference' => 'UNIQUE-' . time(),
        'callback_url' => route('payment.callback'),
    ];
    
    $response = LaraPaystack::initialize($paymentData);
    return redirect()->away($response['data']['authorization_url']);
    
  4. Verify Callback Handle the Paystack callback in a route:

    Route::post('/payment/callback', [PaymentController::class, 'handleCallback']);
    
    public function handleCallback(Request $request)
    {
        $data = $request->all();
        $response = LaraPaystack::verifyTransaction($data['reference']);
        return view('payment.success', ['response' => $response]);
    }
    

Implementation Patterns

Common Workflows

1. Transaction Initialization

  • Basic Initialization:
    $response = LaraPaystack::initialize([
        'email' => 'user@example.com',
        'amount' => 50000, // ₦500
        'reference' => 'REF-' . Str::uuid(),
        'callback_url' => route('callback'),
        'metadata' => ['custom_field' => 'value'],
    ]);
    
  • Redirect to Paystack:
    return redirect()->away($response['data']['authorization_url']);
    

2. Handling Callbacks

  • Verify Transaction:
    $response = LaraPaystack::verifyTransaction($reference);
    if ($response['status']) {
        // Payment successful
        $transaction = $response['data'];
    }
    
  • Webhook Handling (for server-to-server verification):
    public function handleWebhook(Request $request)
    {
        $event = $request->event;
        $data = $request->data;
    
        if (LaraPaystack::verifyWebhook($event, $data)) {
            // Process the event (e.g., charge.success, transfer.received)
        }
    }
    

3. Recurring Payments (Subscriptions)

  • Create Plan:
    $plan = LaraPaystack::createPlan([
        'name' => 'Premium Subscription',
        'amount' => 20000, // ₦200
        'interval' => 'monthly',
        'currency' => 'NGN',
    ]);
    
  • Subscribe Customer:
    $subscription = LaraPaystack::subscribeCustomer([
        'customer' => $customerId, // From Paystack
        'plan' => $plan['data']['code'],
        'start_date' => now()->addDay(),
    ]);
    

4. Customer Management

  • Create Customer:
    $customer = LaraPaystack::createCustomer([
        'email' => 'user@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
    ]);
    
  • List Customers:
    $customers = LaraPaystack::listCustomers(['perPage' => 10]);
    

5. Transfer Money

  • Transfer to Bank Account:
    $transfer = LaraPaystack::transfer([
        'source' => 'balance', // or 'account'
        'amount' => 10000,
        'reason' => 'Refund',
        'recipient' => 'recipient_code_or_account_number',
        'reference' => 'TRANS-' . time(),
    ]);
    

Integration Tips

Laravel Services

Bind the package to a service container for dependency injection:

// In a service provider
$this->app->bind(
    \Sdkcodes\LaraPaystack\LaraPaystack::class,
    function ($app) {
        return new \Sdkcodes\LaraPaystack\LaraPaystack(
            $app->make('config')->get('larapaystack')
        );
    }
);

Middleware for Authenticated Payments

Protect payment routes with middleware to ensure only authenticated users can initiate transactions:

Route::middleware(['auth'])->group(function () {
    Route::post('/init-payment', [PaymentController::class, 'initiate']);
});

Logging Responses

Log Paystack API responses for debugging:

$response = LaraPaystack::initialize($data);
\Log::info('Paystack Response', ['response' => $response]);

Testing

Use mocking to test Paystack interactions:

$this->mock(LaraPaystack::class)->shouldReceive('initialize')
    ->once()
    ->andReturn(['status' => true, 'data' => ['authorization_url' => 'https://test.com']]);

Gotchas and Tips

Pitfalls

1. Amount in Kobo

  • Paystack expects amounts in kobo (100 kobo = ₦1). Forgetting to multiply by 100 will result in incorrect charges.
  • Fix: Always ensure amounts are in kobo:
    $amountInNaira = 100; // ₦100
    $amountInKobo = $amountInNaira * 100; // 10000
    

2. Callback URL Mismatch

  • Paystack redirects to the exact callback URL provided during initialization. Typos or missing trailing slashes will break the flow.
  • Fix: Use absolute URLs and validate them:
    $callbackUrl = url('/payment/callback');
    

3. Webhook Verification

  • Always verify webhook signatures to prevent spoofing. The package provides verifyWebhook(), but ensure you use it:
    if (!LaraPaystack::verifyWebhook($event, $data)) {
        abort(403, 'Invalid webhook signature');
    }
    

4. Rate Limits

  • Paystack has rate limits (e.g., 10 requests/second). Exceeding limits may temporarily block your API key.
  • Fix: Implement retries with exponential backoff:
    use Illuminate\Support\Facades\Http;
    
    $response = Http::withOptions(['timeout' => 30])
        ->retry(3, 100)
        ->post('https://api.paystack.co/transaction/initialize', $data);
    

5. Deprecated Endpoints

  • The package is outdated (last release: 2020). Some Paystack endpoints may have changed or been deprecated.
  • Fix: Check Paystack’s API docs for updates and manually extend the package if needed:
    // Extend LaraPaystack class
    namespace App\Services;
    
    use Sdkcodes\LaraPaystack\LaraPaystack as BaseLaraPaystack;
    
    class LaraPaystack extends BaseLaraPaystack
    {
        public function newEndpoint($data)
        {
            return $this->post('new-endpoint', $data);
        }
    }
    

Debugging Tips

1. Enable Debug Mode

Add this to your .env to log API requests/responses:

LARAPAYSTACK_DEBUG=true

2. Inspect Raw Responses

Dump the raw response from Paystack to debug issues:

$response = LaraPaystack::initialize($data);
dd($response); // Check for errors in 'message' or 'status'

3. Test Mode

Use Paystack’s test mode with test cards (e.g., 5431748765432105) to avoid real charges during development.

4. Common Error Codes

  • invalid_reference: Duplicate or invalid reference.
  • insufficient_balance: Insufficient funds in Paystack account.
  • invalid_signature: Webhook signature verification failed.

Extension Points

1. Customize Request Headers

Override headers globally in the config (config/larapaystack.php):

'headers' => [
    'Accept' => 'application/json
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor