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

> Integra i pagamenti Dodo nelle tue applicazioni Ruby con un elegante SDK nativo Ruby

L'SDK Ruby fornisce un modo semplice e intuitivo per integrare i pagamenti Dodo nelle tue applicazioni Ruby. Segue le convenzioni e le migliori pratiche di Ruby, offrendo una gestione degli errori completa, paginazione e supporto per middleware.

## Installazione

Aggiungi la gem al tuo Gemfile:

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

<Tip>
  Usa sempre la versione più recente dell'SDK per accedere alle funzionalità più nuove di Dodo Payments. Esegui `bundle update dodopayments` regolarmente per restare aggiornato.
</Tip>

Poi esegui:

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

<Info>
  L’SDK supporta Ruby 3.2.0 e versioni successive, con tipi completi, gestione degli errori e meccanismi di retry.
</Info>

## Avvio Veloce

Inizializza il client e crea una sessione di checkout:

```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>
  Conserva le tue chiavi API in modo sicuro usando variabili d’ambiente. Non inserirle mai nel controllo versione né esporle nel codice.
</Warning>

## Caratteristiche Principali

<CardGroup cols={2}>
  <Card title="Ruby Conventions" icon="gem">
    Segue le convenzioni di nomenclatura e i pattern idiomatici di Ruby
  </Card>

  <Card title="Elegant Syntax" icon="code">
    API pulita e leggibile che risulta naturale per gli sviluppatori Ruby
  </Card>

  <Card title="Auto-Pagination" icon="arrows-rotate">
    Iteratori per auto-paginazione integrati nelle risposte di elenco
  </Card>

  <Card title="Type Safety" icon="shield-check">
    Tipi opzionali Sorbet per una maggiore sicurezza dei tipi
  </Card>
</CardGroup>

## Configurazione

### Configurazione del Timeout

Configura i timeout delle richieste:

```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}
)
```

### Configurazione del Retry

Configura il comportamento di ripetizione automatica:

```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}
)
```

## Operazioni Comuni

### Crea una Sessione di Checkout

Genera una sessione di checkout:

CODICE\_SEGNAPOSTO\_7c1ac649956d8988\_FINE

### Gestisci i Clienti

Crea e recupera informazioni sui clienti:

```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})"
```

### Gestisci Abbonamenti

Crea e gestisci abbonamenti ricorrenti:

```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` richiede almeno il codice `country` ISO a due lettere. `customer` accetta sia `{ customer_id: "..." }` per collegare un cliente esistente sia `{ email: "...", name: "..." }` per crearne uno nuovo. `product_price` è nella denominazione di valuta più bassa.
</Info>

## Paginazione

### Auto-Paginazione

Iterare automaticamente attraverso tutte le pagine:

```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
```

### Paginazione Manuale

Per avere più controllo sulla paginazione:

```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
```

## Gestione degli Errori

Gestire vari errori dell'API Dodo Payments:

```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>
  Implementare la logica di ripetizione con backoff esponenziale per gli errori di limite di velocità per garantire che la tua applicazione gestisca in modo efficace scenari ad alto volume.
</Tip>

## Sicurezza dei Tipi con Sorbet

Usa Sorbet per parametri di richiesta sicuri per tipo:

```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)
```

## Uso Avanzato

### Endpoint Non Documentati

Effettua richieste a endpoint non documentati:

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

### Parametri Non Documentati

Invia parametri non documentati:

```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])
```

## Integrazione con Rails

### Creare un Inizializzatore

Crea `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"
)
```

### Modello del Servizio

Crea un servizio di pagamento:

```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
```

### Integrazione con il Controller

Usa nei tuoi controller Rails:

CODICE\_SEGNAPOSTO\_69abc2503afdcf97\_FINE

## Integrazione con Sinatra

Usa con applicazioni Sinatra:

CODICE\_SEGNAPOSTO\_872fbf0ab03131bd\_FINE

## Risorse

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-ruby">
    Visualizza il codice sorgente e contribuisci
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Documentazione completa dell'API
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Ottieni aiuto e connettiti con gli sviluppatori
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-ruby/issues">
    Segnala bug o richiedi funzionalità
  </Card>
</CardGroup>

## Supporto

Hai bisogno di aiuto con il Ruby SDK?

* **Discord**: Unisciti al nostro [server della community](https://discord.gg/bYqAp4ayYh) per supporto in tempo reale
* **Email**: Contattaci a [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Apri un problema sul [repository](https://github.com/dodopayments/dodopayments-ruby)

## Contribuzione

Accogliamo con favore i contributi! Consulta le [linee guida per i contributi](https://github.com/dodopayments/dodopayments-ruby/blob/main/CONTRIBUTING.md) per iniziare.
