<?php
header('Content-Type: application/json');
// Enable error logging
error_reporting(E_ALL);
ini_set('log_errors', 1);
ini_set('error_log', 'callback_errors.log');
try {
// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if (!$data) {
http_response_code(400);
echo json_encode(['code' => 400, 'msg' => 'Invalid JSON payload']);
exit;
}
$code = $data['code'] ?? null;
$msg = $data['msg'] ?? '';
$callbackData = $data['data'] ?? [];
$taskId = $callbackData['task_id'] ?? null;
error_log("Received callback for task: " . $taskId);
if ($code === 200) {
// Success - video generated
$videoUrl = $callbackData['video_url'] ?? '';
$imageUrl = $callbackData['image_url'] ?? '';
$videoId = $callbackData['video_id'] ?? '';
error_log("Video generated successfully: " . $videoUrl);
handleSuccessfulGeneration($taskId, $videoUrl, $imageUrl, $videoId);
} else {
// Error occurred
error_log("Generation failed for task $taskId: " . $msg);
handleGenerationError($taskId, $msg);
}
// Always return 200 to acknowledge receipt
http_response_code(200);
echo json_encode(['code' => 200, 'msg' => 'Callback received successfully']);
} catch (Exception $e) {
error_log("Error processing callback: " . $e->getMessage());
http_response_code(500);
echo json_encode(['code' => 500, 'msg' => 'Error processing callback']);
}
function handleSuccessfulGeneration($taskId, $videoUrl, $imageUrl, $videoId) {
try {
// Update database
updateTaskStatus($taskId, 'completed', [
'video_url' => $videoUrl,
'image_url' => $imageUrl,
'video_id' => $videoId,
'completed_at' => date('Y-m-d H:i:s')
]);
// Send notification
notifyUser($taskId, 'Your Aleph video is ready!');
} catch (Exception $e) {
error_log("Error handling successful generation: " . $e->getMessage());
}
}
function handleGenerationError($taskId, $errorMessage) {
try {
// Update database
updateTaskStatus($taskId, 'failed', [
'error_message' => $errorMessage,
'failed_at' => date('Y-m-d H:i:s')
]);
// Send notification
notifyUser($taskId, "Video generation failed: $errorMessage");
} catch (Exception $e) {
error_log("Error handling generation error: " . $e->getMessage());
}
}
function updateTaskStatus($taskId, $status, $additionalData = []) {
// Implement your database update logic here
error_log("Updating task $taskId status to $status");
// Example using PDO:
/*
$pdo = new PDO($dsn, $username, $password);
$stmt = $pdo->prepare("UPDATE tasks SET status = ?, updated_at = NOW() WHERE task_id = ?");
$stmt->execute([$status, $taskId]);
*/
}
function notifyUser($taskId, $message) {
// Implement your notification logic here
error_log("Notifying user for task $taskId: $message");
// Example: Send email, push notification, etc.
}
?>