> ## 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.

# Ruby

> Integrieren Sie Dodo Payments in Ihre Ruby-Anwendungen mit einem eleganten, Ruby-nativen SDK

Das Ruby SDK bietet eine einfache und intuitive Möglichkeit, Dodo Payments in Ihre Ruby-Anwendungen zu integrieren. Es folgt den Ruby-Konventionen und Best Practices und bietet umfassende Fehlerbehandlung, Paginierung und Middleware-Unterstützung.

## Installation

Fügen Sie das Gem zu Ihrer Gemfile hinzu:

```ruby Gemfile theme={null}
gem "dodopayments", "~> 2.9"
```

<Tip>
  Verwenden Sie immer die neueste SDK-Version, um auf die neuesten Dodo Payments-Funktionen zuzugreifen. Führen Sie `bundle update dodopayments` regelmäßig aus, um auf dem neuesten Stand zu bleiben.
</Tip>

Führen Sie dann aus:

```bash theme={null}
bundle install
```

<Info>
  Das SDK unterstützt Ruby 3.2.0 und spätere Versionen mit umfassenden Typen, Fehlerbehandlung und Retry-Mechanismen.
</Info>

## Schnellstart

Initialisieren Sie den Client und erstellen Sie eine Checkout-Sitzung:

```ruby theme={null}
require "bundler/setup"
require "dodopayments"

dodo_payments = Dodopayments::Client.new(
  bearer_token: ENV["DODO_PAYMENTS_API_KEY"], # This is the default and can be omitted
  environment: "test_mode" # defaults to "live_mode"
)

checkout_session_response = dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", quantity: 1}]
)

puts(checkout_session_response.session_id)
```

<Warning>
  Speichern Sie Ihre API-Schlüssel sicher mithilfe von Umgebungsvariablen. Committen Sie sie niemals in die Versionskontrolle oder legen Sie sie offen in Ihrem Code ab.
</Warning>

## Kernfunktionen

<CardGroup cols={2}>
  <Card title="Ruby Conventions" icon="gem">
    Entspricht den Ruby-Benennungskonventionen und idiomatischen Mustern
  </Card>

  <Card title="Elegant Syntax" icon="code">
    Saubere, gut lesbare API, die sich für Ruby-Entwickler natürlich anfühlt
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    Eingebaute Auto-Paging-Iteratoren für Listenantworten
  </Card>

  <Card title="Type Safety" icon="shield-check">
    Optionale Sorbet-Typen für verbesserte Typensicherheit
  </Card>
</CardGroup>

## Konfiguration

### Timeout-Konfiguration

Konfigurieren Sie die Anfrage-Timeouts:

```ruby theme={null}
# Configure default for all requests (default is 60 seconds)
dodo_payments = Dodopayments::Client.new(
  timeout: nil # disable timeout
)

# Or, configure per-request
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", quantity: 1}],
  request_options: {timeout: 5}
)
```

### Wiederholungs-Konfiguration

Konfigurieren Sie das automatische Wiederholungsverhalten:

```ruby theme={null}
# Configure default for all requests (default is 2)
dodo_payments = Dodopayments::Client.new(
  max_retries: 0 # disable retries
)

# Or, configure per-request
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", quantity: 1}],
  request_options: {max_retries: 5}
)
```

## Häufige Operationen

### Erstellen einer Checkout-Sitzung

Generieren Sie eine Checkout-Sitzung:

```ruby theme={null}
session = dodo_payments.checkout_sessions.create(
  product_cart: [
    {
      product_id: "prod_123",
      quantity: 1
    }
  ],
  return_url: "https://yourdomain.com/return"
)

# Redirect to checkout
redirect_to session.checkout_url
```

### Kunden verwalten

Erstellen und Abrufen von Kundeninformationen:

```ruby theme={null}
# Create a customer
customer = dodo_payments.customers.create(
  email: "customer@example.com",
  name: "John Doe",
  metadata: {
    user_id: "12345"
  }
)

# Retrieve customer
customer = dodo_payments.customers.retrieve("cus_123")
puts "Customer: #{customer.name} (#{customer.email})"
```

### Abonnements verwalten

Erstellen und verwalten Sie wiederkehrende Abonnements:

```ruby theme={null}
# Create a subscription
subscription = dodo_payments.subscriptions.create(
  billing: {
    country: "US",
    city: "San Francisco",
    state: "CA",
    street: "1 Market St",
    zipcode: "94105"
  },
  customer: { customer_id: "cus_123" }, # or { email: "...", name: "..." } for a new customer
  product_id: "pdt_456",
  quantity: 1
)

# Charge an on-demand subscription
# product_price is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
charge = dodo_payments.subscriptions.charge(
  subscription.subscription_id,
  product_price: 2500
)

# Update subscription metadata
updated = dodo_payments.subscriptions.update(
  subscription.subscription_id,
  metadata: { plan_type: "premium" }
)
```

<Info>
  `billing` erfordert mindestens den zweibuchstabigen ISO `country` Code. `customer` akzeptiert entweder `{ customer_id: "..." }`, um einen bestehenden Kunden anzuhängen, oder `{ email: "...", name: "..." }`, um einen neuen zu erstellen. `product_price` ist in der kleinsten Währungsdenomination.
</Info>

## Paginierung

### Auto-Paginierung

Automatisch durch alle Seiten iterieren:

```ruby theme={null}
page = dodo_payments.payments.list

# Fetch single item from page
payment = page.items[0]
puts(payment.brand_id)

# Automatically fetches more pages as needed
page.auto_paging_each do |payment|
  puts(payment.brand_id)
end
```

