paystacksdkgo

package module
v2.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 20, 2026 License: MIT Imports: 27 Imported by: 0

README

Paystack SDK for Go

Go Reference Go Report Card GitHub release codecov

A comprehensive and robust Go SDK for the Paystack API. This library provides a clean, idiomatic Go interface for integrating Paystack payments into your applications.

Features

  • Full API Coverage: Comprehensive support for all 24 Paystack services (Transactions, Customers, Transfers, etc.).
  • Smart Retries & Rate Limiting: Built-in exponential backoff that respects Paystack's 429 Retry-After headers and strictly avoids retrying non-retryable 4xx errors.
  • Automatic Idempotency: Automatically generates UUIDv4 Idempotency-Key headers for all POST and PUT requests to prevent duplicate charges on network retries.
  • Generic Pagination Iterators: Best-in-class paystackapi.Iterator[T] for elegantly fetching paginated list endpoints.
  • Strongly Typed & Safe: Uses strictly typed enums (paystackapi.Currency, paystackapi.Channel, etc.) rather than raw strings to prevent runtime errors.
  • 100% Mockable: Every service client is exposed as a Go interface allowing effortless unit testing via gomock.
  • Webhook IP Allowlisting: Defense-in-depth webhook signature verification and official IP address validation.
  • Zero Dependencies: Relies solely on the Go standard library for a lightweight footprint and maximum security.

Installation

go get github.com/samaasi/paystack-sdk-go/v2@v2.0.0

Usage

Initialization

Initialize the client with your secret key.

package main

import (
	"fmt"
	"os"

	paystack "github.com/samaasi/paystack-sdk-go"
)

func main() {
	apiKey := os.Getenv("PAYSTACK_SECRET_KEY")
	client := paystack.NewClient(apiKey)
	
	// You can also pass options
	// client := paystack.NewClient(apiKey, 
	//     paystack.WithBaseURL("https://api.paystack.co"),
	//     paystack.WithMaxRetries(5),
	//     paystack.WithTimeout(10 * time.Second),
	// )
}
Configuration

You can configure the client with the following options:

  • WithBaseURL(url string): Override the default Paystack API base URL.
  • WithMaxRetries(retries int): Set the maximum number of retries for failed requests (default: 3).
  • WithTimeout(timeout time.Duration): Set the timeout for HTTP requests (default: 30s).
  • WithHTTPClient(client *http.Client): Use a custom HTTP client.
Making Requests

Example: Initializing a transaction.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	paystack "github.com/samaasi/paystack-sdk-go/v2"
	"github.com/samaasi/paystack-sdk-go/v2/paystackapi"
	"github.com/samaasi/paystack-sdk-go/service/transactions"
)

func main() {
	client := paystack.NewClient(os.Getenv("PAYSTACK_SECRET_KEY"))

	req := &transactions.InitializeRequest{
		Email:    "customer@email.com",
		Amount:   "500000", // in kobo
		Currency: paystackapi.CurrencyNGN,
		Metadata: paystackapi.Metadata{
			"cart_id": "398",
			"custom_fields": []map[string]interface{}{
				{
					"display_name":  "Invoice ID",
					"variable_name": "invoice_id",
					"value":         "INV-001",
				},
			},
		},
	}

	resp, err := client.Transactions.Initialize(context.Background(), req)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Authorization URL: %s\n", resp.Data.AuthorizationURL)
}
Pagination with Iterators

The SDK provides a generic Iterator pattern to effortlessly fetch records across multiple pages without manually handling Meta cursors or next-page logic.

package main

import (
	"context"
	"fmt"
	"log"

	paystack "github.com/samaasi/paystack-sdk-go/v2"
	"github.com/samaasi/paystack-sdk-go/v2/paystackapi"
	"github.com/samaasi/paystack-sdk-go/service/transactions"
)

func main() {
	client := paystack.NewClient("sk_test_...")
	ctx := context.Background()

	iter := paystackapi.NewIterator(func(ctx context.Context, page, perPage int) (paystackapi.Response[[]transactions.VerifyData], error) {
		resp, err := client.Transactions.List(ctx, &transactions.ListTransactionParams{
			Page:    &page,
			PerPage: &perPage,
		})
		if err != nil {
			return paystackapi.Response[[]transactions.VerifyData]{}, err
		}
		return resp.Response, nil
	})

	for iter.Next(ctx) {
		tx := iter.Value()
		fmt.Printf("Transaction ID: %d, Status: %s\n", tx.ID, tx.Status)
	}

	if err := iter.Err(); err != nil {
		log.Fatal("Error during iteration:", err)
	}
}
Webhook Verification

Easily and securely verify incoming webhooks from Paystack using HMAC validation and IP Allowlisting.

package main

import (
	"log"
	"net/http"

	"github.com/samaasi/paystack-sdk-go/webhook"
)

