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

Build Paystack Subscriptions in Laravel

To build Paystack subscriptions in Laravel, create a plan via the API, initialize a transaction with the plan code, handle subscription webhooks with Jobs, track status in an Eloquent model, and use middleware to gate premium features behind active subscription checks.

In this article

  1. 1. Subscription Model
  2. 2. Subscribe a Customer
  3. 3. Webhook Handlers
  4. 4. Subscription Middleware
  5. 5. Cancel Subscription
  6. 6. Ship Payments Faster

Subscription Model

// database/migrations/create_subscriptions_table.php
Schema::create('subscriptions', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('subscription_code')->unique();
    $table->string('plan_code');
    $table->string('email_token');
    $table->string('status')->default('active');
    $table->timestamp('next_payment_date')->nullable();
    $table->timestamps();
});

Subscribe a Customer

public function subscribe(Request $request)
{
    $response = Http::withToken(config('services.paystack.secret_key'))
        ->post('https://api.paystack.co/transaction/initialize', [
            'email' => auth()->user()->email,
            'plan' => $request->plan_code,
            'callback_url' => route('subscription.callback'),
        ]);

    $data = $response->json();

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

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

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Webhook Handlers

// In ProcessPaystackWebhook Job
case 'subscription.create':
    $user = \App\Models\User::where('email', $data['customer']['email'])->first();
    if ($user) {
        \App\Models\Subscription::updateOrCreate(
            ['user_id' => $user->id],
            [
                'subscription_code' => $data['subscription_code'],
                'plan_code' => $data['plan']['plan_code'],
                'email_token' => $data['email_token'] ?? '',
                'status' => 'active',
                'next_payment_date' => $data['next_payment_date'] ?? null,
            ]
        );
    }
    break;

case 'invoice.payment_failed':
    $subCode = $data['subscription']['subscription_code'] ?? null;
    if ($subCode) {
        \App\Models\Subscription::where('subscription_code', $subCode)
            ->update(['status' => 'past_due']);
    }
    break;

case 'subscription.disable':
    $subCode = $data['subscription_code'] ?? null;
    if ($subCode) {
        \App\Models\Subscription::where('subscription_code', $subCode)
            ->update(['status' => 'cancelled']);
    }
    break;

Subscription Middleware

// app/Http/Middleware/EnsureActiveSubscription.php
namespace App\Http\Middleware;

use Closure;

class EnsureActiveSubscription
{
    public function handle($request, Closure $next)
    {
        $user = $request->user();

        if (!$user || !$user->subscription || $user->subscription->status !== 'active') {
            return redirect('/subscribe');
        }

        return $next($request);
    }
}

// In routes:
Route::middleware(['auth', 'subscription'])->group(function () {
    Route::get('/premium', [PremiumController::class, 'index']);
});

Cancel Subscription

public function cancel()
{
    $sub = auth()->user()->subscription;

    if (!$sub) {
        return back()->with('error', 'No subscription found');
    }

    $response = Http::withToken(config('services.paystack.secret_key'))
        ->post('https://api.paystack.co/subscription/disable', [
            'code' => $sub->subscription_code,
            'token' => $sub->email_token,
        ]);

    if ($response->json()['status'] ?? false) {
        $sub->update(['status' => 'cancelled']);
        return redirect('/dashboard')->with('success', 'Subscription cancelled');
    }

    return back()->with('error', 'Cancellation failed');
}

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

  • ✓Paystack manages recurring billing. You create plans, subscribe customers, and Paystack charges automatically.
  • ✓Use Eloquent for subscription tracking. A Subscription model with status, subscription_code, and email_token.
  • ✓Webhook events are the source of truth. Handle subscription.create, charge.success, and invoice.payment_failed.
  • ✓Laravel middleware gates premium routes behind active subscription checks.
  • ✓Store email_token from the subscription.create webhook for cancellation.
  • ✓Dispatch Jobs from your webhook handler for reliable async processing.

Frequently Asked Questions

Can I use Laravel Cashier with Paystack?
No. Laravel Cashier is designed for Stripe and Paddle. For Paystack subscriptions, build the integration directly using the HTTP client and Paystack API as shown in this guide.
How do I handle plan upgrades?
Cancel the current subscription and create a new one on the new plan. Handle prorating in your application logic.
What happens when a renewal fails?
Paystack retries the charge. You receive invoice.payment_failed webhooks. Update the status to past_due and notify the customer.
How do I register the middleware?
Add it to your Kernel.php routeMiddleware array with a key like "subscription". Then use it in your route groups with middleware("subscription").

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

Assigning Dedicated Virtual Accounts to Users at Signup

For wallet-based apps and marketplaces, every user needs a dedicated virtual account from day one. This guide covers how to integrate DVA creation into your signup flow, handle failures gracefully, and design the UX so new users see their account number immediately after registration.

Read more

Paystack Split Not Applied to Transaction

You set up a split on Paystack, but the transaction settled entirely to your main account. The split was not applied. Here is why it happens and how to fix it.

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.