WooCommerce delayed webhooks using actions scheduler
Recently been contacted by a user who needed the ability to delay the WooCommerce webhooks by x time, this would allow other processes happening on the site to finish instead of firing the webhook straight away, for example waiting for the payment process to finalise. Delaying webhooks is not common practice, however some time special case arises!
Take a look at actions scheduler if you wish to read more into the scheduler system used by WooCommerce.
Code
The following code allows you to delay several WooCommerces webhooks by a set duration (seconds) and also run in two modes.
- Single Webhook, creates 1 single webhook but delayed by x seconds.
- Multi Webhook, creates 2 webhooks, the normal webhook created by WooCommerce and a second repeat webhook which runs x seconds later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function filter_woocommerce_webhook_deliver_async($true, $instance, $arg) { // Replace default schedule action? (single web hook fired, with delay) // Or schedule a seperate delayed action (default webhook fied with a second delayed web hook) $singleWebhook = false; // Target webhook topics $targetWebhookTopics = [ 'order.updated', ]; // Delay time in seconds $delayTime = 300; // If order.update, we want to create a seperate delayed webhook via schedule actions if (in_array($instance->get_topic(), $targetWebhookTopics)) { $payload = ['webhook_id' => $instance->get_id(), arg => $arg]; $group = $singleWebhook ? 'woocommerce-webhooks' : 'woocommerce-webhooks-delayed'; // Schedule a single action to run in 5 minutes, to cause the order.update to fire (delayed) // Make sure to run as_next_scheduled_action so multiple instances are not scheduled if one is already scheduled if (as_next_scheduled_action('woocommerce_deliver_webhook_async', $payload, $group) === false) { as_schedule_single_action(time() + $delayTime, 'woocommerce_deliver_webhook_async', $payload, $group); } } return $true; }; add_filter('woocommerce_webhook_deliver_async', 'filter_woocommerce_webhook_deliver_async', 10, 3); |
This code is provided as it and may require changes to work for your needs.
Lekkerhoning.nl
Works like a charm!
Thank you so much, you helped to resolve the problem i was struggling for 3 years now 😀
Shane Rutter
Glad it worked for you!