func webhookHandler(w http.ResponseWriter, r *http.Request) {
	// Defense-in-depth: Verify request originates from Paystack's official IPs
	if !webhook.IsFromPaystackIP(r) {
		http.Error(w, "Unauthorized IP", http.StatusUnauthorized)
		return
	}

	// Parse and verify the payload signature using your secret key
	var event webhook.Event
	if err := webhook.Parse(r, "PAYSTACK_SECRET_KEY", &event); err != nil {
		log.Printf("Webhook validation failed: %v", err)
		http.Error(w, "Invalid signature", http.StatusUnauthorized)
		return
	}

	log.Printf("Received event: %s", event.Event)
	w.WriteHeader(http.StatusOK)
}
Idempotency Keys

To prevent duplicate operations, you can pass an Idempotency Key using the context.

import (
	"context"
	"github.com/samaasi/paystack-sdk-go/paystackapi"
)

func main() {
	// ... init client ...

	ctx := context.Background()
	// Add Idempotency Key to context
	ctx = paystackapi.WithIdempotencyKey(ctx, "unique-transaction-id-123")

	// The key will be sent in the header as 'Idempotency-Key'
	resp, err := client.Transactions.Initialize(ctx, req)
}
Custom Headers

You can also pass arbitrary custom headers via context.

ctx := paystackapi.WithCustomHeader(context.Background(), "X-Custom-Header", "Value")

Supported Services

  • Apple Pay
  • Bulk Charges
  • Charges
  • Customers
  • Disputes
  • Integration
  • Miscellaneous (Banks, Countries, etc.)
  • Payment Pages
  • Payment Requests
  • Plans
  • Products
  • Refunds
  • Settlements
  • Splits
  • Status
  • Subaccounts
  • Subscriptions
  • Terminal
  • Transactions
  • Transfer Control
  • Transfer Recipients
  • Transfers
  • Verification
  • Virtual Accounts

Examples

Runnable examples are available under examples/:

Example Description
initialize_transaction/ Initialize a transaction and redirect to the Paystack checkout URL
verify_webhook/ IP allowlist + HMAC signature verification + event dispatch
pagination/ Paginate a transaction list using the generic iterator
charge_returning_customer/ Charge an existing authorization with typed error handling

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for details.

To get started:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/amazing-feature).
  3. Commit your changes (git commit -m 'Add some amazing feature').
  4. Push to the branch (git push origin feature/amazing-feature).
  5. Open a Pull Request.

Please ensure you run tests before submitting:

go test ./...

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package paystacksdkgo provides a comprehensive and robust Go client for the Paystack API.

This SDK covers all major Paystack services including Transactions, Customers, Plans, Subscriptions, Transfers, and more. It is designed to be idiomatic, context-aware, and easy to use.

Initialization

import (
	"os"
	paystack "github.com/samaasi/paystack-sdk-go/v2"
)

func main() {
	apiKey := os.Getenv("PAYSTACK_SECRET_KEY")
	client := paystack.NewClient(apiKey)
	// Use client to interact with Paystack API...
}

Services

The client provides access to various services via fields:

client.Transactions.Initialize(...)
client.Customers.Create(...)

See individual service documentation for details.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// Transaction service for handling transaction-related operations
	Transactions transactions.Service

	// Transfer service for handling transfer-related operations
	Transfers transfers.Service

	// ApplePay service for handling Apple Pay-related operations
	ApplePay applepay.Service

	// BulkCharges service for handling bulk charge operations
	BulkCharges bulkcharges.Service

	// Charges service for handling charge operations
	Charges charges.Service

	// PaymentPages service for handling payment page operations
	PaymentPages paymentPages.Service

	// PaymentRequests service for handling payment request operations
	PaymentRequests paymentRequests.Service

	// Customers service for handling customer operations
	Customers customers.Service

	// Disputes service for handling dispute operations
	Disputes disputes.Service

	// Integration service for handling integration operations
	Integration integration.Service

	// Plans service for handling plans
	Plans plans.Service

	// Products service for handling products
	Products products.Service

	// Refunds service for handling refunds
	Refunds refunds.Service

	// Settlements service for handling settlements
	Settlements settlements.Service

	// Splits service for handling splits
	Splits splits.Service

	// Status service for handling status
	Status status.Service

	// Subaccounts service for handling subaccounts
	Subaccounts subaccounts.Service

	// Subscriptions service for handling subscriptions
	Subscriptions subscriptions.Service

	// Terminal service for handling terminal
	Terminal terminal.Service

	// Verification service for handling verification
	Verification verification.Service

	// VirtualAccounts service for handling virtual accounts
	VirtualAccounts virtualAccounts.Service

	// TransferControl service for handling transfer control
	TransferControl transferControl.Service

	// TransferRecipients service for handling transfer recipients
	TransferRecipients transferRecipients.Service

	// Misc service for handling miscellaneous operations
	Misc misc.Service
	// contains filtered or unexported fields
}

Client is the main entry point for the Paystack SDK.

