本地环境中WooCommerce Webhook失效,PHP代码获取数据异常
Fixing Empty
php://input & Data Access Issues with WooCommerce Webhooks Hey there, let's walk through why you're hitting this problem and how to fix it. I've dealt with similar WooCommerce webhook headaches before, so here's what's going on:
First, Why is $post_data Empty?
A blank string(0) from file_get_contents("php://input") usually comes down to one of these common issues:
- You already read the POST data elsewhere: If your script (or any plugin/function running before it) uses
$_POSTor$_REQUEST, PHP will consume thephp://inputstream, leaving it empty. - Server configuration limits: Check your
php.inisettings—post_max_sizemight be too small for the webhook payload, orallow_url_fopencould be disabled (though this is less likely forphp://input). - WooCommerce Webhook misconfiguration: Double-check that your webhook is set to send a POST request with a JSON payload (not form data) to the correct URL.
Second, Your Code Has a Critical Mistake
You're trying to access $post_data->id directly, but file_get_contents("php://input") returns a raw JSON string—not an object. You need to decode it first!
Fixed Code Example
Here's a revised, robust version of your script that addresses both issues:
// Ensure we're handling a POST request if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit('Method Not Allowed'); } // Grab raw POST data (avoid using $_POST before this!) $post_data = file_get_contents("php://input"); // Debug: Check if we actually got data if (empty($post_data)) { // Print request details to diagnose echo "Content-Type: " . $_SERVER['CONTENT_TYPE'] . "<br>"; echo "Content-Length: " . $_SERVER['CONTENT_LENGTH'] . "<br>"; exit('No POST payload received. Check server or webhook settings.'); } // Decode JSON into an object (use true as second arg for array) $webhook_payload = json_decode($post_data); // Validate JSON parsing if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); exit('Invalid JSON: ' . json_last_error_msg()); } // Safely access the ID if (isset($webhook_payload->id)) { $id = (int) filter_var($webhook_payload->id, FILTER_SANITIZE_NUMBER_INT); var_dump($id); // Should now show the correct ID! } else { exit('"id" field not found in webhook payload.'); }
Additional Troubleshooting Steps
- Test with Postman: Send a manual POST request to your script with a sample JSON payload (like
{"id": 123}) to confirm your script works outside WooCommerce. - Check WooCommerce Webhook Logs: Go to WooCommerce > Status > Logs, filter for webhook logs, and see if there are delivery errors (e.g., 404, 500 responses from your script).
- Verify Webhook Signature (Optional but Recommended): To ensure the request is actually from WooCommerce, use the webhook secret to validate the
X-WC-Webhook-Signatureheader. This prevents fake requests from hitting your script.
内容的提问来源于stack exchange,提问作者user13575758
相关产品推荐
相关产品推荐

