PHP如何区分Query String与JSON格式Webhook并分别处理?
Hey there, let's sort out your webhook handling logic properly. The core goal is to distinguish between query string-based requests and JSON payloads, then run the right code for each case. Here's a polished, working version of your code with the detection logic built in:
<?php date_default_timezone_set('America/Chicago'); // Grab raw input data $rawQuery = $_SERVER["QUERY_STRING"]; $rawJson = file_get_contents("php://input"); // Log the full request details (including headers) to webhook.log $date = new DateTime(); $headers = apache_request_headers(); $logEntry = sprintf("[%s]\n", $date->format('Y-m-d H:i:s')); $logEntry .= "Request Headers:\n"; foreach ($headers as $name => $value) { $logEntry .= " $name: $value\n"; } $logEntry .= "Query String: $rawQuery\n"; $logEntry .= "Raw JSON Payload: $rawJson\n"; $logEntry .= "-------------------------\n"; file_put_contents('webhook.log', $logEntry, FILE_APPEND); // Determine which request format we're dealing with $isQueryStringRequest = !empty($rawQuery); $isJsonRequest = !empty($rawJson) && json_decode($rawJson, true) !== null; // Handle query string requests if ($isQueryStringRequest) { parse_str($rawQuery, $queryData); // Add your query string-specific operations here // Example: process $queryData array echo "Processed query string request: " . print_r($queryData, true); } // Handle JSON requests elseif ($isJsonRequest) { $jsonData = json_decode($rawJson, true); // Add your JSON-specific operations here // Example: process $jsonData array echo "Processed JSON request: " . print_r($jsonData, true); } // Fallback for invalid/unexpected requests else { http_response_code(400); echo "Error: Unsupported request format"; } ?>
Key Details Explained:
- Request Detection:
- We check if the query string has content (
$isQueryStringRequest) to catch that webhook. - For JSON, we verify the raw input isn't empty and that it can be parsed into valid JSON (
$isJsonRequest).
- We check if the query string has content (
- Logging: Expanded the log to include headers, query string, and raw JSON so you can debug exactly what each webhook is sending.
- Parsing:
parse_str()converts the query string into a usable associative array.json_decode($rawJson, true)turns the JSON payload into an associative array (remove thetrueif you prefer an object).
- Fallback: Added a 400 Bad Request response for cases where neither format matches—this helps catch unexpected requests during testing.
If you need to adjust the priority (e.g., if a request could technically have both a query string and JSON), just reorder the conditionals. But based on your description, this should cover your two server scenarios perfectly.
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

