ทักคับ นักพัฒนา

ตัวอย่างโค้ด

PHP

รับ Webhook และตอบข้อความแบบง่าย ไม่ใช้ไลบรารีเสริม งาน AI ที่ใช้เวลานานควรส่งเข้าคิวแยก

webhook.php
<?php
$secret = getenv('TAKKUB_WEBHOOK_SECRET');
$key = getenv('TAKKUB_API_KEY');
$raw = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_TAKKUB_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_TAKKUB_SIGNATURE'] ?? '';

$expected = 'v1=' . hash_hmac('sha256', $timestamp . '.' . $raw, $secret);
if (abs(time() - (int) $timestamp) > 300 || !hash_equals($expected, $signature)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw, true);
if ($event['event'] === 'message.received') {
    $url = 'https://office.takkub.com/api/v1/threads/' . $event['thread']['id'] . '/messages';
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer $key", 'Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode([
            'text' => 'ได้รับข้อความแล้ว เดี๋ยวทีมงานรีบตอบนะคะ',
            'client_id' => 'ack-' . $event['id'],
        ]),
    ]);
    curl_exec($ch);
}
http_response_code(200);