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

> دمج مدفوعات دودي في تطبيقات PHP الخاصة بك باستخدام SDK حديث متوافق مع PSR-4

يوفر SDK PHP طريقة قوية ومرنة لدمج مدفوعات دودي في تطبيقات PHP الخاصة بك. تم بناؤه وفقًا لمعايير PHP الحديثة مع تحميل تلقائي متوافق مع PSR-4، ويقدم تغطية اختبار شاملة ووثائق مفصلة.

## التثبيت

قم بتثبيت SDK باستخدام Composer:

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

<Info>
  يتطلب SDK إصدار PHP 8.1.0 أو أعلى وComposer لإدارة التبعيات.
</Info>

## بداية سريعة

قم بتهيئة العميل وإنشاء جلسة دفع:

```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>
  خزّن مفاتيح API الخاصة بك بشكل آمن باستخدام متغيرات البيئة. لا تكشفها أبداً في
  قاعدة الشيفرة أو ترفعها إلى نظام التحكم في الإصدارات.
</Warning>

## الميزات الأساسية

<CardGroup cols={2}>
  <Card title="PSR-4 Compliant" icon="check">
    يتبع توصيات معايير PHP للتطوير الحديث بلغة PHP
  </Card>

  <Card title="Modern PHP" icon="php">
    مصمم لـ PHP 8.1+ بإعلانات الأنواع والأنواع الصارمة
  </Card>

  <Card title="Extensive Testing" icon="vial">
    تغطية اختبار شاملة للموثوقية والاستقرار
  </Card>

  <Card title="Exception Handling" icon="shield-check">
    أنواع استثناءات واضحة لسيناريوهات الأخطاء المختلفة
  </Card>
</CardGroup>

## كائنات القيمة

يستخدم SDK المعاملات المسماة لتحديد الوسائط الاختيارية. يمكنك تهيئة كائنات القيمة باستخدام الباني الساكن `with`:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

كما تتوفر البُناة كنهج بديل:

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

use Dodopayments\Customers\AttachExistingCustomer;

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

## التكوين

### تكوين إعادة المحاولة

يتم إعادة محاولة بعض الأخطاء تلقائياً مرتين افتراضياً مع تراجع أُسّي قصير. تقوم الأخطاء التالية بتشغيل إعادة المحاولة التلقائية:

* أخطاء الاتصال (مشاكل في الاتصال الشبكي)
* 408 انتهاء مهلة الطلب
* 409 تعارض
* 429 حد المعدل
* أخطاء داخلية 500+
* انتهاء المهلة

قم بتكوين سلوك إعادة المحاولة بشكل عام أو لكل طلب:

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

## العمليات الشائعة

### إنشاء جلسة دفع

أنشئ جلسة دفع:

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

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

### إدارة العملاء

أنشئ معلومات العملاء واسترجعها:

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

### التعامل مع الاشتراكات

أنشئ وادِر الاشتراكات المتكررة:

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

## الترميز

اعمل مع استجابات القوائم المقسمة إلى صفحات:

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

## التعامل مع الأخطاء

عندما لا يستطيع المكتبة الاتصال بواجهة برمجة التطبيقات أو يتلقى رمز حالة غير ناجح (4xx أو 5xx)، يتم رمي فئة فرعية من `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();
}
```

### أنواع الأخطاء

| السبب         | نوع الخطأ                      |
| ------------- | ------------------------------ |
| HTTP 400      | `BadRequestException`          |
| HTTP 401      | `AuthenticationException`      |
| HTTP 403      | `PermissionDeniedException`    |
| HTTP 404      | `NotFoundException`            |
| HTTP 409      | `ConflictException`            |
| HTTP 422      | `UnprocessableEntityException` |
| HTTP 429      | `RateLimitException`           |
| HTTP >= 500   | `InternalServerException`      |
| خطأ HTTP آخر  | `APIStatusException`           |
| انتهاء المهلة | `APITimeoutException`          |
| خطأ شبكة      | `APIConnectionException`       |

<Tip>
  احرص دائماً على تغليف استدعاءات واجهة برمجة التطبيقات في كتل try-catch لمعالجة الأخطاء المحتملة
  برشاقة وتوفير تغذية راجعة ذات معنى للمستخدمين.
</Tip>

## الاستخدام المتقدم

### نقاط نهاية غير موثقة

قم بإرسال طلبات إلى نقاط نهاية غير موثقة:

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

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

### معلمات غير موثقة

أرسل معلمات غير موثقة إلى أي نقطة نهاية أو اقرأ خصائص استجابة غير موثقة:

```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*` ذات الاسم نفسه تُلغي المعلمات الموثقة.
</Note>

## التكامل مع الأُطر

### Laravel

أنشئ خدمة لتطبيقات 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')
        );
    }
}
```

أضف التكوين في `config/services.php`:

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

### Symfony

أنشئ خدمة في 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
        );
    }
}
```

سجّل في `config/services.yaml`:

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

## الموارد

<CardGroup cols={2}>
  <Card title="GitHub Repository" icon="github" href="https://github.com/dodopayments/dodopayments-php">
    عرض شفرة المصدر والمساهمة
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    توثيق API كامل
  </Card>

  <Card title="Discord Community" icon="discord" href="https://discord.gg/bYqAp4ayYh">
    احصل على المساعدة وتواصل مع المطورين
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/dodopayments/dodopayments-php/issues">
    أبلغ عن الأخطاء أو اطلب ميزات
  </Card>
</CardGroup>

## الدعم

هل تحتاج مساعدة في SDK لـ PHP؟

* **Discord**: انضم إلى [خادم المجتمع](https://discord.gg/bYqAp4ayYh) للحصول على دعم فوري
* **البريد الإلكتروني**: تواصل معنا عبر [support@dodopayments.com](mailto:support@dodopayments.com)
* **GitHub**: افتح قضية في [المستودع](https://github.com/dodopayments/dodopayments-php)

## المساهمة

نرحب بالمساهمات! اطلع على [إرشادات المساهمة](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) للبدء.

نرحب بالمساهمات! اطلع على [إرشادات المساهمة](https://github.com/dodopayments/dodopayments-php/blob/main/CONTRIBUTING.md) للبدء.
