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

> Integrera Dodo Payments i dina PHP-applikationer med ett modernt, PSR-4-kompatibelt SDK

PHP SDK:n erbjuder ett robust och flexibelt sätt att integrera Dodo Payments i dina PHP-applikationer. Byggd enligt moderna PHP-standarder med PSR-4 autoloading, erbjuder den omfattande testtäckning och detaljerad dokumentation.

## Installation

Installera SDK:t med Composer:

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

<Info>
  SDK:t kräver PHP 8.1.0 eller högre och Composer för beroendehantering.
</Info>

## Kom igång snabbt

Initiera klienten och skapa en kassa-session:

```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>
  Förvara dina API-nycklar säkert med hjälp av miljövariabler. Visa aldrig dem i
  din kodbas eller checka in dem i versionshantering.
</Warning>

## Kärnfunktioner

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    Följer PHP Standards Recommendations för modern PHP-utveckling
  </Card>

  <Card title="Modern PHP" icon="php">
    Byggd för PHP 8.1+ med typedeklarationer och strikta typer
  </Card>

  <Card title="Extensive Testing" icon="vial">
    Omfattande testtäckning för pålitlighet och stabilitet
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    Tydliga undantagstyper för olika felscenarier
  </Card>
</CardGroup>

## Värdeobjekt

SDK:t använder namngivna parametrar för att ange valfria argument. Du kan initiera värdeobjekt med den statiska `with`-konstruktorn:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

Byggare finns också som ett alternativt mönster:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

## Konfiguration

### Konfiguration för omförsök

Vissa fel försöks automatiskt igen två gånger som standard med en kort exponentiell återgång. Följande fel utlöser automatiska omförsök:

* Anslutningsfel (nätverksproblem)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 500+ interna fel
* Tidsgränser

Konfigurera omförsöksbeteendet globalt eller per begäran:

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

## Vanliga operationer

### Skapa en kassa-session

Generera en kassa-session:

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

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

### Hantera kunder

Skapa och hämta kundinformation:

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

### Hantera prenumerationer

Skapa och hantera återkommande prenumerationer:

```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` kräver minst den tvåbokstaviga ISO `country`-koden. Skicka `AttachExistingCustomer::with(customerID: '...')` för att ansluta en befintlig kund, eller `NewCustomer::with(email: '...', name: '...')` för att skapa en. `productPrice` är i den lägsta valutadenominationen.
</Info>

## Pagination

Arbeta med paginerade listresponser:

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

## Felhantering

När biblioteket inte kan ansluta till API:et eller får tillbaka en statuskod som inte indikerar framgång (4xx eller 5xx), kastas en subklass av `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();
}
```

### Feltyper

| Orsak          | Feltyp                         |
| -------------- | ------------------------------ |
| HTTP 400       | `BadRequestException`          |
| HTTP 401       | `AuthenticationException`      |
| HTTP 403       | `PermissionDeniedException`    |
| HTTP 404       | `NotFoundException`            |
| HTTP 409       | `ConflictException`            |
| HTTP 422       | `UnprocessableEntityException` |
| HTTP 429       | `RateLimitException`           |
| HTTP >= 500    | `InternalServerException`      |
| Annan HTTP-fel | `APIStatusException`           |
| Timeout        | `APITimeoutException`          |
| Nätverksfel    | `APIConnectionException`       |

<Tip>
  Omge alltid API-anrop med try-catch block för att hantera potentiella fel
  på ett graciöst sätt och ge betydelsefull feedback till användarna.
</Tip>

## Avancerad användning

### Odokumenterade slutpunkter

Skicka förfrågningar till odokumenterade slutpunkter:

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

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

### Odokumenterade parametrar

Skicka odokumenterade parametrar till vilken slutpunkt som helst eller läs odokumenterade svarsegenskaper:

```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>
  `extra*` parametrar med samma namn åsidosätter dokumenterade parametrar.
</Note>

## Ramverksintegration

### Laravel

Skapa en tjänst för Laravel-applikationer:

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

Lägg till konfiguration i `config/services.php`:

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

### Symfony

Skapa en tjänst i 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
        );
    }
}
```

Registrera i `config/services.yaml`:

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

## Resurser

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    Visa källkod och bidra
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Komplett API-dokumentation
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Få hjälp och anslut med utvecklare
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-php/issues">
    Rapportera buggar eller begär funktioner
  </Card>
</CardGroup>

## Support

Behöver du hjälp med PHP SDK?

* **Discord**: Gå med i vår [community-server](https://discord.gg/bYqAp4ayYh) för support i realtid
* **E-post**: Kontakta oss på [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Öppna ett ärende på [repository](https://github.com/dodopayments/dodopayments-php)

## Bidra

Vi välkomnar bidrag! Kolla [riktlinjer för att bidra](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) för att komma igång.
