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

> Integrieren Sie Dodo Payments in Ihre PHP-Anwendungen mit einem modernen, PSR-4-konformen SDK

Das PHP SDK bietet eine robuste und flexible Möglichkeit, Dodo Payments in Ihre PHP-Anwendungen zu integrieren. Es wurde nach modernen PHP-Standards mit PSR-4-Autoloading entwickelt und bietet umfassende Testabdeckung sowie detaillierte Dokumentation.

## Installation

Installieren Sie das SDK mit Composer:

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

<Info>
  Das SDK benötigt PHP 8.1.0 oder höher sowie Composer für die Abhängigkeitsverwaltung.
</Info>

## Schnellstart

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

```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>
  Speichern Sie Ihre API-Schlüssel sicher mit Umgebungsvariablen. Geben Sie sie niemals im Code oder in der Versionskontrolle frei.
</Warning>

## Kernfunktionen

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    Entspricht den PHP Standards-Empfehlungen für moderne PHP-Entwicklung
  </Card>

  <Card title="Modern PHP" icon="php">
    Entwickelt für PHP 8.1+ mit Typdeklarationen und strikten Typen
  </Card>

  <Card title="Extensive Testing" icon="vial">
    Umfassende Testabdeckung für Zuverlässigkeit und Stabilität
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    Klar definierte Ausnahmearten für verschiedene Fehlerszenarien
  </Card>
</CardGroup>

## Value-Objekte

Das SDK verwendet benannte Parameter, um optionale Argumente anzugeben. Sie können Value-Objekte mit dem statischen `with`-Konstruktor initialisieren:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

Builder sind ebenfalls als alternatives Muster verfügbar:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

## Konfiguration

### Wiederholungs-Konfiguration

Bestimmte Fehler werden standardmäßig zweimal automatisch mit einem kurzen exponentiellen Backoff erneut versucht. Die folgenden Fehler lösen automatische Wiederholungen aus:

* Verbindungsfehler (Netzwerkprobleme)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 500+ Internal errors
* Timeouts

Konfigurieren Sie das Wiederholungsverhalten global oder pro Anfrage:

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

## Häufige Vorgänge

### Erstellen einer Checkout-Sitzung

Erzeugen Sie eine Checkout-Sitzung:

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

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

### Kunden verwalten

Erstellen und abrufen von Kundeninformationen:

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

### Abonnements verwalten

Erstellen und Verwalten wiederkehrender Abonnements:

```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` benötigt mindestens den zweistelligen ISO `country`-Code. Übergeben Sie `AttachExistingCustomer::with(customerID: '...')`, um einen bestehenden Kunden zu verknüpfen, oder `NewCustomer::with(email: '...', name: '...')`, um einen zu erstellen. `productPrice` ist in der kleinsten Währungseinheit.
</Info>

## Paginierung

Arbeiten mit paginierten Listenantworten:

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

## Fehlerbehandlung

Wenn die Bibliothek keine Verbindung zur API herstellen kann oder einen Statuscode ungleich Erfolg (4xx oder 5xx) erhält, wird eine Unterklasse von `APIException` ausgelöst:

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

### Fehlertypen

| Ursache             | Fehlertyp                      |
| ------------------- | ------------------------------ |
| HTTP 400            | `BadRequestException`          |
| HTTP 401            | `AuthenticationException`      |
| HTTP 403            | `PermissionDeniedException`    |
| HTTP 404            | `NotFoundException`            |
| HTTP 409            | `ConflictException`            |
| HTTP 422            | `UnprocessableEntityException` |
| HTTP 429            | `RateLimitException`           |
| HTTP >= 500         | `InternalServerException`      |
| Anderer HTTP-Fehler | `APIStatusException`           |
| Timeout             | `APITimeoutException`          |
| Netzwerkfehler      | `APIConnectionException`       |

<Tip>
  API-Aufrufe immer in try-catch-Blöcken einbetten, um potenzielle Fehler
  elegant zu behandeln und den Benutzern aussagekräftiges Feedback zu geben.
</Tip>

## Erweiterte Nutzung

### Undokumentierte Endpunkte

Anfragen an undokumentierte Endpunkte stellen:

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

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

### Undokumentierte Parameter

Undokumentierte Parameter an jeden Endpunkt senden oder undokumentierte Antwort-Eigenschaften lesen:

```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>
  Die `extra*`-Parameter mit demselben Namen überschreiben dokumentierte Parameter.
</Note>

## Framework-Integration

### Laravel

Erstellen Sie einen Dienst für Laravel-Anwendungen:

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

Konfiguration in `config/services.php` hinzufügen:

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

### Symfony

Erstellen Sie einen Dienst 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
        );
    }
}
```

In `config/services.yaml` registrieren:

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

## Ressourcen

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

## Unterstützung

Brauchen Sie Hilfe mit dem PHP SDK?

* **Discord**: Treten Sie unserem [Community-Server](https://discord.gg/bYqAp4ayYh) für Echtzeit-Support bei
* **Email**: Kontaktieren Sie uns unter [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Öffnen Sie ein Issue im [Repository](https://github.com/dodopayments/dodopayments-php)

## Beitrag leisten

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