Monday, 22 September 2025

Webhook

1️⃣ What Is a Webhook?

A webhook is an automatic HTTP callback from one application to another.

  • Think of it like a doorbell:

    • You don’t keep checking if someone is outside.

    • Instead, the doorbell (webhook) notifies you immediately.

In software terms:

  • App A sends an HTTP POST request to a URL you provide whenever a specific event happens.

  • Your app receives the data instantly, without polling.


2️⃣ Real-Life Examples

  • Payment Gateway: Stripe or PayPal sends a webhook when a payment succeeds.

  • GitHub: Sends a webhook when someone pushes code to a repository.

  • Chat Apps: Slack sends a webhook when a new message arrives.


3️⃣ How It Works (Simple Flow)

Event Happens in Service A | Service A sends HTTP POST (JSON) | Your Webhook Endpoint (Service B) | You process the data

Steps:

  1. You give Service A a URL (e.g., https://yourapp.com/webhook/order).

  2. Service A triggers an event (e.g., order created).

  3. It sends a POST request with a JSON payload to your URL.

  4. Your server reads it and takes action (update DB, send email, etc.).


4️⃣ Creating a Webhook Receiver in .NET

Here’s a minimal ASP.NET Core example:

[ApiController] [Route("webhook")] public class WebhookController : ControllerBase { [HttpPost("order")] public async Task<IActionResult> Receive([FromBody] OrderEvent payload) { // Process the incoming event // e.g., save to database, trigger another service Console.WriteLine($"Order received: {payload.OrderId}"); return Ok(); // Reply 200 so sender knows you got it } } public class OrderEvent { public string OrderId { get; set; } public decimal Amount { get; set; } }

Steps to use:

  1. Deploy your app so it has a public HTTPS endpoint.

  2. Give that URL to the service sending the webhook.

  3. Test with a tool like ngrok (to expose local development) or Postman.


5️⃣ Sending a Webhook (If Your App Triggers One)

If you want to notify others:

using var http = new HttpClient(); await http.PostAsJsonAsync("https://partner.com/webhook/receive", new { OrderId = 123, Amount = 99.99M });

6️⃣ Best Practices

  • Security: Verify signatures or use a secret token to ensure the request is genuine.

  • Retry/Idempotency: Handle duplicate messages—sender may retry if it doesn’t get a 200 OK.

  • Logging: Log every received event for debugging.

  • Timeouts: Reply quickly; heavy work should be queued or processed asynchronously.


7️⃣ Quick Recap

  • Webhook = “We push data to you when something happens.”

  • Sender: service that triggers the event.

  • Receiver: your endpoint that processes the POST request.

  • Great for real-time updates without constant polling.

In .NET, it’s just an ASP.NET Core controller action that accepts an HTTP POST with JSON.