> ## 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 en tus aplicaciones PHP con un SDK moderno y compatible con PSR-4

El SDK de PHP proporciona una forma robusta y flexible de integrar Dodo Payments en tus aplicaciones PHP. Construido siguiendo los estándares modernos de PHP con autoloading PSR-4, ofrece una amplia cobertura de pruebas y documentación detallada.

## Instalación

Instala el SDK con Composer:

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

<Info>
  El SDK requiere PHP 8.1.0 o superior y Composer para la gestión de dependencias.
</Info>

## Inicio rápido

Inicializa el cliente y crea una sesión de pago:

```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>
  Guarda tus claves de API de forma segura utilizando variables de entorno. Nunca las expongas
  en tu código ni las incluyas en el control de versiones.
</Warning>

## Características principales

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    Cumple con las Recomendaciones de Estándares de PHP para el desarrollo moderno en PHP
  </Card>

  <Card title="Modern PHP" icon="php">
    Diseñado para PHP 8.1+ con declaraciones de tipo y tipos estrictos
  </Card>

  <Card title="Extensive Testing" icon="vial">
    Cobertura de pruebas integral para garantizar fiabilidad y estabilidad
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    Tipos de excepción claros para distintos escenarios de error
  </Card>
</CardGroup>

## Objetos de valor

El SDK utiliza parámetros nombrados para especificar argumentos opcionales. Puedes inicializar objetos de valor usando el constructor estático `with`:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

También hay constructores disponibles como patrón alternativo:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

## Configuración

### Configuración de reintentos

Ciertos errores se reintentan automáticamente 2 veces por defecto con un retroceso exponencial corto. Los siguientes errores activan reintentos automáticos:

* Errores de conexión (problemas de conectividad de red)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 500+ Internal errors
* Timeouts

Configura el comportamiento de reintentos de forma global o por solicitud:

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

## Operaciones comunes

### Crear una sesión de pago

Genera una sesión de pago:

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

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

### Gestionar clientes

Crea y recupera información de clientes:

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

### Gestionar suscripciones

Crea y administra suscripciones recurrentes:

```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` requiere al menos el código `country` ISO de dos letras. Pase `AttachExistingCustomer::with(customerID: '...')` para adjuntar un cliente existente, o `NewCustomer::with(email: '...', name: '...')` para crear uno. `productPrice` está en la denominación más baja de la moneda.
</Info>

## Paginación

Trabajar con respuestas de lista paginadas:

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

## Manejo de Errores

Cuando la biblioteca no puede conectarse a la API o recibe un código de estado negativo (4xx o 5xx), se lanza una subclase de `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();
}
```

### Tipos de Error

| Causa            | Tipo de Error                  |
| ---------------- | ------------------------------ |
| HTTP 400         | `BadRequestException`          |
| HTTP 401         | `AuthenticationException`      |
| HTTP 403         | `PermissionDeniedException`    |
| HTTP 404         | `NotFoundException`            |
| HTTP 409         | `ConflictException`            |
| HTTP 422         | `UnprocessableEntityException` |
| HTTP 429         | `RateLimitException`           |
| HTTP >= 500      | `InternalServerException`      |
| Otro error HTTP  | `APIStatusException`           |
| Tiempo de espera | `APITimeoutException`          |
| Error de red     | `APIConnectionException`       |

<Tip>
  Siempre envuelva llamadas API en bloques try-catch para manejar posibles errores
  de manera elegante y proporcionar retroalimentación significativa a los usuarios.
</Tip>

## Uso Avanzado

### Endpoints No Documentados

Realizar solicitudes a endpoints no documentados:

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

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

### Parámetros No Documentados

Enviar parámetros no documentados a cualquier endpoint o leer propiedades de respuesta no documentadas:

```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>
  Los parámetros `extra*` con el mismo nombre sobrescriben los parámetros documentados.
</Note>

## Integración con Frameworks

### Laravel

Crear un servicio para aplicaciones 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')
        );
    }
}
```

Agregar configuración en `config/services.php`:

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

### Symfony

Crear un servicio en 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
        );
    }
}
```

Registrar en `config/services.yaml`:

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

## Recursos

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    Ver el código fuente y contribuir
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Documentación completa de la API
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Obtener ayuda y conectar con desarrolladores
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-php/issues">
    Reportar errores o solicitar funciones
  </Card>
</CardGroup>

## Soporte

¿Necesitas ayuda con el SDK de PHP?

* **Discord**: Únete a nuestro [servidor comunitario](https://discord.gg/bYqAp4ayYh) para soporte en tiempo real
* **Email**: Contáctanos en [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Abre un problema en el [repositorio](https://github.com/dodopayments/dodopayments-php)

## Contribuyendo

¡Damos la bienvenida a contribuciones! Revisa las [directrices de contribución](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) para comenzar.
