تكامل لغة PHP

ربط واتساب API بلغة PHP — كود إرسال رسائل و OTP عبر WhatsApp

أكواد جاهزة ونظيفة للربط بلغة PHP 8.x دون الحاجة لمكتبات معقدة. إرسال مباشر باستخدام cURL المدمج أو حزمة Guzzle مع معالجة توقيع Webhooks وضمان عدم تكرار الإرسال.

💡 معايير بيئة العمل والتشغيل في EzyCode Connect

  • عنوان الخدمة المعتمد: https://connect-dashboard.ezycode.dev/connect/v1
  • نظام التسعير: 0.009$ لكل رسالة تحقق (OTP) بدون اشتراكات أو رسوم شهرية خفية.
  • بيئة Sandbox: تدعم حتى 5 أرقام مستلمين تجريبيين مسجلين في حسابك لاختبار الكود قبل الإطلاق.

1. كود الإرسال باستخدام cURL الأصلي (بدون Composer)

<?php
/**
 * EzyCode Connect - Native PHP cURL WhatsApp OTP Dispatcher
 */
function sendWhatsAppOtp(string $phone, string $code, string $apiKey): array
{
    $url = 'https://connect-dashboard.ezycode.dev/connect/v1/messages';
    
    $payload = [
        'to'   => $phone,
        'type' => 'text',
        'text' => "رمز التحقق الخاص بك هو: {$code}. صالح لمدة 5 دقائق.",
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
            'Accept: application/json',
            'Idempotency-Key: ' . bin2hex(random_bytes(16)),
        ],
    ]);

    $raw = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlErr  = curl_error($ch);
    curl_close($ch);

    if ($curlErr) {
        return ['success' => false, 'error' => "cURL Error: {$curlErr}"];
    }

    $response = json_decode($raw, true);

    if ($httpCode >= 200 && $httpCode < 300 && isset($response['data']['id'])) {
        return [
            'success'    => true,
            'message_id' => $response['data']['id'],
            'status'     => $response['data']['status'] ?? 'queued',
        ];
    }

    return [
        'success'   => false,
        'http_code' => $httpCode,
        'error'     => $response['message'] ?? 'Unknown dispatch failure',
    ];
}

// Example usage:
$apiKey = 'ezk_live_xxxxxxxxxxxxxxxxxxxx';
$result = sendWhatsAppOtp('+201000000000', '581920', $apiKey);

if ($result['success']) {
    echo "Message sent successfully! ID: " . $result['message_id'];
} else {
    echo "Failed to send: " . $result['error'];
}

2. الإرسال باستخدام مكتبة Guzzle

<?php
require 'vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

$client = new Client([
    'base_uri' => 'https://connect-dashboard.ezycode.dev/connect/v1/',
    'timeout'  => 10.0,
]);

try {
    $response = $client->post('messages', [
        'headers' => [
            'Authorization'   => 'Bearer ezk_live_xxxxxxxxxxxxxxxxxxxx',
            'Idempotency-Key' => 'req_' . uniqid(),
            'Content-Type'    => 'application/json',
            'Accept'          => 'application/json',
        ],
        'json' => [
            'to'   => '+201000000000',
            'type' => 'text',
            'text' => 'رمز الدخول السريع: 419203',
        ],
    ]);

    $body = json_decode($response->getBody()->getContents(), true);
    print_r($body['data']);
} catch (GuzzleException $e) {
    echo "Request Error: " . $e->getMessage();
}

3. معالج Webhook للتحقق من وصول الرسالة

<?php
/**
 * webhook.php - Receive EzyCode delivery receipts securely
 */
$secret = 'whsec_xxxxxxxxxxxxxxxxxxxx';
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_EZYCODE_SIGNATURE'] ?? '';

// Verify HMAC-SHA256 signature
$expected = hash_hmac('sha256', $payload, $secret);

if (!hash_equals($expected, $signature)) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid signature']);
    exit;
}

$data = json_decode($payload, true);
$event = $data['event'] ?? '';
$messageId = $data['data']['message_id'] ?? null;
$status = $data['data']['status'] ?? null; // delivered, read, failed

// Update your MySQL or database record
// DB::query("UPDATE messages SET status = ? WHERE provider_id = ?", [$status, $messageId]);

http_response_code(200);
echo json_encode(['status' => 'received']);

الأسئلة المتكررة لمطوري PHP

هل يتطلب الكود إصداراً معيناً من PHP؟

الكود متوافق تماماً مع PHP 7.4 و 8.0 و 8.1 و 8.2 و 8.3 بدون أي مشاكل، ويعتمد فقط على دالة cURL القياسية.

كيف أمنع الهجمات وإرسال رسائل غير مرغوبة؟

يُنصح بوضع Rate Limiting على مستوى عنوان الـ IP ورقم الهاتف (مثلاً بحد أقصى 3 محاولات كل 10 دقائق)، واستخدام ترويسة Idempotency-Key مع كل طلب.

ابدأ في إرسال رسائل واتساب من تطبيقك الآن

احصل على مفتاح الـ API المجاني وابدأ الإرسال فوراً بأقل كود ممكن وبأعلى موثوقية.