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

# Rust

> Integra Dodo Payments nelle tue applicazioni Rust con un SDK fortemente tipizzato e orientato all'async, basato su Tokio e reqwest

Il Rust SDK fornisce un accesso comodo e orientato all'async al REST API di Dodo Payments dalle applicazioni scritte in Rust. Offre richieste e risposte fortemente tipizzate, helper di paginazione integrati e timeout e ambienti configurabili.

## Installazione

Aggiungi l'SDK al tuo progetto con Cargo:

```bash theme={null}
cargo add dodopayments
```

Oppure aggiungilo manualmente al tuo `Cargo.toml`:

```toml theme={null}
[dependencies]
dodopayments = "1.106.0"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
futures = "0.3" # required for streaming paginated results
```

<Info>
  L'SDK richiede Rust 1.75 o successivi, sfruttando le moderne funzionalità async per prestazioni ottimali.
</Info>

## Guida Rapida

Il client legge la tua key API dalla variabile di ambiente `DODO_PAYMENTS_API_KEY` per impostazione predefinita. Inizializza il client e crea la tua prima sessione di checkout:

```rust theme={null}
use dodopayments::Client;

#[tokio::main]
async fn main() -> dodopayments::Result<()> {
    let client = Client::from_env()?;

    let result = client
        .checkout_sessions()
        .create()
        .body(dodopayments::models::CheckoutSessionsCreateParams {
            product_cart: Some(vec![dodopayments::models::ProductItemReq {
                product_id: "product_id".to_string(),
                quantity: 1,
                addons: None,
                amount: None,
                credit_entitlements: None,
            }]),
            ..Default::default()
        })
        .await?;

    println!("{result:?}");
    Ok(())
}
```

<Warning>
  Archivia sempre le tue key API in modo sicuro utilizzando variabili di ambiente. Non inserirle mai nel tuo codice sorgente.
</Warning>

## Funzionalità Principali

<CardGroup cols={2}>
  <Card title="Async First" icon="bolt">
    Basato su Tokio e reqwest con supporto `async`/`await`
  </Card>

  <Card title="Strong Typing" icon="shield-check">
    Richieste e risposte fortemente tipizzate per la sicurezza durante la compilazione
  </Card>

  <Card title="Auto-Pagination" icon="layer-group">
    Trasmetti ogni elemento attraverso le pagine o avanza una pagina alla volta
  </Card>

  <Card title="Configurable" icon="sliders">
    Configura ambienti, timeout e URL di base per cliente
  </Card>
</CardGroup>

## Configurazione

### Variabili di Ambiente

Per impostazione predefinita, `Client::from_env()` legge la tua key API dalla variabile di ambiente `DODO_PAYMENTS_API_KEY` e utilizza l'URL di base predefinito a meno che tu non imposti `DODO_PAYMENTS_BASE_URL`:

```bash theme={null}
export DODO_PAYMENTS_API_KEY="your_api_key"
export DODO_PAYMENTS_BASE_URL="https://test.dodopayments.com" # optional
```

Puoi anche configurare esplicitamente il client. `Client::new` restituisce un `Result`, quindi estrailo con `?` all'interno di una funzione che restituisce `dodopayments::Result`:

```rust theme={null}
use dodopayments::{Client, ClientConfig};

#[tokio::main]
async fn main() -> dodopayments::Result<()> {
    let client = Client::new(
        ClientConfig::new("https://live.dodopayments.com").with_api_key("My API Key"),
    )?;
    println!("{}", client.base_url());
    Ok(())
}
```

### Ambienti

| Nome        | URL di Base                     |
| ----------- | ------------------------------- |
| `live_mode` | `https://live.dodopayments.com` |
| `test_mode` | `https://test.dodopayments.com` |

L'URL di base predefinito è `https://live.dodopayments.com`. Seleziona un altro ambiente con l'enum `Environment` invece di codificare gli URL:

```rust theme={null}
use dodopayments::{Client, ClientConfig, Environment};

let client = Client::new(
    ClientConfig::from_environment(Environment::TestMode).with_api_key("My API Key"),
)?;
```

Per continuare a leggere la key API da `DODO_PAYMENTS_API_KEY` tramite `from_env()` mentre si punta a un ambiente non predefinito, sostituirlo nella configurazione:

```rust theme={null}
use dodopayments::{Client, ClientConfig, Environment};

let client = Client::new(ClientConfig::from_env()?.with_environment(Environment::TestMode))?;
```

### Timeout

Il timeout di richiesta predefinito è di 30 secondi. Sostituirlo per cliente:

```rust theme={null}
use std::time::Duration;
use dodopayments::{Client, ClientConfig};

let client = Client::new(
    ClientConfig::new("https://live.dodopayments.com")
        .with_api_key("My API Key")
        .with_timeout(Duration::from_secs(60)),
)?;
```

## Operazioni Comuni

### Crea una Sessione di Checkout

Genera una sessione di checkout:

```rust theme={null}
let session = client
    .checkout_sessions()
    .create()
    .body(dodopayments::models::CheckoutSessionsCreateParams {
        product_cart: Some(vec![dodopayments::models::ProductItemReq {
            product_id: "prod_123".to_string(),
            quantity: 1,
            addons: None,
            amount: None,
            credit_entitlements: None,
        }]),
        return_url: Some("https://yourdomain.com/return".to_string()),
        ..Default::default()
    })
    .await?;

println!("{session:?}");
```

