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

# PHP

> Integra Dodo Payments nelle tue applicazioni PHP con un SDK moderno e conforme a PSR-4

L'SDK PHP fornisce un modo robusto e flessibile per integrare Dodo Payments nelle tue applicazioni PHP. Costruito seguendo gli standard PHP moderni con autoloading PSR-4, offre una copertura di test estesa e documentazione dettagliata.

## Installazione

Installa l'SDK usando Composer:

```bash theme={null}
composer require "dodopayments/client 6.7.1"
```

<Info>
  L'SDK richiede PHP 8.1.0 o superiore e Composer per la gestione delle dipendenze.
</Info>

## Avvio rapido

Inizializza il client e crea una sessione di checkout:

```php theme={null}
<?php

use Dodopayments\Client;

$client = new Client(
  bearerToken: getenv('DODO_PAYMENTS_API_KEY') ?: 'My Bearer Token',
  environment: 'test_mode',
);

$checkoutSessionResponse = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]]
);

var_dump($checkoutSessionResponse->session_id);
```

<Warning>
  Conserva le chiavi API in modo sicuro usando variabili d'ambiente. Non esporle mai
  nel tuo codice o non committarle nel controllo versione.
</Warning>

## Funzionalità principali

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    Segue le PHP Standards Recommendations per lo sviluppo PHP moderno
  </Card>

  <Card title="Modern PHP" icon="php">
    Progettato per PHP 8.1+ con dichiarazioni di tipo e strict types
  </Card>

  <Card title="Extensive Testing" icon="vial">
    Copertura completa dei test per affidabilità e stabilità
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    Tipi di eccezione chiari per scenari di errore diversi
  </Card>
</CardGroup>

## Oggetti di valore

L'SDK utilizza parametri nominati per specificare argomenti opzionali. Puoi inizializzare gli oggetti di valore usando il costruttore statico `with`:

```php theme={null}
<?php

use Dodopayments\Customers\AttachExistingCustomer;

// Recommended: Use static 'with' constructor with named parameters
$customer = AttachExistingCustomer::with(customerID: "customer_id");
```

Sono disponibili anche builder come pattern alternativo:

```php theme={null}
<?php

use Dodopayments\Customers\AttachExistingCustomer;

// Alternative: Use builder pattern
$customer = (new AttachExistingCustomer)->withCustomerID("customer_id");
```

## Configurazione

### Configurazione dei tentativi

Alcuni errori vengono riprovati automaticamente 2 volte per impostazione predefinita con un breve backoff esponenziale. I seguenti errori attivano il ripristino automatico:

* Errori di connessione (problemi di connettività di rete)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 500+ Errori interni
* Timeout

Configura il comportamento dei tentativi globalmente o per singola richiesta:

```php theme={null}
<?php

use Dodopayments\Client;

// Configure default for all requests (disable retries)
$client = new Client(requestOptions: ['maxRetries' => 0]);

// Or, configure per-request
$result = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]],
  requestOptions: ['maxRetries' => 5],
);
```

## Operazioni comuni

### Crea una sessione di checkout

Genera una sessione di checkout:

```php theme={null}
$session = $client->checkoutSessions->create(
  productCart: [
    ["productID" => "prod_123", "quantity" => 1]
  ],
  returnUrl: "https://yourdomain.com/return"
);

header('Location: ' . $session->checkout_url);
```

### Gestisci clienti

Crea e recupera informazioni sui clienti:

```php theme={null}
// Create a customer
$customer = $client->customers->create(
  email: "customer@example.com",
  name: "John Doe",
  metadata: [
    "user_id" => "12345"
  ]
);

// Retrieve customer
$customer = $client->customers->retrieve("cus_123");
echo "Customer: {$customer->name} ({$customer->email})";
```

### Gestisci abbonamenti

Crea e gestisci abbonamenti ricorrenti:

```php theme={null}
use Dodopayments\Customers\AttachExistingCustomer;
use Dodopayments\Payments\BillingAddress;

// Create a subscription
$subscription = $client->subscriptions->create(
  billing: BillingAddress::with(
    country: 'US',
    city: 'San Francisco',
    state: 'CA',
    street: '1 Market St',
    zipcode: '94105',
  ),
  customer: AttachExistingCustomer::with(customerID: 'cus_123'),
  productID: 'pdt_456',
  quantity: 1,
);

// Charge an on-demand subscription
// productPrice is in the lowest currency denomination (e.g., 2500 = $25.00 USD)
$charge = $client->subscriptions->charge(
  $subscription->subscription_id,
  productPrice: 2500,
);
```

<Info>
  `billing` richiede almeno il codice ISO a due lettere `country`. Passa `AttachExistingCustomer::with(customerID: '...')` per collegare un cliente esistente, o `NewCustomer::with(email: '...', name: '...')` per crearne uno. `productPrice` è nella denominazione valutaria più bassa.
</Info>

