El SDK de Go proporciona una interfaz limpia e idiomática de Go para integrar Dodo Payments en tus aplicaciones. Ofrece soporte de contexto, respuestas fuertemente tipadas, capacidades de middleware y es seguro para uso concurrente.
Instalación
Instala el SDK usando módulos de Go:
go get github.com/dodopayments/dodopayments-go
El SDK es compatible con Go 1.18 y versiones posteriores, aprovechando las características modernas de Go para un rendimiento óptimo.
Inicio Rápido
Inicializa el cliente y crea tu primera sesión de pago:
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 )
}
Siempre almacena tus claves API de forma segura utilizando variables de entorno. Nunca las codifiques directamente en tu código fuente.
Características Principales
Soporte de Contexto Soporte completo para context.Context para cancelaciones y tiempos de espera
Tipado Fuerte Solicitudes y respuestas fuertemente tipadas para seguridad en tiempo de compilación
Middleware Soporte de middleware extensible para registro, métricas y lógica personalizada
Seguro para Goroutines Cliente seguro para hilos diseñado para operaciones concurrentes
Configuración
Contexto y Tiempos de Espera
Aprovecha el contexto de Go para tiempos de espera y cancelaciones:
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 )
}
}
Configuración de Reintentos
Configura el comportamiento de reintento automático:
// 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 ),
)
Operaciones Comunes
Crear una Sesión de Pago
Genera una sesión de pago:
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 )
Gestionar Clientes
Crea y recupera información de clientes:
// Create a customer
customer , err := client . Customers . New ( ctx , dodopayments . CustomerNewParams {
Email : dodopayments . F ( "[email protected] " ),
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 )
Manejar Suscripciones
Crea y gestiona suscripciones recurrentes:
// 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 )
}
Facturación Basada en Uso
Ingestar Eventos de Uso
Rastrea eventos personalizados:
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 )
}
Listar Eventos de Uso
// 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 )
}
Manejo de Errores
Maneja tipos de errores específicos:
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
Agrega middleware personalizado para registro o métricas:
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 ),
)
Concurrencia
El cliente es seguro para uso concurrente:
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 ()
}
Recursos
Soporte
¿Necesitas ayuda con el SDK de Go?
Contribuyendo
¡Damos la bienvenida a las contribuciones! Consulta las directrices de contribución para comenzar.