Files
2026-09-05 15:54:33 +03:30

61 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Eitaa;
use App\Http\HttpException;
final class Client
{
public function __construct(private readonly string $token)
{
}
public function verify(string $hash, ?string $ip): void
{
$payload = ['hash' => $hash];
if ($ip !== null) {
$payload['ip'] = $ip;
}
$this->post('verify', $payload);
}
public function sendMessage(string $userId, string $text): void
{
$result = $this->post('sendMessage', ['chat_id' => $userId, 'text' => $text]);
if (($result['result'] ?? null) !== 'success') {
throw new HttpException('ارسال پیام توسط ایتایار تأیید نشد.', 502);
}
}
private function post(string $method, array $payload): array
{
if (!extension_loaded('curl')) {
throw new HttpException('افزونهٔ cURL در تنظیمات PHP هاست فعال نیست.', 503);
}
// Only the two public methods select endpoints. Credentials stay in TLS POST bodies.
$curl = curl_init('https://eitaayar.ir/api/app/' . $method);
curl_setopt_array($curl, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query(['token' => $this->token] + $payload),
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 12,
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/x-www-form-urlencoded'],
]);
$raw = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($raw === false || $status !== 200 || strlen($raw) > 65536) {
throw new HttpException('پاسخ معتبر از ایتایار دریافت نشد. بعداً تلاش کنید.', 502);
}
$data = json_decode($raw, true);
if (!is_array($data) || ($data['ok'] ?? false) !== true) {
throw new HttpException($method === 'verify'
? 'اصالت تأیید نشد؛ مهلت یک دقیقه‌ای یا محدودیت یک بار مصرف را بررسی کنید.'
: 'ارسال انجام نشد؛ مجوز پیام و اعتبار برنامه را در ایتایار بررسی کنید.', 422);
}
return $data;
}
}