35274-vm/webhook_receiver.php
Flatlogic Bot d2f005da56 nu norm
2025-10-27 13:55:31 +00:00

83 lines
2.6 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
header('Content-Type: application/json');
// --- Security Check ---
$provided_token = $_GET['token'] ?? null;
if (!$provided_token) {
http_response_code(401);
echo json_encode(['status' => 'error', 'message' => 'Security token not provided.']);
exit;
}
$pdo = db();
$stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'webhook_token'");
$stmt->execute();
$correct_token = $stmt->fetchColumn();
if (!$correct_token || !hash_equals($correct_token, $provided_token)) {
http_response_code(403);
echo json_encode(['status' => 'error', 'message' => 'Invalid security token.']);
exit;
}
// --- Payload Processing ---
$raw_payload = file_get_contents('php://input');
$payload = json_decode($raw_payload, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Invalid JSON payload.']);
exit;
}
// --- Data Validation ---
$post_id = $payload['post_id'] ?? null;
$status = $payload['status'] ?? null; // e.g., 'success', 'error', 'published', 'failed'
$message = $payload['message'] ?? 'No message provided.';
if (!$post_id || !$status) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Required fields \'post_id\' and \'status\' are missing.']);
exit;
}
// --- Database Update ---
try {
$pdo->beginTransaction();
// 1. Log the incoming event
$log_stmt = $pdo->prepare(
"INSERT INTO webhook_events (post_id, status, message, raw_payload) VALUES (?, ?, ?, ?)"
);
$log_stmt->execute([$post_id, $status, $message, $raw_payload]);
// 2. Update the status of the scheduled post
// We map various possible statuses to a simplified set for our internal state.
$internal_status = 'pending';
if (in_array($status, ['success', 'published'])) {
$internal_status = 'published';
} elseif (in_array($status, ['error', 'failed'])) {
$internal_status = 'failed';
}
if ($internal_status !== 'pending') {
$update_stmt = $pdo->prepare("UPDATE scheduled_posts SET status = ? WHERE id = ?");
$update_stmt->execute([$internal_status, $post_id]);
}
$pdo->commit();
echo json_encode(['status' => 'success', 'message' => 'Webhook processed and status updated.']);
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
http_response_code(500);
// In a real app, you would log this error to a file instead of echoing it.
echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}