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

Accept Payments with Paystack in Go

To accept Paystack payments in Go, create HTTP handlers that call the Paystack REST API using net/http. Initialize a transaction, redirect the user to Paystack checkout, and verify the payment in a callback handler before granting value.

In this article

  1. 1. Setup
  2. 2. Request and Response Structs
  3. 3. Initialize a Transaction
  4. 4. Handle the Callback
  5. 5. Main Function
  6. 6. Production Checklist
  7. 7. Ship Payments Faster

Setup

mkdir paystack-go && cd paystack-go
go mod init paystack-go

Set your environment variable:

export PAYSTACK_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxxxxxxx

Request and Response Structs

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

type InitRequest struct {
    Email       string "json:\"email\""
    Amount      int    "json:\"amount\""
    Reference   string "json:\"reference\""
    CallbackURL string "json:\"callback_url\""
}

type PaystackResponse struct {
    Status  bool   "json:\"status\""
    Message string "json:\"message\""
    Data    struct {
        AuthorizationURL string "json:\"authorization_url\""
        AccessCode       string "json:\"access_code\""
        Reference        string "json:\"reference\""
    } "json:\"data\""
}

type VerifyResponse struct {
    Status bool "json:\"status\""
    Data   struct {
        Status   string "json:\"status\""
        Amount   int    "json:\"amount\""
        Currency string "json:\"currency\""
        Customer struct {
            Email string "json:\"email\""
        } "json:\"customer\""
        Reference string "json:\"reference\""
    } "json:\"data\""
}

var paystackSecret = os.Getenv("PAYSTACK_SECRET_KEY")

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Initialize a Transaction

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

    var input struct {
        Email  string  "json:\"email\""
        Amount float64 "json:\"amount\""
    }
    json.NewDecoder(r.Body).Decode(&input)

    ref := fmt.Sprintf("order_%d", time.Now().UnixNano())

    reqBody := InitRequest{
        Email:       input.Email,
        Amount:      int(input.Amount * 100),
        Reference:   ref,
        CallbackURL: "http://localhost:8080/payment/callback",
    }

    body, _ := json.Marshal(reqBody)

    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")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        http.Error(w, "Failed to call Paystack", http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()

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

    if !result.Status {
        http.Error(w, result.Message, http.StatusBadRequest)
        return
    }

    // TODO: Save order to database

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{
        "authorization_url": result.Data.AuthorizationURL,
        "reference":         result.Data.Reference,
    })
}

Handle the Callback

func callbackHandler(w http.ResponseWriter, r *http.Request) {
    reference := r.URL.Query().Get("reference")
    if reference == "" {
        reference = r.URL.Query().Get("trxref")
    }
    if reference == "" {
        http.Error(w, "Missing reference", http.StatusBadRequest)
        return
    }

    req, _ := http.NewRequest("GET", "https://api.paystack.co/transaction/verify/"+reference, nil)
    req.Header.Set("Authorization", "Bearer "+paystackSecret)

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        http.Error(w, "Verification failed", http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()

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

    if result.Status && result.Data.Status == "success" {
        // TODO: Verify amount, mark order as paid
        fmt.Fprintf(w, "Payment successful! %s %d", result.Data.Currency, result.Data.Amount/100)
        return
    }

    http.Error(w, "Payment not successful", http.StatusBadRequest)
}

Main Function

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

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

Production Checklist

  1. Use a router. Consider gorilla/mux or chi for production routing.
  2. Set up webhooks. See Handle Paystack Webhooks in Go.
  3. HTTPS. Use TLS in production. Paystack requires HTTPS for callbacks.
  4. Validate amounts. Check against your database, not client input.
  5. Error handling. Handle all errors from HTTP calls and JSON parsing.

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

  • ✓Go standard library net/http handles all Paystack API calls. No external packages required.
  • ✓Store your Paystack secret key in environment variables. Access with os.Getenv.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Multiply by 100 before sending.
  • ✓Go structs with json tags map cleanly to Paystack API request and response shapes.
  • ✓Always verify the transaction server-side after the redirect callback.
  • ✓Go error handling makes it explicit when API calls fail.

Frequently Asked Questions

Do I need a Paystack Go package?
No. The standard library net/http handles all API calls. The Paystack API is a simple REST API that works well with Go structs and json encoding.
Should I use Gin or Echo for Paystack integration?
Any Go router works. The Paystack API calls are the same regardless of your router choice. Gin and Echo add convenience for middleware and routing but are not required.
How do I handle concurrent requests in Go?
Go handles concurrency automatically with goroutines. Each HTTP request runs in its own goroutine. Use database transactions or atomic operations to prevent race conditions in payment fulfillment.

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

Building a Fully Custom Checkout on the Paystack Charge API

When the hosted checkout does not fit your product, you can build every piece of the payment experience yourself. This guide walks through designing the form, posting card or bank data to your server, running the Charge API flow, and shipping a production-ready checkout.

Read more

Paystack Apple Pay Domain Verification Failing

Apple Pay on Paystack requires domain verification. Apple sends a request to a specific file path on your domain, and if it cannot find the file or the response is wrong, verification fails silently. The fix depends on your hosting platform, and each one has its own gotcha.

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.