O SDK Go fornece uma interface limpa e idiomática em Go para integrar os pagamentos Dodo em suas aplicações. Ele oferece suporte a contexto, respostas fortemente tipadas, capacidades de middleware e é seguro para uso concorrente.
Instalação
Instale o SDK usando módulos Go:
go get github.com/dodopayments/dodopayments-go
O SDK suporta Go 1.18 e versões posteriores, aproveitando os recursos modernos do Go para desempenho ideal.
Início Rápido
Inicialize o cliente e crie sua primeira sessão de checkout:
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 )
}
Sempre armazene suas chaves de API de forma segura usando variáveis de ambiente. Nunca as codifique diretamente em seu código-fonte.
Recursos Principais
Suporte a Contexto Suporte total para context.Context para cancelamento e timeouts
Tipagem Forte Requisições e respostas fortemente tipadas para segurança em tempo de compilação
Middleware Suporte a middleware extensível para logging, métricas e lógica personalizada
Seguro para Goroutines Cliente seguro para threads projetado para operações concorrentes
Configuração
Contexto e Timeouts
Aproveite o contexto do Go para timeouts e cancelamento:
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 )
}
}
Configuração de Retentativas
Configure o comportamento de retentativa automática:
// 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 ),
)
Operações Comuns
Criar uma Sessão de Checkout
Gere uma sessão de checkout:
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 )
Gerenciar Clientes
Crie e recupere informações 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 )
Gerenciar Assinaturas
Crie e gerencie assinaturas recorrentes:
// 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 )
}
Cobrança Baseada em Uso
Registrar Eventos de Uso
Rastreie 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 )
}
Tratamento de Erros
Trate tipos de erro 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
Adicione middleware personalizado para logging ou 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 ),
)
Concorrência
O cliente é seguro para uso concorrente:
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
Suporte
Precisa de ajuda com o SDK Go?
Contribuindo
Agradecemos contribuições! Confira as diretrizes de contribuição para começar.