### Gestisci Clienti

Crea e recupera informazioni sui clienti:

```rust theme={null}
// Create a customer
let customer = client
    .customers()
    .create()
    .body(dodopayments::models::CustomerCreateParams {
        email: "customer@example.com".to_string(),
        name: "John Doe".to_string(),
        ..Default::default()
    })
    .await?;

// Retrieve a customer
let customer = client
    .customers()
    .retrieve("cus_123")
    .await?;

println!("{customer:?}");
```

### Gestisci Abbonamenti

Crea e gestisci abbonamenti ricorrenti:

```rust theme={null}
let subscription = client
    .subscriptions()
    .create()
    .body(dodopayments::models::SubscriptionCreateParams {
        billing: dodopayments::models::BillingAddress {
            country: "US".to_string(),
            city: "San Francisco".to_string(),
            state: "CA".to_string(),
            street: "1 Market St".to_string(),
            zipcode: "94105".to_string(),
        },
        customer: dodopayments::models::CustomerRequest::AttachExisting(
            dodopayments::models::AttachExistingCustomer {
                customer_id: "cus_123".to_string(),
            },
        ),
        product_id: "pdt_456".to_string(),
        quantity: 1,
        ..Default::default()
    })
    .await?;

println!("{subscription:?}");
```

<Info>
  `billing` richiede almeno il codice ISO a due lettere `country`. `customer` è un enum `CustomerRequest` — passa `AttachExisting` per un cliente esistente o `New` per uno nuovo. I campi di importo come `product_price` sono nell'unità più bassa della valuta (e.g., `2500` = \$25.00 USD).
</Info>

## Fatturazione Basata sull'Uso

### Ingerire Eventi di Utilizzo

Monitorare eventi personalizzati:

```rust theme={null}
let response = client
    .usage_events()
    .ingest()
    .body(dodopayments::models::UsageEventsIngestParams {
        events: vec![dodopayments::models::EventInput {
            event_id: "api_call_12345".to_string(),
            customer_id: "cus_abc123".to_string(),
            event_name: "api_request".to_string(),
            ..Default::default()
        }],
    })
    .await?;

println!("{response:?}");
```

### Elenco degli Eventi di Utilizzo

```rust theme={null}
let events = client
    .usage_events()
    .list()
    .query(serde_json::json!({
        "customer_id": "cus_abc123",
        "event_name": "api_request",
    }))
    .await?;

for event in &events.items {
    println!("{event:?}");
}
```

## Paginazione

Gli endpoint dell'elenco restituiranno una pagina tipizzata il cui campo `items` contiene la pagina corrente dei risultati. Trasmetti ogni elemento attraverso tutte le pagine con `into_stream`:

```rust theme={null}
use futures::StreamExt;

let mut items = Box::pin(
    client
        .payments()
        .list()
        .query(serde_json::json!({}))
        .await?
        .into_stream(),
);

while let Some(item) = items.next().await {
    let item = item?;
    println!("{item:?}");
}
```

Oppure avanza una pagina alla volta con `get_next_page`:

```rust theme={null}
let mut page = client
    .payments()
    .list()
    .query(serde_json::json!({}))
    .await?;

loop {
    for item in &page.items {
        println!("{item:?}");
    }
    match page.get_next_page().await? {
        Some(next) => page = next,
        None => break,
    }
}
```

## Gestione degli Errori

Ogni metodo restituisce un `dodopayments::Result<T>`. I fallimenti sono rappresentati dall'enum `dodopayments::Error`. Puoi gestire gli errori API in modo distinto dagli errori di trasporto tramite match:

```rust theme={null}
let result = client
    .checkout_sessions()
    .create()
    .body(dodopayments::models::CheckoutSessionsCreateParams {
        product_cart: Some(vec![dodopayments::models::ProductItemReq {
            product_id: "product_id".to_string(),
            quantity: 1,
            addons: None,
            amount: None,
            credit_entitlements: None,
        }]),
        ..Default::default()
    })
    .await;

match result {
    Ok(value) => println!("{value:?}"),
    Err(dodopayments::Error::Api { status, message }) => {
        eprintln!("API returned {status}: {message}");
    }
    Err(err) => eprintln!("request failed: {err}"),
}
```

## Endpoint Non Documentati

Per chiamare un endpoint non ancora esposto come metodo tipizzato, usa il costruttore `request`, che applica l'autenticazione e l'URL di base:

```rust theme={null}
let response = client
    .request(reqwest::Method::GET, "/some/path")
    .send()
    .await?;
```

## Risorse

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

  <Card title="Crates.io" icon="cube" href="https://crates.io/crates/dodopayments">
    Visualizza il pacchetto pubblicato e le versioni
  </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">
    Ricevi aiuto e connettiti con gli sviluppatori
  </Card>
</CardGroup>

## Supporto

Hai bisogno di aiuto con il Rust SDK?

* **Discord**: Unisciti al nostro [server della comunità](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-rust/issues)

## Contributi

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