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

> Tích hợp Dodo Payments vào các ứng dụng PHP của bạn với SDK hiện đại, tuân thủ PSR-4

SDK PHP cung cấp một cách mạnh mẽ và linh hoạt để tích hợp Dodo Payments vào các ứng dụng PHP của bạn. Được xây dựng theo các tiêu chuẩn PHP hiện đại với autoloading PSR-4, nó cung cấp độ phủ kiểm tra rộng rãi và tài liệu chi tiết.

## Cài đặt

Cài đặt SDK bằng Composer:

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

<Info>
  SDK yêu cầu PHP 8.1.0 trở lên và Composer để quản lý phụ thuộc.
</Info>

## Bắt đầu nhanh

Khởi tạo client và tạo phiên thanh toán:

```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>
  Lưu trữ các khóa API một cách an toàn bằng biến môi trường. Không bao giờ để lộ chúng trong mã nguồn hoặc cam kết chúng vào hệ thống kiểm soát phiên bản.
</Warning>

## Tính năng chính

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    Tuân theo khuyến nghị chuẩn PHP cho phát triển PHP hiện đại
  </Card>

  <Card title="Modern PHP" icon="php">
    Xây dựng cho PHP 8.1+ với khai báo kiểu và strict types
  </Card>

  <Card title="Extensive Testing" icon="vial">
    Bao phủ kiểm thử toàn diện để đảm bảo độ tin cậy và ổn định
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    Các loại ngoại lệ rõ ràng cho các tình huống lỗi khác nhau
  </Card>
</CardGroup>

## Các đối tượng giá trị

SDK sử dụng tham số đặt tên để chỉ định các đối số tùy chọn. Bạn có thể khởi tạo đối tượng giá trị bằng cách sử dụng constructor tĩnh `with`:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

Các builder cũng có sẵn như một mẫu thay thế:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

## Cấu hình

### Cấu hình thử lại

Một số lỗi được tự động thử lại 2 lần theo mặc định với độ chờ tăng theo hàm mũ ngắn. Các lỗi sau dẫn đến thử lại tự động:

* Lỗi kết nối (sự cố kết nối mạng)
* 408 Request Timeout
* 409 Conflict
* 429 Rate Limit
* 500+ lỗi nội bộ
* Hết thời gian chờ

Cấu hình hành vi thử lại toàn cục hoặc theo từng yêu cầu:

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

## Các thao tác phổ biến

### Tạo phiên thanh toán

Tạo một phiên thanh toán:

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

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

### Quản lý khách hàng

Tạo và lấy thông tin khách hàng:

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

### Xử lý đăng ký

Tạo và quản lý đăng ký định kỳ:

```php theme={null}
// Create a subscription
$subscription = $client->subscriptions->create(
  customerID: "cus_123",
  productID: "prod_456",
  priceID: "price_789"
);

// Cancel subscription
$client->subscriptions->cancel($subscription->id);
```

## Phân trang

Làm việc với phản hồi danh sách phân trang:

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

## Xử lý lỗi

Khi thư viện không thể kết nối với API hoặc nhận được mã trạng thái không thành công (4xx hoặc 5xx), một lớp con của `APIException` được ném ra:

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

### Các loại lỗi

| Nguyên nhân       | Loại lỗi                       |
| ----------------- | ------------------------------ |
| HTTP 400          | `BadRequestException`          |
| HTTP 401          | `AuthenticationException`      |
| HTTP 403          | `PermissionDeniedException`    |
| HTTP 404          | `NotFoundException`            |
| HTTP 409          | `ConflictException`            |
| HTTP 422          | `UnprocessableEntityException` |
| HTTP 429          | `RateLimitException`           |
| HTTP >= 500       | `InternalServerException`      |
| Other HTTP error  | `APIStatusException`           |
| Hết thời gian chờ | `APITimeoutException`          |
| Lỗi mạng          | `APIConnectionException`       |

<Tip>
  Luôn bao các cuộc gọi API trong các khối try-catch để xử lý lỗi một cách nhẹ nhàng và cung cấp phản hồi có ý nghĩa cho người dùng.
</Tip>

## Sử dụng nâng cao

### Các endpoint không có tài liệu

Gửi yêu cầu tới các endpoint không có tài liệu:

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

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

### Tham số không có tài liệu

Gửi tham số chưa được ghi tài liệu tới bất kỳ endpoint nào hoặc đọc các thuộc tính phản hồi không được ghi tài liệu:

```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>
  Các tham số `extra*` có cùng tên sẽ ghi đè lên các tham số đã được ghi tài liệu.
</Note>

## Tích hợp framework

### Laravel

Tạo một dịch vụ cho ứng dụng 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')
        );
    }
}
```

Thêm cấu hình vào `config/services.php`:

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

### Symfony

Tạo một dịch vụ trong 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
        );
    }
}
```

Đăng ký trong `config/services.yaml`:

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

## Tài nguyên

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    Xem mã nguồn và đóng góp
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Tài liệu API đầy đủ
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    Nhận trợ giúp và kết nối với các nhà phát triển
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-php/issues">
    Báo lỗi hoặc yêu cầu tính năng
  </Card>
</CardGroup>

## Hỗ trợ

Cần trợ giúp với SDK PHP?

* **Discord**: Tham gia [máy chủ cộng đồng](https://discord.gg/bYqAp4ayYh) của chúng tôi để được hỗ trợ theo thời gian thực
* **Email**: Liên hệ với chúng tôi qua [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: Mở issue trên [kho lưu trữ](https://github.com/dodopayments/dodopayments-php)

## Đóng góp

Chúng tôi hoan nghênh các đóng góp! Hãy xem [hướng dẫn đóng góp](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) để bắt đầu.

Chúng tôi hoan nghênh các đóng góp! Hãy xem [hướng dẫn đóng góp](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) để bắt đầu.
