Chuyển đến nội dung chính
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:
composer require "dodopayments/client 5.8.1"
SDK yêu cầu PHP 8.1.0 trở lên và Composer để quản lý phụ thuộc.

Bắt đầu nhanh

Khởi tạo client và tạo phiên thanh toán:
<?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);
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.

Tính năng chính

PSR-4 Compliant

Tuân theo khuyến nghị chuẩn PHP cho phát triển PHP hiện đại

Modern PHP

Xây dựng cho PHP 8.1+ với khai báo kiểu và strict types

Extensive Testing

Bao phủ kiểm thử toàn diện để đảm bảo độ tin cậy và ổn định

Exception Handling

Các loại ngoại lệ rõ ràng cho các tình huống lỗi khác nhau

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

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

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

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:
$session = $client->checkoutSessions->create(
  productCart: [
    ["productID" => "prod_123", "quantity" => 1]
  ],
  returnUrl: "https://yourdomain.com/return"
);

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

Quản lý khách hàng

Tạo và lấy thông tin khách hàng:
// 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ỳ:
// 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:
$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

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ânLoại lỗi
HTTP 400BadRequestException
HTTP 401AuthenticationException
HTTP 403PermissionDeniedException
HTTP 404NotFoundException
HTTP 409ConflictException
HTTP 422UnprocessableEntityException
HTTP 429RateLimitException
HTTP >= 500InternalServerException
Other HTTP errorAPIStatusException
Hết thời gian chờAPITimeoutException
Lỗi mạngAPIConnectionException
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.

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

$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

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

Tích hợp framework

Laravel

Tạo một dịch vụ cho ứng dụng Laravel:
<?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:
'dodo' => [
    'api_key' => env('DODO_API_KEY'),
    'environment' => env('DODO_ENVIRONMENT', 'sandbox')
],

Symfony

Tạo một dịch vụ trong Symfony:
<?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:
services:
  App\Service\DodoPaymentService:
    arguments:
      $apiKey: "%env(DODO_API_KEY)%"

Tài nguyên

Hỗ trợ

Cần trợ giúp với SDK 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 để bắt đầu.