func NewClient

func NewClient(secretKey string, opts ...ClientOption) *Client

NewClient creates a new Paystack client with the given secret key. You can pass the secret key from your environment variables or any other source.

Example:

client := paystack.NewClient(os.Getenv("PAYSTACK_SECRET_KEY"))

type ClientOption

type ClientOption = backend.ClientOption

ClientOption is a function that configures the Client.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL allows you to override the default Paystack API base URL.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient allows you to provide a custom HTTP client. This is useful for testing or if you need to configure proxies, timeouts, etc.

func WithMaxRetries

func WithMaxRetries(retries int) ClientOption

WithMaxRetries sets the maximum number of retries for failed requests. Default is 3. Set to 0 to disable retries.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the timeout for HTTP requests. Default is 30 seconds.

Directories

Path Synopsis
examples
charge_returning_customer command
Example: charge a returning customer using a saved authorization code.
Example: charge a returning customer using a saved authorization code.
initialize_transaction command
Example: initialize a transaction and redirect the user to the checkout URL.
Example: initialize a transaction and redirect the user to the checkout URL.
pagination command
Example: iterate over all transactions using the built-in Iterator.
Example: iterate over all transactions using the built-in Iterator.
verify_webhook command
Example: verify an incoming Paystack webhook and dispatch on event type.
Example: verify an incoming Paystack webhook and dispatch on event type.
internal
service
apple-pay
Package applepay provides methods for interacting with the Paystack API for apple-pay.
Package applepay provides methods for interacting with the Paystack API for apple-pay.
bulk-charges
Package bulkcharges provides methods for interacting with the Paystack API for bulk-charges.
Package bulkcharges provides methods for interacting with the Paystack API for bulk-charges.
charges
Package charges provides methods for interacting with the Paystack API for charges.
Package charges provides methods for interacting with the Paystack API for charges.
customers
Package customers provides methods for interacting with the Paystack API for customers.
Package customers provides methods for interacting with the Paystack API for customers.
disputes
Package disputes provides methods for interacting with the Paystack API for disputes.
Package disputes provides methods for interacting with the Paystack API for disputes.
integration
Package integration provides methods for interacting with the Paystack API for integration.
Package integration provides methods for interacting with the Paystack API for integration.
misc
Package misc provides methods for interacting with the Paystack API for misc.
Package misc provides methods for interacting with the Paystack API for misc.
payment-pages
Package paymentpages provides methods for interacting with the Paystack API for payment-pages.
Package paymentpages provides methods for interacting with the Paystack API for payment-pages.
payment-requests
Package paymentrequests provides methods for interacting with the Paystack API for payment-requests.
Package paymentrequests provides methods for interacting with the Paystack API for payment-requests.
plans
Package plans provides methods for interacting with the Paystack API for plans.
Package plans provides methods for interacting with the Paystack API for plans.
products
Package products provides methods for interacting with the Paystack API for products.
Package products provides methods for interacting with the Paystack API for products.
refunds
Package refunds provides methods for interacting with the Paystack API for refunds.
Package refunds provides methods for interacting with the Paystack API for refunds.
settlements
Package settlements provides methods for interacting with the Paystack API for settlements.
Package settlements provides methods for interacting with the Paystack API for settlements.
splits
Package splits provides methods for interacting with the Paystack API for splits.
Package splits provides methods for interacting with the Paystack API for splits.
status
Package status provides methods for interacting with the Paystack API for status.
Package status provides methods for interacting with the Paystack API for status.
subaccounts
Package subaccounts provides methods for interacting with the Paystack API for subaccounts.
Package subaccounts provides methods for interacting with the Paystack API for subaccounts.
subscriptions
Package subscriptions provides methods for interacting with the Paystack API for subscriptions.
Package subscriptions provides methods for interacting with the Paystack API for subscriptions.
terminal
Package terminal provides methods for interacting with the Paystack API for terminal.
Package terminal provides methods for interacting with the Paystack API for terminal.
transactions
Package transactions provides methods for interacting with the Paystack API for transactions.
Package transactions provides methods for interacting with the Paystack API for transactions.
transfer-control
Package transferControl provides methods for interacting with the Paystack API for transfer-control.
Package transferControl provides methods for interacting with the Paystack API for transfer-control.
transfer-recipients
Package transferRecipients provides methods for interacting with the Paystack API for transfer-recipients.
Package transferRecipients provides methods for interacting with the Paystack API for transfer-recipients.
transfers
Package transfers provides methods for interacting with the Paystack API for transfers.
Package transfers provides methods for interacting with the Paystack API for transfers.
verification
Package verification provides methods for interacting with the Paystack API for verification.
Package verification provides methods for interacting with the Paystack API for verification.
virtual-accounts
Package virtualAccounts provides methods for interacting with the Paystack API for virtual-accounts.
Package virtualAccounts provides methods for interacting with the Paystack API for virtual-accounts.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL