The Go SDK provides a clean and idiomatic Go interface for integrating Dodo Payments into your applications. It offers context support, strongly typed responses, middleware capabilities, and is safe for concurrent use.
Installation
Install the SDK using Go modules:
go get github.com/dodopayments/dodopayments-go
The SDK supports Go 1.18 and later versions, leveraging modern Go features for optimal performance.
Quick Start
Initialize the client and create your first checkout session:
package main
import (
" context "
" fmt "
" log "
" github.com/dodopayments/dodopayments-go "
" github.com/dodopayments/dodopayments-go/option "
)
func main () {
client := dodopayments . NewClient (
option . WithBearerToken ( "My Bearer Token" ), // defaults to os.LookupEnv("DODO_PAYMENTS_API_KEY")
option . WithEnvironmentTestMode (), // defaults to option.WithEnvironmentLiveMode()
)
checkoutSessionResponse , err := client . CheckoutSessions . New ( context . TODO (), dodopayments . CheckoutSessionNewParams {
CheckoutSessionRequest : dodopayments . CheckoutSessionRequestParam {
ProductCart : dodopayments . F ([] dodopayments . CheckoutSessionRequestProductCartParam {{
ProductID : dodopayments . F ( "product_id" ),
Quantity : dodopayments . F ( int64 ( 1 )),
}}),
},
})
if err != nil {
log . Fatal ( err )
}
fmt . Printf ( "Session ID: %s \n " , checkoutSessionResponse . SessionID )
}
Always store your API keys securely using environment variables. Never hardcode them in your source code.
Core Features
Context Support Full support for context.Context for cancellation and timeouts
Strong Typing Strongly typed requests and responses for compile-time safety
Middleware Extensible middleware support for logging, metrics, and custom logic
Goroutine Safe Thread-safe client designed for concurrent operations
Configuration
Context and Timeouts
Leverage Go’s context for timeouts and cancellation:
import (
" context "
" time "
" github.com/dodopayments/dodopayments-go "
" github.com/dodopayments/dodopayments-go/option "
)
// Create a context with timeout
ctx , cancel := context . WithTimeout ( context . Background (), 10 * time . Second )
defer cancel ()
payment , err := client . Payments . Create ( ctx , dodopayments . PaymentCreateParams {
Amount : 5000 ,
Currency : "USD" ,
CustomerID : "cus_123" ,
})
if err != nil {
if ctx . Err () == context . DeadlineExceeded {
log . Println ( "Request timed out" )
} else {
log . Fatal ( err )
}
}
Retry Configuration
Configure automatic retry behavior:
// Configure default for all requests (default is 2)
client := dodopayments . NewClient (
option . WithMaxRetries ( 0 ), // disable retries
)
// Override per-request
client . CheckoutSessions . New (
context . TODO (),
dodopayments . CheckoutSessionNewParams {
CheckoutSessionRequest : dodopayments . CheckoutSessionRequestParam {
ProductCart : dodopayments . F ([] dodopayments . CheckoutSessionRequestProductCartParam {{
ProductID : dodopayments . F ( "product_id" ),
Quantity : dodopayments . F ( int64 ( 0 )),
}}),
},
},
option . WithMaxRetries ( 5 ),
)
Common Operations
Create a Checkout Session
Generate a checkout session:
session , err := client . CheckoutSessions . New ( ctx , dodopayments . CheckoutSessionNewParams {
CheckoutSessionRequest : dodopayments . CheckoutSessionRequestParam {
ProductCart : dodopayments . F ([] dodopayments . CheckoutSessionRequestProductCartParam {{
ProductID : dodopayments . F ( "prod_123" ),
Quantity : dodopayments . F ( int64 ( 1 )),
}}),
ReturnURL : dodopayments . F ( "https://yourdomain.com/return" ),
},
})
if err != nil {
log . Fatal ( err )
}
fmt . Printf ( "Checkout URL: %s \n " , session . URL )
Manage Customers
Create and retrieve customer information:
// Create a customer
customer , err := client . Customers . New ( ctx , dodopayments . CustomerNewParams {
Email : dodopayments . F ( "customer@example.com" ),
Name : dodopayments . F ( "John Doe" ),
Metadata : dodopayments . F ( map [ string ] string {
"user_id" : "12345" ,
}),
})
if err != nil {
log . Fatal ( err )
}
// Retrieve customer
customer , err = client . Customers . Get ( ctx , "cus_123" )
if err != nil {
log . Fatal ( err )
}
fmt . Printf ( "Customer: %s ( %s ) \n " , customer . Name , customer . Email )
Handle Subscriptions
Create and manage recurring subscriptions:
// Create a subscription
subscription , err := client . Subscriptions . New ( ctx , dodopayments . SubscriptionNewParams {
CustomerID : dodopayments . F ( "cus_123" ),
ProductID : dodopayments . F ( "prod_456" ),
PriceID : dodopayments . F ( "price_789" ),
})
if err != nil {
log . Fatal ( err )
}
// Get usage history
usageHistory , err := client . Subscriptions . GetUsageHistory (
ctx ,
subscription . ID ,
dodopayments . SubscriptionGetUsageHistoryParams {
StartDate : dodopayments . F ( "2024-01-01T00:00:00Z" ),
EndDate : dodopayments . F ( "2024-03-31T23:59:59Z" ),
},
)
if err != nil {
log . Fatal ( err )
}
Usage-Based Billing
Ingest Usage Events
Track custom events:
import " github.com/dodopayments/dodopayments-go "
response , err := client . UsageEvents . Ingest ( ctx , dodopayments . UsageEventIngestParams {
Events : dodopayments . F ([] dodopayments . UsageEventIngestParamsEvent {{
EventID : dodopayments . F ( "api_call_12345" ),
CustomerID : dodopayments . F ( "cus_abc123" ),
EventName : dodopayments . F ( "api_request" ),
Timestamp : dodopayments . F ( "2024-01-15T10:30:00Z" ),
Metadata : dodopayments . F ( map [ string ] string {
"endpoint" : "/api/v1/users" ,
"method" : "GET" ,
"tokens_used" : "150" ,
}),
}}),
})
if err != nil {
log . Fatal ( err )
}
List Usage Events
// List events with filters
params := dodopayments . UsageEventListParams {
CustomerID : dodopayments . F ( "cus_abc123" ),
EventName : dodopayments . F ( "api_request" ),
}
events , err := client . UsageEvents . List ( ctx , params )
if err != nil {
log . Fatal ( err )
}
for _ , event := range events . Data {
fmt . Printf ( "Event %s : %s at %s \n " , event . EventID , event . EventName , event . Timestamp )
}
Error Handling
Handle specific error types:
payment , err := client . Payments . Create ( ctx , dodopayments . PaymentCreateParams {
Amount : 5000 ,
Currency : "USD" ,
})
if err != nil {
if apiErr , ok := err .( * dodopayments . APIError ); ok {
fmt . Printf ( "API Error: %s \n " , apiErr . Message )
fmt . Printf ( "Status Code: %d \n " , apiErr . StatusCode )
fmt . Printf ( "Request ID: %s \n " , apiErr . RequestID )
// Handle specific error types
switch apiErr . Type {
case dodopayments . ErrorTypeAuthentication :
log . Println ( "Authentication failed" )
case dodopayments . ErrorTypeInvalidRequest :
log . Println ( "Invalid request parameters" )
case dodopayments . ErrorTypeRateLimit :
log . Println ( "Rate limit exceeded" )
default :
log . Printf ( "API error: %s \n " , apiErr . Message )
}
} else {
log . Fatal ( err )
}
}
Middleware
Add custom middleware for logging or metrics:
func Logger ( req * http . Request , next option . MiddlewareNext ) ( res * http . Response , err error ) {
// Before the request
start := time . Now ()
log . Printf ( "Request: %s %s \n " , req . Method , req . URL )
// Forward the request to the next handler
res , err = next ( req )
// After the request
end := time . Now ()
log . Printf ( "Response: %d in %v \n " , res . StatusCode , end . Sub ( start ))
return res , err
}
client := dodopayments . NewClient (
option . WithMiddleware ( Logger ),
)
Concurrency
The client is safe for concurrent use:
package main
import (
" context "
" sync "
" log "
" github.com/dodopayments/dodopayments-go "
)
func main () {
client := dodopayments . NewClient ()
var wg sync . WaitGroup
for i := 0 ; i < 10 ; i ++ {
wg . Add ( 1 )
go func ( idx int ) {
defer wg . Done ()
payment , err := client . Payments . Create ( context . Background (), dodopayments . PaymentCreateParams {
Amount : 1000 ,
Currency : "USD" ,
CustomerID : "cus_123" ,
})
if err != nil {
log . Printf ( "Failed to create payment %d : %v " , idx , err )
return
}
log . Printf ( "Created payment %d : %s " , idx , payment . ID )
}( i )
}
wg . Wait ()
}
Resources
Support
Need help with the Go SDK?
Contributing
We welcome contributions! Check the contributing guidelines to get started.