# Handling Webhook Events

### Handling Events (Node.js)

The below example illustrates how to securely handle webhook events within your own applications. Each webhook call from the API includes a secure `X-Terminal-Signature` which is generated using your `SECRET_KEY`. To ensure integrity of each request you receive, you can complete a simple verification task as shown in the example below:

```
const crypto = require('crypto');
const SECRET_KEY = ""; //Your secret key

// Handle webhook event 
const handleEvent = (req, res) => {
	try{
		res.sendStatus(200);
		let webhook_signature = req.headers['X-Terminal-Signature']; //retrieve the request signature
		let {body} = req; // Retrieve the request's body
		let request_validation = verifyWebhookRequest(webhook_signature, SECRET_KEY, body); //Validate webhook request
		
		if(request_validation.status){
			let {data, event} = body; //retrieve event type and data payload
			switch(event){
				case "shipment.created":
					//Handle successful shipment creation event
				break;
				case "address.updated":
					//Handle successful address update event
				break;
				default:
					//Handle unknown event received
			}		
		}else{
			//request is not valid API webhook
		}
	}catch(e){
		console.log("Error occurred - %O", e)
	}
}

/**
* Verifies validity of webhook request.
* @params - signature - Signature hash received via webhook.
* @params - secret_key - API secret key.
* @params - body - Request payload received via webhook.
*/
const verifyWebhookRequest = (signature, secret_key, body={}) => {
	try{
		let manual_hash_signature = crypto.createHmac('sha512', secret_key).update(JSON.stringify(body)).digest('hex'); //regenerate hash using secret key and webhook payload
		let request_valid = (signature === manual_hash_signature); //verify signature from webhook matches manual hash
		let valid_message = (request_valid) ? "Webhook request is valid" : "Invalid webhook request received";
		
		return {
			status: request_valid,
			message: valid_message
		}		
	}catch(e){
		console.log("An error occurred %O", e);
		return {
			status: false,
			message: "Unable to verify request"
		}		
	}
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.terminal.africa/tship/miscallaneous/webhook-events/handling-webhook-events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
