在PHP中处理Webhook异常情况,可以通过以下几种方法:
function is_valid_origin($origin) {
// 允许的域名列表
$allowed_origins = ['https://example.com', 'https://www.example.com'];
return in_array($origin, $allowed_origins);
}
if ($_SERVER['HTTP_ORIGIN'] !== 'https://example.com') {
header('HTTP/1.1 403 Forbidden');
exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('HTTP/1.1 405 Method Not Allowed');
exit;
}
$request_data = file_get_contents('php://input');
$data = json_decode($request_data, true);
// 使用JSON Schema验证数据
$schema = [
'type' => 'object',
'properties' => [
'key' => ['type' => 'string'],
'value' => ['type' => 'string'],
],
];
$validator = new JsonSchema\Validator();
if (!$validator->validate($data, $schema)) {
header('HTTP/1.1 400 Bad Request');
exit;
}
try {
// 处理Webhook数据的逻辑
} catch (Exception $e) {
// 记录错误日志
error_log($e->getMessage());
// 返回错误信息
header('HTTP/1.1 500 Internal Server Error');
echo 'An error occurred while processing the webhook data.';
exit;
}
header('HTTP/1.1 200 OK');
echo 'Webhook received and processed successfully.';
通过以上方法,可以有效地处理PHP Webhook中的异常情况,确保系统的稳定性和安全性。