### Manuelle Paginierung

Für mehr Kontrolle über die Paginierung:

```ruby theme={null}
page = dodo_payments.payments.list

if page.next_page?
  new_page = page.next_page
  puts(new_page.items[0].brand_id)
end
```

## Fehlerbehandlung

Verschiedene Dodo Payments API-Fehler behandeln:

```ruby theme={null}
begin
  checkout_session = dodo_payments.checkout_sessions.create(
product_cart: [{product_id: "product_id", quantity: 1}]
  )
rescue Dodopayments::Errors::APIConnectionError => e
  puts("The server could not be reached")
  puts(e.cause)  # an underlying Exception, likely raised within `net/http`
rescue Dodopayments::Errors::RateLimitError => e
  puts("A 429 status code was received; we should back off a bit.")
rescue Dodopayments::Errors::APIStatusError => e
  puts("Another non-200-range status code was received")
  puts(e.status)
end
```

<Tip>
  Retry-Logik mit exponentiellen Backoff für Rate-Limit-Fehler implementieren, um sicherzustellen, dass Ihre Anwendung Hochvolumen-Szenarien elegant verarbeitet.
</Tip>

## Typsicherheit mit Sorbet

Sorbet für typsichere Anfrageparameter verwenden:

```ruby theme={null}
# Type-safe using Sorbet RBI definitions
dodo_payments.checkout_sessions.create(
  product_cart: [
    Dodopayments::ProductItemReq.new(
      product_id: "product_id",
      quantity: 1
    )
  ]
)

# Hashes work, but are not typesafe
dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", quantity: 1}]
)

# You can also splat a full Params class
params = Dodopayments::CheckoutSessionCreateParams.new(
  product_cart: [
    Dodopayments::ProductItemReq.new(
      product_id: "product_id",
      quantity: 1
    )
  ]
)
dodo_payments.checkout_sessions.create(**params)
```

## Erweiterte Nutzung

### Undokumentierte Endpunkte

Anfragen an undokumentierte Endpunkte stellen:

```ruby theme={null}
response = dodo_payments.request(
  method: :post,
  path: '/undocumented/endpoint',
  query: {"dog": "woof"},
  headers: {"useful-header": "interesting-value"},
  body: {"hello": "world"}
)
```

### Undokumentierte Parameter

Undokumentierte Parameter senden:

```ruby theme={null}
checkout_session_response = dodo_payments.checkout_sessions.create(
  product_cart: [{product_id: "product_id", quantity: 1}],
  request_options: {
    extra_query: {my_query_parameter: value},
    extra_body: {my_body_parameter: value},
    extra_headers: {"my-header": value}
  }
)

# Access undocumented response properties
puts(checkout_session_response[:my_undocumented_property])
```

## Rails-Integration

### Initializer erstellen

Erstellen `config/initializers/dodo_payments.rb`:

```ruby theme={null}
require "dodopayments"

DODO_CLIENT = Dodopayments::Client.new(
  bearer_token: Rails.application.credentials.dodo_api_key,
  environment: Rails.env.production? ? "live_mode" : "test_mode"
)
```

### Service-Objekt-Muster

Einen Zahlungsservice erstellen:

```ruby theme={null}
# app/services/payment_service.rb
class PaymentService
  def initialize
    @client = DODO_CLIENT
  end

  def create_checkout(items)
    @client.checkout_sessions.create(
      product_cart: items,
      return_url: Rails.application.routes.url_helpers.checkout_return_url
    )
  end

  def process_payment(amount:, currency:, customer_id:)
    @client.payments.create(
      amount: amount,
      currency: currency,
      customer_id: customer_id
    )
  end
end
```

### Controller-Integration

In Ihren Rails-Controllern verwenden:

```ruby theme={null}
# app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def create
    service = PaymentService.new
    session = service.create_checkout(checkout_params[:items])
    
    redirect_to session.checkout_url, allow_other_host: true
  rescue Dodopayments::Errors::APIError => e
    flash[:error] = "Payment error: #{e.message}"
    redirect_to cart_path
  end

  private

  def checkout_params
    params.require(:checkout).permit(items: [:product_id, :quantity])
  end
end
```

## Sinatra-Integration

Mit Sinatra-Anwendungen verwenden:

```ruby theme={null}
require "sinatra"
require "dodopayments"

configure do
  set :dodo_client, Dodopayments::Client.new(
    bearer_token: ENV["DODO_API_KEY"]
  )
end

post "/create-checkout" do
  content_type :json
  
  begin
    session = settings.dodo_client.checkout_sessions.create(
      product_cart: JSON.parse(request.body.read)["items"],
      return_url: "#{request.base_url}/return"
    )
    
    { checkout_url: session.checkout_url }.to_json
  rescue Dodopayments::Errors::APIError => e
    status 400
    { error: e.message }.to_json
  end
end
```

## Ressourcen

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-ruby">
    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-ruby/issues">
    Fehler melden oder Funktionen anfordern
  </Card>
</CardGroup>

## Unterstützung

Benötigen Sie Hilfe mit dem Ruby SDK?

* **Discord**: Treten Sie unserem [Community-Server](https://discord.gg/bYqAp4ayYh) bei, um Echtzeit-Support zu erhalten
* **Email**: Kontaktieren Sie uns unter [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Eröffnen Sie ein Issue im [Repository](https://github.com/dodopayments/dodopayments-ruby)

## Mitwirken

Wir begrüßen Beiträge! Prüfen Sie die [Mitwirkungsrichtlinien](https://github.com/dodopayments/dodopayments-ruby/blob/main/CONTRIBUTING.md), um loszulegen.
