نمونه اتصال REST API با PHP

نمونه عملی اتصال PHP و Laravel به REST API اینپی فای، مدیریت پاسخ و خطا و نگهداری امن کلید API.

PHP با cURL

تابع زیر برای متدهای GET، POST و DELETE قابل‌استفاده است:

<?php

function inAppifyRequest(
    string $method,
    string $path,
    ?array $payload = null,
    array $extraHeaders = [],
): array {
    $baseUrl = rtrim(getenv('INAPPIFY_API_URL'), '/');
    $apiKey = getenv('INAPPIFY_SECRET_API_KEY');
    $curl = curl_init($baseUrl.'/api/v1/'.$path);

    $headers = array_merge([
        'Authorization: Bearer '.$apiKey,
        'Accept: application/json',
        'Content-Type: application/json',
    ], $extraHeaders);

    curl_setopt_array($curl, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
        CURLOPT_HTTPHEADER => $headers,
    ]);

    if ($payload !== null) {
        curl_setopt(
            $curl,
            CURLOPT_POSTFIELDS,
            json_encode($payload, JSON_THROW_ON_ERROR),
        );
    }

    $body = curl_exec($curl);
    $statusCode = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);

    if ($body === false) {
        $message = curl_error($curl);
        curl_close($curl);
        throw new RuntimeException('InAppify connection failed: '.$message);
    }

    curl_close($curl);
    $data = json_decode($body, true, flags: JSON_THROW_ON_ERROR);

    if ($statusCode < 200 || $statusCode >= 300) {
        throw new RuntimeException(
            'InAppify API error '.$statusCode.': '.($data['message'] ?? $body),
        );
    }

    return $data;
}

دریافت مشتری

$customer = inAppifyRequest(
    'GET',
    'subscribers/'.rawurlencode('customer_123'),
);

$hasPremiumAccess = collect($customer['data']['entitlements'])
    ->contains(fn (array $item) =>
        $item['identifier'] === 'premium' && $item['isActive'] === true
    );

ثبت ویژگی مشتری

$result = inAppifyRequest(
    'POST',
    'subscribers/'.rawurlencode('customer_123').'/attributes',
    [
        'attributes' => [
            ['key' => 'plan', 'value' => 'pro'],
            ['key' => 'language', 'value' => 'fa'],
        ],
    ],
);

دریافت پیشنهادهای اپلیکیشن

$offerings = inAppifyRequest(
    'GET',
    'subscribers/'.rawurlencode('customer_123').'/offerings',
    extraHeaders: ['X-InAppify-App-ID: android_app'],
);

Laravel HTTP Client

use Illuminate\Support\Facades\Http;

$response = Http::baseUrl(config('services.inappify.url').'/api/v1')
    ->withToken(config('services.inappify.secret'))
    ->acceptJson()
    ->timeout(15)
    ->retry(3, 500, throw: false)
    ->get('/subscribers/customer_123');

if ($response->failed()) {
    report('InAppify request failed', [
        'status' => $response->status(),
        'message' => $response->json('message'),
    ]);
}

$customer = $response->throw()->json('data');

کلید را در .env سرور نگه دارید و فقط نام متغیر را در .env.example ثبت کنید:

INAPPIFY_API_URL=https://api.example.com
INAPPIFY_SECRET_API_KEY=YOUR_SECRET_API_KEY

برای 401، 403 و 422 retry خودکار نکنید. retry را به خطاهای اتصال، 429 و خطاهای موقت 5xx محدود کنید.