Das Go SDK bietet eine saubere und idiomatische Go-Schnittstelle zur Integration von Dodo Payments in Ihre Anwendungen. Es bietet Unterstützung für Kontexte, stark typisierte Antworten, Middleware-Funktionen und ist sicher für die gleichzeitige Nutzung.
Installation
Installieren Sie das SDK mit Go-Modulen:
go get github.com/dodopayments/dodopayments-go
Oder um auf eine bestimmte Version zu verweisen:
go get -u 'github.com/dodopayments/dodopayments-go@v1.86.1'
Das SDK erfordert Go 1.22 oder neuere Versionen und nutzt moderne Go-Funktionen für optimale Leistung.
Schnellstart
Initialisieren Sie den Client und erstellen Sie Ihre erste Checkout-Sitzung:
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 . ProductItemReqParam {{
ProductID : dodopayments . F ( "product_id" ),
Quantity : dodopayments . F ( int64 ( 1 )),
}}),
},
})
if err != nil {
panic ( err . Error ())
}
fmt . Printf ( "Session ID: %s \n " , checkoutSessionResponse . SessionID )
}
Speichern Sie Ihre API-Schlüssel immer sicher über Umgebungsvariablen. Hardcodieren Sie sie niemals im Quellcode.
Kernfunktionen
Context Support Vollständige Unterstützung für context.Context zur Abbruchsteuerung und Timeout-Verwaltung
Strong Typing Stark typisierte Anfragen und Antworten für Kompilierzeitsicherheit
Middleware Erweiterbare Middleware-Unterstützung für Logging, Metriken und benutzerdefinierte Logik
Goroutine Safe Thread-sicherer Client für gleichzeitige Operationen entwickelt
Konfiguration
Kontext und Zeitüberschreitungen
Nutzen Sie den Kontext von Go für Zeitüberschreitungen und Abbrüche:
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 )
}
}
Wiederholungs-Konfiguration
Konfigurieren Sie das automatische Wiederholungsverhalten:
// 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 . ProductItemReqParam {{
ProductID : dodopayments . F ( "product_id" ),
Quantity : dodopayments . F ( int64 ( 0 )),
}}),
},
},
option . WithMaxRetries ( 5 ),
)
Häufige Operationen
Erstellen einer Checkout-Sitzung
Generieren Sie eine Checkout-Sitzung:
session , err := client . CheckoutSessions . New ( ctx , dodopayments . CheckoutSessionNewParams {
CheckoutSessionRequest : dodopayments . CheckoutSessionRequestParam {
ProductCart : dodopayments . F ([] dodopayments . ProductItemReqParam {{
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 . CheckoutURL )
Kunden verwalten
Erstellen und Abrufen von Kundeninformationen:
// 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 )
Abonnements verwalten
Erstellen und verwalten Sie wiederkehrende Abonnements:
// 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 )
}
Nutzungsbasierte Abrechnung
Nutzungsereignisse erfassen
Verfolgen Sie benutzerdefinierte Ereignisse:
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 )
}
Nutzungsereignisse auflisten
// 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 )
}
Fehlerbehandlung
Behandeln Sie spezifische Fehlertypen:
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
Fügen Sie benutzerdefinierte Middleware für Protokollierung oder Metriken hinzu:
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 ),
)
Nebenläufigkeit
Der Client ist für die gleichzeitige Verwendung sicher:
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 ()
}
Ressourcen
Unterstützung
Brauchen Sie Hilfe mit dem Go SDK?
Mitwirken
Wir freuen uns über Beiträge! Überprüfen Sie die Mitwirkungsrichtlinien , um loszulegen.