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

Handle Paystack Webhooks in Go

To handle Paystack webhooks in Go, create an HTTP handler that reads the raw body with io.ReadAll, computes an HMAC SHA-512 hash using crypto/hmac, compares it to the X-Paystack-Signature header with hmac.Equal, and processes the event. Return a 200 status.

In this article

  1. 1. Webhook Handler
  2. 2. Route Registration
  3. 3. Testing
  4. 4. Ship Payments Faster

Webhook Handler

import (
    "crypto/hmac"
    "crypto/sha512"
    "encoding/hex"
    "encoding/json"
    "io"
    "log"
    "net/http"
)

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }

    signature := r.Header.Get("X-Paystack-Signature")
    if signature == "" {
        http.Error(w, "Missing signature", http.StatusBadRequest)
        return
    }

    body, err := io.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Failed to read body", http.StatusBadRequest)
        return
    }

    mac := hmac.New(sha512.New, []byte(paystackSecret))
    mac.Write(body)
    expectedMAC := hex.EncodeToString(mac.Sum(nil))

    if !hmac.Equal([]byte(expectedMAC), []byte(signature)) {
        http.Error(w, "Invalid signature", http.StatusBadRequest)
        return
    }

    var event struct {
        Event string          "json:\"event\""
        Data  json.RawMessage "json:\"data\""
    }
    json.Unmarshal(body, &event)

    // Process async
    go processEvent(event.Event, event.Data)

    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func processEvent(eventType string, data json.RawMessage) {
    switch eventType {
    case "charge.success":
        var txn struct {
            Reference string "json:\"reference\""
        }
        json.Unmarshal(data, &txn)
        if txn.Reference != "" {
            if err := verifyAndFulfill(txn.Reference, db); err != nil {
                log.Printf("Fulfillment error: %v", err)
            }
        }
    case "subscription.create":
        log.Println("New subscription created")
    case "invoice.payment_failed":
        log.Println("Invoice payment failed")
    default:
        log.Printf("Unhandled event: %s", eventType)
    }
}

Route Registration

func main() {
    http.HandleFunc("/api/pay", initializeHandler)
    http.HandleFunc("/payment/callback", callbackHandler)
    http.HandleFunc("/webhooks/paystack", webhookHandler)

    log.Println("Server running on :8080")
    http.ListenAndServe(":8080", nil)
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Testing

func TestWebhookHandler(t *testing.T) {
    payload := []byte("{\"event\":\"charge.success\",\"data\":{\"reference\":\"test\"}}")

    mac := hmac.New(sha512.New, []byte("sk_test_xxx"))
    mac.Write(payload)
    sig := hex.EncodeToString(mac.Sum(nil))

    req := httptest.NewRequest("POST", "/webhooks/paystack", bytes.NewBuffer(payload))
    req.Header.Set("X-Paystack-Signature", sig)
    req.Header.Set("Content-Type", "application/json")

    rr := httptest.NewRecorder()
    webhookHandler(rr, req)

    if rr.Code != http.StatusOK {
        t.Errorf("Expected 200, got %d", rr.Code)
    }
}

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

  • ✓Use io.ReadAll(r.Body) for the raw bytes needed for HMAC verification.
  • ✓Go crypto/hmac and crypto/sha512 handle signature computation.
  • ✓Use hmac.Equal for constant-time comparison to prevent timing attacks.
  • ✓Launch event processing in a goroutine for async handling after returning 200.
  • ✓Make handlers idempotent. Paystack retries failed deliveries.
  • ✓Go is well-suited for high-throughput webhook processing.

Frequently Asked Questions

Is goroutine processing safe for webhooks?
Yes. Goroutines are lightweight and safe to spawn per request. The idempotent database update handles concurrency. Make sure your database operations are goroutine-safe.
Should I use a message queue instead of goroutines?
For simple processing, goroutines work well. For complex workflows or guaranteed delivery, use a message queue like NATS or RabbitMQ.
How do I test webhooks locally?
Use ngrok to expose your local server, or compute the HMAC in your test and use httptest for unit tests.

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 Transaction Export and Reporting via API

The Paystack dashboard lets you download CSV reports manually. But when you need daily automated exports, custom financial reports, or reconciliation pipelines, you need the API. This guide covers listing transactions with filters, exporting data in bulk, and building reporting workflows that run without human intervention.

Read more

Paystack USSD Payment Not Completing

USSD payments on Paystack fail more often than card or bank transfer payments. The timeout is brutal, bank USSD systems go down frequently, and customers get confused by the flow. Here is how to handle each problem.

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.