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 Go
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Build Paystack Subscriptions in Go

To build Paystack subscriptions in Go, create a plan via the API, initialize a transaction with the plan code, handle subscription webhooks in your webhook handler, track status in your database, and provide an endpoint for cancellation.

In this article

  1. 1. Subscribe Handler
  2. 2. Subscription Webhook Events
  3. 3. Cancel Subscription
  4. 4. Subscription Middleware
  5. 5. Ship Payments Faster

Subscribe Handler

func subscribeHandler(w http.ResponseWriter, r *http.Request) {
    var input struct {
        Email    string "json:\"email\""
        PlanCode string "json:\"plan_code\""
    }
    json.NewDecoder(r.Body).Decode(&input)

    body, _ := json.Marshal(map[string]string{
        "email":        input.Email,
        "plan":         input.PlanCode,
        "callback_url": "http://localhost:8080/subscription/callback",
    })

    req, _ := http.NewRequest("POST", "https://api.paystack.co/transaction/initialize",
        bytes.NewBuffer(body))
    req.Header.Set("Authorization", "Bearer "+paystackSecret)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        http.Error(w, "Failed", http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()

    var result PaystackResponse
    json.NewDecoder(resp.Body).Decode(&result)

    if result.Status {
        json.NewEncoder(w).Encode(map[string]string{
            "authorization_url": result.Data.AuthorizationURL,
        })
        return
    }

    http.Error(w, result.Message, http.StatusBadRequest)
}

Subscription Webhook Events

// In processEvent:
case "subscription.create":
    var sub struct {
        SubscriptionCode string "json:\"subscription_code\""
        EmailToken       string "json:\"email_token\""
        Customer         struct {
            Email string "json:\"email\""
        } "json:\"customer\""
        Plan struct {
            PlanCode string "json:\"plan_code\""
        } "json:\"plan\""
    }
    json.Unmarshal(data, &sub)
    // Save to database

case "invoice.payment_failed":
    var inv struct {
        Subscription struct {
            SubscriptionCode string "json:\"subscription_code\""
        } "json:\"subscription\""
    }
    json.Unmarshal(data, &inv)
    // Update status to past_due

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Cancel Subscription

func cancelHandler(w http.ResponseWriter, r *http.Request) {
    // Get subscription from database for current user
    subCode := "SUB_xxx" // from database
    emailToken := "token_xxx" // from database

    body, _ := json.Marshal(map[string]string{
        "code":  subCode,
        "token": emailToken,
    })

    req, _ := http.NewRequest("POST", "https://api.paystack.co/subscription/disable",
        bytes.NewBuffer(body))
    req.Header.Set("Authorization", "Bearer "+paystackSecret)
    req.Header.Set("Content-Type", "application/json")

    resp, _ := http.DefaultClient.Do(req)
    defer resp.Body.Close()

    // Update database status to cancelled
    w.Write([]byte("Subscription cancelled"))
}

Subscription Middleware

func requireSubscription(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Check user subscription status from database
        // If not active, return 403
        // Otherwise, call next(w, r)
        next(w, r)
    }
}

// Usage:
http.HandleFunc("/premium", requireSubscription(premiumHandler))

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 handles recurring billing. Create plans once and subscribe customers.
  • ✓Initialize with a plan parameter instead of amount. Paystack uses the plan price.
  • ✓Webhook events drive subscription state. Handle subscription.create and invoice.payment_failed.
  • ✓Store subscription_code and email_token for managing subscriptions.
  • ✓Go middleware can gate handlers behind subscription checks.
  • ✓Use database transactions for safe subscription status updates.

Frequently Asked Questions

Can I change subscription plans?
Paystack does not support direct plan changes. Cancel the current subscription and create a new one on the desired plan.
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 store the email_token?
The email_token comes in the subscription.create webhook. Store it in your database alongside the subscription_code. You need both for cancellation.

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 Balance and Settlement APIs Explained

Your Paystack dashboard shows you a balance number and a list of settlements. But when you need to reconcile programmatically, track pending payouts, or build financial reports, you need the API. This guide covers every endpoint, what each field means, and how to build reconciliation logic on top of them.

Read more

When Paystack Is Down: Building Graceful Degradation

Paystack will go down. Every payment provider does. The question is not whether it will happen but whether your app handles it gracefully or shows your customers a broken checkout page.

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.