Help > Forum > Website Integration > Sample code for receiving a webhook event
Sample code for receiving a webhook event
To create a webhook URL that receives a JSON payload, you need to set up a server and route that can handle the incoming HTTP POST request containing the JSON event data. This involves choosing a programming language and web framework, defining the route on your server that will handle the incoming request, and using a unique URL path for this route. Once you have set up the server and route, you can start your server and test the route by sending a test request with a sample JSON payload. Once you have confirmed that your server is receiving and processing the webhook events correctly, you can save the webhook URL in your forum settings, and it will start sending the events to this URL whenever a relevant event occurs.
In this code, we are using the Sinatra web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
require 'sinatra'
require 'json'
post '/webhook' do
request_body = request.body.read
request_data = JSON.parse(request_body)
if request_data['type'] === 'post.created'
# Do something with the webhook request data
puts request_data['id']
end
status 200
end
In this code, we are using the Flask web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
import json
from flask import Flask, request
app = Flask(__name__)
@app.route('/webhook', methods=['POST'])
def webhook():
request_body = request.get_data()
request_data = json.loads(request_body)
if request_data['type'] == 'post.created':
# Do something with the webhook request data
print(request_data['id'])
# Return a 200 HTTP status code
return '', 200
<?php
$requestBody = file_get_contents('php://input');
$requestData = json_decode($requestBody, true);
if ($requestData['type'] === 'post.created') {
// Do something with the webhook request data
echo $requestData['id'];
}
http_response_code(200);
?>
In this code, we are using the Jersey web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/webhook")
public class Webhook {
@POST
public Response webhook(String requestBody) {
JSONObject requestData = new JSONObject(requestBody);
if (requestData.getString("type").equals("post.created")) {
// Do something with the webhook request data
System.out.println(requestData.getString("id"));
}
// Return a 200 HTTP status code
return Response.ok().build();
}
}
In this code, we are using the Express web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
const express = require('express');
const app = express();
app.post('/webhook', (req, res) => {
const requestBody = req.body;
const requestData = JSON.parse(requestBody);
if (requestData.type === 'post.created') {
// Do something with the webhook request data
console.log(requestData.id);
}
// Return a 200 HTTP status code
res.sendStatus(200);
});
app.listen(8000, () => console.log('Running on port 8000'));
In this code, we are using the Gorilla web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.HandleFunc("/webhook", webhookHandler).Methods("POST")
http.ListenAndServe(":3000", router)
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
// Read the request body
requestBody, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
// Parse the request body as JSON
var requestData map[string]interface{}
if err := json.Unmarshal(requestBody, &requestData); err != nil {
panic(err)
}
if requestData["type"] == "post.created" {
// Do something with the webhook request data
fmt.Println(requestData["id"])
}
// Return a 200 HTTP status code
w.WriteHeader(http.StatusOK)
}
In this code, we are using the ASP.NET Core web framework to create a route that can handle the incoming HTTP POST request containing the JSON event data. The route extracts the JSON payload from the request and processes it as needed, then returns a 200 HTTP status code to indicate that the event was received and processed successfully.
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace Webhook.Controllers
{
[Route("api/[controller]")]
public class WebhookController : Controller
{
[HttpPost]
public IActionResult Webhook()
{
// Read the request body
string requestBody = Request.InputStream.ReadToEnd();
// Parse the request body as JSON
dynamic requestData = JObject.Parse(requestBody);
if (requestData.type == "post.created")
{
// Do something with the webhook request data
Console.WriteLine(requestData.id);
}
// Return a 200 HTTP status code
return new HttpStatusCodeResult(200);
}
}
}
If you still need help, please contact us.