McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Handle Paystack Webhooks in Laravel
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Handle Paystack Webhooks in Laravel

To handle Paystack webhooks in Laravel, add the webhook route to the CSRF exceptions, create a controller that reads the raw body with request()->getContent(), computes an HMAC SHA-512 hash, compares it to the X-Paystack-Signature header, and dispatches a Job for processing. Return response 200.

In this article

  1. 1. CSRF Exemption
  2. 2. Webhook Controller
  3. 3. Webhook Processing Job
  4. 4. Route Configuration
  5. 5. Log Webhook Events
  6. 6. Testing
  7. 7. Ship Payments Faster

CSRF Exemption

// app/Http/Middleware/VerifyCsrfToken.php
protected $except = [
    'webhooks/paystack',
];

Without this, Laravel returns 419 for all Paystack webhook requests because they lack a CSRF token.

Webhook Controller

// app/Http/Controllers/WebhookController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

class WebhookController extends Controller
{
    public function handlePaystack(Request $request)
    {
        $signature = $request->header('X-Paystack-Signature');

        if (!$signature) {
            return response('Missing signature', 400);
        }

        $body = $request->getContent();
        $secret = config('services.paystack.secret_key');

        $computedHash = hash_hmac('sha512', $body, $secret);

        if (!hash_equals($computedHash, $signature)) {
            return response('Invalid signature', 400);
        }

        $event = json_decode($body, true);

        // Process asynchronously
        dispatch(new \App\Jobs\ProcessPaystackWebhook($event));

        return response('OK', 200);
    }
}

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Webhook Processing Job

// app/Jobs/ProcessPaystackWebhook.php
namespace App\Jobs;

use App\Services\PaystackService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;

class ProcessPaystackWebhook implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    private array $event;

    public function __construct(array $event)
    {
        $this->event = $event;
    }

    public function handle(PaystackService $paystack): void
    {
        $eventType = $this->event['event'] ?? '';
        $data = $this->event['data'] ?? [];

        switch ($eventType) {
            case 'charge.success':
                $reference = $data['reference'] ?? null;
                if ($reference) {
                    $paystack->verifyAndFulfill($reference);
                }
                break;

            case 'subscription.create':
                // Handle new subscription
                break;

            case 'invoice.payment_failed':
                // Handle failed renewal
                break;
        }
    }
}

Route Configuration

// routes/web.php
Route::post('/webhooks/paystack', [WebhookController::class, 'handlePaystack']);

Set the webhook URL in your Paystack dashboard: https://yourdomain.com/webhooks/paystack

Log Webhook Events

// Create a migration for webhook events
Schema::create('webhook_events', function (Blueprint $table) {
    $table->id();
    $table->string('event_type');
    $table->string('reference')->nullable();
    $table->json('payload');
    $table->boolean('processed')->default(false);
    $table->timestamps();
});

// In the controller, log before dispatching:
\App\Models\WebhookEvent::create([
    'event_type' => $event['event'] ?? 'unknown',
    'reference' => $event['data']['reference'] ?? null,
    'payload' => $event,
]);

Testing

// tests/Feature/WebhookTest.php
public function test_valid_webhook()
{
    $payload = json_encode([
        'event' => 'charge.success',
        'data' => ['reference' => 'test_123', 'amount' => 500000],
    ]);

    $signature = hash_hmac('sha512', $payload, config('services.paystack.secret_key'));

    $response = $this->postJson('/webhooks/paystack', json_decode($payload, true), [
        'X-Paystack-Signature' => $signature,
    ]);

    $response->assertStatus(200);
}

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Add the webhook route to VerifyCsrfToken $except array. Paystack does not send CSRF tokens.
  • ✓Use request()->getContent() for the raw body. Do not use request()->all() as it gives parsed data.
  • ✓Dispatch Laravel Jobs for async webhook processing. Return 200 immediately.
  • ✓Use hash_hmac("sha512", $body, $secret) and hash_equals() for signature verification.
  • ✓Make handlers idempotent. Paystack retries failed deliveries.
  • ✓Log every webhook event in a database table for debugging.

Frequently Asked Questions

Why does my webhook return 419?
You forgot to add the webhook route to the CSRF exceptions in VerifyCsrfToken middleware. Paystack requests do not include Laravel CSRF tokens.
Can I use Laravel Events instead of Jobs?
Yes. Fire a PaystackWebhookReceived event and handle it with a listener. Both approaches work. Jobs are simpler for direct processing. Events are better if multiple parts of your app need to react to the same webhook.
Should I use request()->all() or request()->getContent()?
Use request()->getContent() for the raw body bytes. You need these for HMAC verification. request()->all() gives you parsed data, which may differ from the original bytes.
How do I test webhooks locally?
Use ngrok to expose your local server. Set the ngrok HTTPS URL as your webhook URL in the Paystack dashboard. For automated tests, compute the HMAC signature in your test and send it in the request header.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Paystack Dedicated Virtual Accounts: Complete Implementation

Dedicated Virtual Accounts give each of your customers a permanent bank account number that routes deposits directly to your Paystack balance. This guide covers creating DVAs, assigning them to customers, detecting deposits via webhooks, and reconciling incoming funds.

Read more

Paystack Dedicated Account Deposit Not Reflecting

A customer sends money to their Dedicated Virtual Account, but your system shows nothing. The deposit is not reflecting. Here is how to trace the problem from bank to webhook to database.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.