Fix WooCommerce webhook loop when using WooCommerce API
Problem (Quick)
Updating a product via the WooCommerce API would fire an update webhook, causing a loop of webhook and API activity which never ended.
Problem
Created a script which keeps stock levels synced between WooCommerce and a stock management system, WooCommerce WebHooks are used to set products stock levels in near real time. Using WooCommerce API new stock levels are pushed to WooCommerce, however with each API push this would trigger a product updated webhook, causing my script to reinforce the stock levels via API (causing an unlimited updating loop).
Solution
We can use woocommerce_webhook_should_deliver filter to control if a webhook should be delivered.
The following example shows how I used the clients IP address (in this example my scripts server) to stop webhook delivery for any requests from that IP address, this allows my script to use the API and webhooks will never be delivered.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function custom_woocommerce_webhook_should_deliver($shouldDeliver, $webhookObject, $arg) { // Is this a REST request? if (defined('REST_REQUEST') && REST_REQUEST) { // Determine IP address if (!empty($_SERVER['HTTP_CLIENT_IP'])) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } if ($ip == '123.123.123.123') { $shouldDeliver = false; } } return $shouldDeliver; } add_filter('woocommerce_webhook_should_deliver', 'custom_woocommerce_webhook_should_deliver', 10, 3); |
Adrià Roca
Thank you! I had an infinite loop because my backend updates the order metadata when an order is updated, and that triggers the order.updated again. Hooking woocommerce_webhook_should_deliver as described in the example allowed me to prevent it.