Creating a custom webhook in WordPress to get data from third part services

In this 2 min blog I will explain how easy it is to setup a webhook url and get data from any external service into your WordPress. šŸ˜‰

Creating a custom webhook in WordPress to get data from third part services

Subscribe to my newsletter and never miss my upcoming articles

Before setting up a webhook lets understand what a webhook is.

A webhook (also called a web callback or HTTP push API) is a way for an app to provide other applications with real-time information.

In simpler terms, they are a great way for applications to speak to each other.

For example : You have a form which you have created on typeform, and you would like to do something on your website when the form is submitted. You can use webhook to achieve this. Typeform supports webhook.

You have to add a webhook URL in your typeform form. When someone fills up the form typeform will send the data to the URL which you have entered. To recieve that data you have to setup a webhook on your wordpress website and get that data.

Setting up Webhook

We will use do_action( "admin_post_nopriv_{$action}" ) provided by wordpress . This action "fires on a non-authenticated admin post request for the given action."

add_action('admin_post_nopriv_get_typeform_data',  'process_data_form_tyepform_webhook', 10);

Here, the action name is get_typeform_data. Which means your webhook url will be

https://yourwebsite.com/wp-admin/admin-post.php?action=get_typeform_data

Processing Incoming data

Now we will define a function which would accept the data and process it.

function process_data_form_tyepform_webhook() {

   $request = file_get_contents('php://input'); // get data from webhoook

   $data = json_decode($request, true); // decode the data is you are getting data in JSON format
   // log it in debug.log
  error_log( $request );
}

Here we have used file_get_contents to store the value in the variable. Most of the time the data you will get is in the form of json, so we have decoded the data and logged it. ( Make sure your debugging is set to true. )

Now you can use the $data variable and process in any way you like. Create a post, create a user etc.

Caveat

When testing your funtionality make sure that you are not using your local development environment. You must have hosted your website somewhere it can be visited by other server. If you are interested in testing it locally you should look into ngrok.com.

I hope you enjoyed reading this blog, as much as I enjoyed writing it. šŸ˜Š

Let me know if you have any question below in the comment and I will try my best to answer them.

Ā 
Share this
Proudly part of