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. Accept Payments with Paystack in Laravel
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in Laravel

To accept Paystack payments in Laravel, create a PaymentController that uses the Laravel HTTP client to initialize a transaction with the Paystack API. Redirect the user to Paystack checkout. In the callback route, verify the transaction using your secret key and mark the order as paid.

In this article

  1. 1. Setup
  2. 2. Order Model and Migration
  3. 3. Payment Controller
  4. 4. Routes
  5. 5. CSRF Exemption for Webhooks
  6. 6. JSON API for SPA Frontends
  7. 7. Production Checklist
  8. 8. Ship Payments Faster

Setup

Add your Paystack keys to .env:

PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx
PAYSTACK_PUBLIC_KEY=pk_test_xxxxxxxxxxxxxxxxxxxxx

Add them to config/services.php:

// config/services.php
'paystack' => [
    'secret_key' => env('PAYSTACK_SECRET_KEY'),
    'public_key' => env('PAYSTACK_PUBLIC_KEY'),
],

Order Model and Migration

php artisan make:model Order -m
// database/migrations/create_orders_table.php
Schema::create('orders', function (Blueprint $table) {
    $table->id();
    $table->string('reference')->unique();
    $table->string('email');
    $table->integer('amount'); // in kobo
    $table->string('currency', 3)->default('NGN');
    $table->boolean('paid')->default(false);
    $table->timestamp('paid_at')->nullable();
    $table->timestamps();
});

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Payment Controller

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

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class PaymentController extends Controller
{
    public function initialize(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'amount' => 'required|numeric|min:1',
        ]);

        $reference = 'order_' . Str::random(12);

        $order = Order::create([
            'reference' => $reference,
            'email' => $request->email,
            'amount' => (int) ($request->amount * 100),
        ]);

        $response = Http::withToken(config('services.paystack.secret_key'))
            ->post('https://api.paystack.co/transaction/initialize', [
                'email' => $request->email,
                'amount' => $order->amount,
                'reference' => $reference,
                'callback_url' => route('payment.callback'),
            ]);

        $data = $response->json();

        if ($data['status'] ?? false) {
            return redirect($data['data']['authorization_url']);
        }

        return back()->with('error', $data['message'] ?? 'Failed');
    }

    public function callback(Request $request)
    {
        $reference = $request->query('reference') ?? $request->query('trxref');

        if (!$reference) {
            return redirect('/')->with('error', 'Missing reference');
        }

        $response = Http::withToken(config('services.paystack.secret_key'))
            ->get('https://api.paystack.co/transaction/verify/' . $reference);

        $data = $response->json();

        if (($data['status'] ?? false) && $data['data']['status'] === 'success') {
            $order = Order::where('reference', $reference)->first();

            if ($order && $data['data']['amount'] === $order->amount) {
                Order::where('reference', $reference)
                    ->where('paid', false)
                    ->update(['paid' => true, 'paid_at' => now()]);

                return view('payment.success', ['order' => $order]);
            }
        }

        return view('payment.failed');
    }
}

Routes

// routes/web.php
use App\Http\Controllers\PaymentController;

Route::post('/pay', [PaymentController::class, 'initialize'])->name('payment.initialize');
Route::get('/payment/callback', [PaymentController::class, 'callback'])->name('payment.callback');

CSRF Exemption for Webhooks

Paystack webhook requests will not have Laravel CSRF tokens. Exempt the webhook route:

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

The callback route is a GET request, so CSRF does not apply to it.

JSON API for SPA Frontends

// For API routes (routes/api.php)
Route::post('/pay', function (Request $request) {
    $reference = 'order_' . Str::random(12);

    $response = Http::withToken(config('services.paystack.secret_key'))
        ->post('https://api.paystack.co/transaction/initialize', [
            'email' => $request->email,
            'amount' => (int) ($request->amount * 100),
            'reference' => $reference,
        ]);

    $data = $response->json();

    if ($data['status'] ?? false) {
        return response()->json([
            'authorization_url' => $data['data']['authorization_url'],
            'access_code' => $data['data']['access_code'],
            'reference' => $data['data']['reference'],
        ]);
    }

    return response()->json(['error' => $data['message'] ?? 'Failed'], 400);
});

Production Checklist

  1. Set up webhooks. See Handle Paystack Webhooks in Laravel.
  2. Use HTTPS. Required for callback and webhook URLs.
  3. Validate amounts server-side. Look up prices from your database.
  4. Switch keys. Use sk_live_ in production .env.
  5. Prevent double-granting. The where('paid', false) condition handles this.

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

  • ✓Laravel HTTP client (Http::withToken()) makes Paystack API calls clean and readable.
  • ✓Store your Paystack keys in .env and access them with config() or env().
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Multiply by 100 before sending to Paystack.
  • ✓Exempt callback and webhook routes from CSRF verification in VerifyCsrfToken middleware.
  • ✓Always verify the transaction server-side. The redirect alone is not proof of payment.
  • ✓No external packages needed. Laravel HTTP client handles all the Paystack REST API calls.

Frequently Asked Questions

Do I need a Paystack Laravel package?
No. Laravel HTTP client handles all the REST API calls cleanly. Community packages exist but add unnecessary abstraction. The Http::withToken() syntax is already concise.
Can I use Laravel Cashier with Paystack?
Laravel Cashier is built for Stripe and Paddle. It does not support Paystack. Build your Paystack integration directly using the HTTP client and Paystack REST API.
How do I handle multiple currencies in Laravel?
Pass the currency parameter when initializing. Store the expected currency in your Order model and verify it matches during payment verification.
Should I use Laravel Jobs for payment processing?
For webhook processing, yes. Dispatch a job from your webhook controller so the response returns immediately. For the callback route, inline processing is fine since the user is waiting for a response.

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

Accepting Mobile Money Payments Through Paystack

Mobile money is the dominant payment method in Ghana, and Paystack supports MTN MoMo, AirtelTigo Money, and Vodafone Cash. This guide covers how mobile money payments work through both the hosted checkout and the Charge API, including handling the asynchronous approval flow.

Read more

Paystack Dispute Deadline Missed: What Happens

When you miss a Paystack dispute deadline, the money is automatically returned to the cardholder. This decision is final and cannot be reversed. This guide covers what happens, why it happens, and how to build alerts so it never happens to you.

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.