> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Go

> Integrieren Sie Dodo Payments in Ihre Go-Anwendungen mit einem idiomatischen, leistungsstarken SDK

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:

```bash theme={null}
go get github.com/dodopayments/dodopayments-go
```

Oder um auf eine bestimmte Version zu verweisen:

```bash theme={null}
go get -u 'github.com/dodopayments/dodopayments-go@v1.97.3'
```

<Info>
  Das SDK erfordert Go 1.22 oder neuere Versionen und nutzt moderne Go-Funktionen für optimale Leistung.
</Info>

## Schnellstart

Initialisieren Sie den Client und erstellen Sie Ihre erste Checkout-Sitzung:

```go theme={null}
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)
}
```

<Warning>
  Speichern Sie Ihre API-Schlüssel immer sicher über Umgebungsvariablen. Hardcodieren Sie sie niemals im Quellcode.
</Warning>

## Kernfunktionen

<CardGroup cols={2}>
  <Card title="Context Support" icon="clock">
    Vollständige Unterstützung für context.Context zur Abbruchsteuerung und Timeout-Verwaltung
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Stark typisierte Anfragen und Antworten für Kompilierzeitsicherheit
  </Card>

  <Card title="Middleware" icon="layer-group">
    Erweiterbare Middleware-Unterstützung für Logging, Metriken und benutzerdefinierte Logik
  </Card>

  <Card title="Goroutine Safe" icon="bolt">
    Thread-sicherer Client für gleichzeitige Operationen entwickelt
  </Card>
</CardGroup>

## Konfiguration

### Kontext und Zeitüberschreitungen

Nutzen Sie den Kontext von Go für Zeitüberschreitungen und Abbrüche:

```go theme={null}
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.New(ctx, dodopayments.PaymentNewParams{
	Billing: dodopayments.F(dodopayments.BillingAddressParam{
		Country: dodopayments.F(dodopayments.CountryCodeUs),
		City:    dodopayments.F("San Francisco"),
		State:   dodopayments.F("CA"),
		Street:  dodopayments.F("1 Market St"),
		Zipcode: dodopayments.F("94105"),
	}),
	Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
		dodopayments.AttachExistingCustomerParam{
			CustomerID: dodopayments.F("cus_123"),
		},
	),
	ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
		ProductID: dodopayments.F("pdt_456"),
		Quantity:  dodopayments.F(int64(1)),
	}}),
})
if err != nil {
	if ctx.Err() == context.DeadlineExceeded {
		log.Println("Request timed out")
	} else {
		log.Fatal(err)
	}
}
```

### Wiederholungs-Konfiguration

Konfigurieren Sie das automatische Wiederholungsverhalten:

```go theme={null}
// 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:

```go theme={null}
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:

```go theme={null}
// 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:

```go theme={null}
import "time"

// Create a subscription
subscription, err := client.Subscriptions.New(ctx, dodopayments.SubscriptionNewParams{
	Billing: dodopayments.F(dodopayments.BillingAddressParam{
		Country: dodopayments.F(dodopayments.CountryCodeUs),
		City:    dodopayments.F("San Francisco"),
		State:   dodopayments.F("CA"),
		Street:  dodopayments.F("1 Market St"),
		Zipcode: dodopayments.F("94105"),
	}),
	Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
		dodopayments.AttachExistingCustomerParam{
			CustomerID: dodopayments.F("cus_123"),
		},
	),
	ProductID: dodopayments.F("pdt_456"),
	Quantity:  dodopayments.F(int64(1)),
})
if err != nil {
	log.Fatal(err)
}

// Charge an on-demand subscription
// ProductPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
chargeResponse, err := client.Subscriptions.Charge(ctx, subscription.SubscriptionID,
	dodopayments.SubscriptionChargeParams{
		ProductPrice: dodopayments.F(int64(2500)),
	},
)
if err != nil {
	log.Fatal(err)
}

// Get usage history (for metered subscriptions)
usageHistory, err := client.Subscriptions.GetUsageHistory(
	ctx,
	subscription.SubscriptionID,
	dodopayments.SubscriptionGetUsageHistoryParams{
		StartDate: dodopayments.F(time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)),
		EndDate:   dodopayments.F(time.Date(2024, 3, 31, 23, 59, 59, 0, time.UTC)),
	},
)
if err != nil {
	log.Fatal(err)
}
```

<Info>
  `Billing` erfordert mindestens den ISO-`Country`-Ländercode. `Customer` ist ein `CustomerRequestUnionParam` — übergeben Sie `AttachExistingCustomerParam{CustomerID: ...}` für einen bestehenden Kunden oder `NewCustomerParam{Email: ..., Name: ...}` für einen neuen. `ProductPrice` ist in der niedrigsten Währungseinheit.
</Info>

## Nutzungsbasierte Abrechnung

### Nutzungsereignisse erfassen

Benutzerdefinierte Ereignisse verfolgen:

```go theme={null}
import "github.com/dodopayments/dodopayments-go"