## Paginazione

Lavora con le risposte dell'elenco paginato:

```php theme={null}
$page = $client->payments->list();

var_dump($page);

// Fetch items from the current page
foreach ($page->getItems() as $item) {
  var_dump($item->brand_id);
}

// Auto-paginate: fetch items from all pages
foreach ($page->pagingEachItem() as $item) {
  var_dump($item->brand_id);
}
```

## Gestione degli Errori

Quando la libreria non può connettersi all'API o riceve un codice di stato non di successo (4xx o 5xx), viene lanciata una sottoclasse di `APIException`:

```php theme={null}
<?php

use Dodopayments\Core\Exceptions\APIConnectionException;
use Dodopayments\Core\Exceptions\RateLimitException;
use Dodopayments\Core\Exceptions\APIStatusException;

try {
  $checkoutSessionResponse = $client->checkoutSessions->create(
    productCart: [["productID" => "product_id", "quantity" => 1]]
  );
} catch (APIConnectionException $e) {
  echo "The server could not be reached", PHP_EOL;
  var_dump($e->getPrevious());
} catch (RateLimitException $_) {
  echo "A 429 status code was received; we should back off a bit.", PHP_EOL;
} catch (APIStatusException $e) {
  echo "Another non-200-range status code was received", PHP_EOL;
  echo $e->getMessage();
}
```

### Tipi di Errore

| Causa             | Tipo di Errore                 |
| ----------------- | ------------------------------ |
| HTTP 400          | `BadRequestException`          |
| HTTP 401          | `AuthenticationException`      |
| HTTP 403          | `PermissionDeniedException`    |
| HTTP 404          | `NotFoundException`            |
| HTTP 409          | `ConflictException`            |
| HTTP 422          | `UnprocessableEntityException` |
| HTTP 429          | `RateLimitException`           |
| HTTP >= 500       | `InternalServerException`      |
| Altro errore HTTP | `APIStatusException`           |
| Timeout           | `APITimeoutException`          |
| Errore di rete    | `APIConnectionException`       |

<Tip>
  Avvolgi sempre le chiamate API in blocchi try-catch per gestire i potenziali errori
  con grazia e fornire feedback significativi agli utenti.
</Tip>

## Uso Avanzato

### Endpoint Non Documentati

Effettua richieste agli endpoint non documentati:

```php theme={null}
<?php

$response = $client->request(
  method: "post",
  path: '/undocumented/endpoint',
  query: ['dog' => 'woof'],
  headers: ['useful-header' => 'interesting-value'],
  body: ['hello' => 'world']
);
```

### Parametri Non Documentati

Invia parametri non documentati a qualsiasi endpoint o leggi le proprietà della risposta non documentate:

```php theme={null}
<?php

use Dodopayments\RequestOptions;

$checkoutSessionResponse = $client->checkoutSessions->create(
  productCart: [["productID" => "product_id", "quantity" => 1]],
  requestOptions: [
    'extraQueryParams' => ["my_query_parameter" => "value"],
    'extraBodyParams' => ["my_body_parameter" => "value"],
    'extraHeaders' => ["my-header" => "value"],
  ],
);
```

<Note>
  I parametri `extra*` con lo stesso nome sovrascrivono i parametri documentati.
</Note>

## Integrazione del Framework

### Laravel

Crea un servizio per le applicazioni Laravel:

```php theme={null}
<?php

namespace App\Services;

use Dodopayments\Client;

class PaymentService
{
    protected $client;

    public function __construct()
    {
        $this->client = new Client(
            bearerToken: config('services.dodo.api_key')
        );
    }

    public function createCheckout(array $items)
    {
        return $this->client->checkoutSessions->create(
            productCart: $items,
            returnUrl: route('checkout.return')
        );
    }
}
```

Aggiungi configurazione in `config/services.php`:

```php theme={null}
'dodo' => [
    'api_key' => env('DODO_API_KEY'),
    'environment' => env('DODO_ENVIRONMENT', 'sandbox')
],
```

### Symfony

Crea un servizio in Symfony:

```php theme={null}
<?php

namespace App\Service;

use Dodopayments\Client;

class DodoPaymentService
{
    private Client $client;

    public function __construct(string $apiKey)
    {
        $this->client = new Client(bearerToken: $apiKey);
    }

    public function createPayment(int $amount, string $currency, string $customerId): object
    {
        return $this->client->payments->create(
            amount: $amount,
            currency: $currency,
            customerID: $customerId
        );
    }
}
```

Registra in `config/services.yaml`:

```yaml theme={null}
services:
  App\Service\DodoPaymentService:
    arguments:
      $apiKey: "%env(DODO_API_KEY)%"
```

## Risorse

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    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-php/issues">
    Segnala bug o richiedi funzionalità
  </Card>
</CardGroup>

## Supporto

Hai bisogno di aiuto con l'SDK PHP?

* **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-php)

## Contribuire

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