response, err := client.UsageEvents.Ingest(ctx, dodopayments.UsageEventIngestParams{
	Events: dodopayments.F([]dodopayments.EventInputParam{{
		EventID:    dodopayments.F("api_call_12345"),
		CustomerID: dodopayments.F("cus_abc123"),
		EventName:  dodopayments.F("api_request"),
		Timestamp:  dodopayments.F(time.Date(2024, 1, 15, 10, 30, 0, 0, time.UTC)),
	}}),
})
if err != nil {
	log.Fatal(err)
}
```

### Nutzungsereignisse auflisten

```go theme={null}
// 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.Items {
	fmt.Printf("Event %s: %s at %s\n", event.EventID, event.EventName, event.Timestamp)
}
```

## Fehlerbehandlung

Wenn die API einen Statuscode außerhalb des Erfolgsbereichs zurückgibt, liefert das SDK einen Fehler vom Typ
`*dodopayments.Error`. Es stellt den `StatusCode`, den zugrunde liegenden `*http.Request` und
`*http.Response` sowie das JSON des Fehlerkörpers bereit. Verwenden Sie das Muster `errors.As`, um es zu
untersuchen, und verzweigen Sie sich auf `StatusCode`, um spezifische Fälle zu behandeln:

```go theme={null}
payment, err := client.Payments.New(ctx, dodopayments.PaymentNewParams{
	Billing: dodopayments.F(dodopayments.BillingAddressParam{
		Country: dodopayments.F(dodopayments.CountryCodeUs),
		City:    dodopayments.F("San Francisco"),
		State:   dodopayments.F("CA"),
		Street:  dodopayments.F("1 Market St"),
		Zipcode: dodopayments.F("94105"),
	}),
	Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
		dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")},
	),
	ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
		ProductID: dodopayments.F("pdt_456"),
		Quantity:  dodopayments.F(int64(1)),
	}}),
})
if err != nil {
	var apiErr *dodopayments.Error
	if errors.As(err, &apiErr) {
		fmt.Printf("Status Code: %d\n", apiErr.StatusCode)
		fmt.Println(string(apiErr.DumpResponse(true))) // Serialized HTTP response

		// Handle specific status codes
		switch apiErr.StatusCode {
		case 401:
			log.Println("Authentication failed")
		case 422:
			log.Println("Invalid request parameters")
		case 429:
			log.Println("Rate limit exceeded")
		default:
			log.Printf("API error: %s", apiErr.Error())
		}
	} else {
		log.Fatal(err)
	}
}
```

## Middleware

Benutzerdefinierte Middleware für Logging oder Metriken hinzufügen:

```go theme={null}
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 sicher für gleichzeitige Nutzung:

```go theme={null}
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.New(context.Background(), dodopayments.PaymentNewParams{
				Billing: dodopayments.F(dodopayments.BillingAddressParam{
					Country: dodopayments.F(dodopayments.CountryCodeUs),
					City:    dodopayments.F("San Francisco"),
					State:   dodopayments.F("CA"),
					Street:  dodopayments.F("1 Market St"),
					Zipcode: dodopayments.F("94105"),
				}),
				Customer: dodopayments.F[dodopayments.CustomerRequestUnionParam](
					dodopayments.AttachExistingCustomerParam{CustomerID: dodopayments.F("cus_123")},
				),
				ProductCart: dodopayments.F([]dodopayments.OneTimeProductCartItemParam{{
					ProductID: dodopayments.F("pdt_456"),
					Quantity:  dodopayments.F(int64(1)),
				}}),
			})
			if err != nil {
				log.Printf("Failed to create payment %d: %v", idx, err)
				return
			}
			
			log.Printf("Created payment %d: %s", idx, payment.PaymentID)
		}(i)
	}
	
	wg.Wait()
}
```

## Ressourcen

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-go">
    Den Quellcode anzeigen und beitragen
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Vollständige API-Dokumentation
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Hilfe erhalten und mit Entwicklern verbinden
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-go/issues">
    Fehler melden oder Funktionen anfordern
  </Card>
</CardGroup>

## Unterstützung

Benötigen Sie Hilfe mit dem Go SDK?

* **Discord**: Treten Sie unserem [Community-Server](https://discord.gg/bYqAp4ayYh) für Echtzeitunterstützung bei
* **E-Mail**: Kontaktieren Sie uns unter [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Öffnen Sie ein Problem im [Repository](https://github.com/dodopayments/dodopayments-go)

## Beitrag

Wir begrüßen Beiträge! Sehen Sie sich die [Beitragsrichtlinien](https://github.com/dodopayments/dodopayments-go/blob/main/CONTRIBUTING.md) an, um loszulegen.
