Search code examples
c#.netwebhooksuber-api

How to get webhook response data in .NET 6


I've created an endpoint in my API than I'm going to use to use the webhook of Uber. It is my first time working with webhook, so: How I'm going to get the response they will give me by using my endpoint?

Here what they will send to me (the data below are for test):

{
    "event_type": "orders.notification",
    "event_id": "c4d2261e-2779-4eb6-beb0-cb41235c751e",
    "event_time": 1427343990,
    "meta": {
        "resource_id": "153dd7f1-339d-4619-940c-418943c14636",
        "status": "pos",
        "user_id": "89dd9741-66b5-4bb4-b216-a813f3b21b4f"
    },
    "resource_href": "https://api.uber.com/v2/eats/order/153dd7f1-339d-4619-940c-418943c14636",
}

And here my API endpoint: (empty because I don't know how to handle it)

[HttpPost("/api/v1/.../delivery/hook")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public async Task<IActionResult> HookDelivery()
        {
            return Ok("hook reached");
        }

Solution

  • When webhook event occurs, the source application typically triggers an http POST. So the easiest way is to create a C# representation of the JSON object you provided and use it as an input param fro your API method. Something like this:

    public class WebHookData
    {
       public string EventType {get;set;}
       public string EventId {get;set;}
       etc....
    }
    

    and then

        [HttpPost("/api/v1/.../delivery/hook")]
        [ProducesResponseType(200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        public async Task<IActionResult> ExistTerminalSerialNumber(WebHookData webHookData)
        {
            // do something with your input here
            return Ok("hook reached");
        }
    

    or something generic and have custom method that "converts" the incoming object to whatever you want it :

    public async Task<IHttpActionResult> ExistTerminalSerialNumber([FromBody]JObject data)
    {
        string eventType= data["event_type"].ToString();
            switch (eventType)
            {
                case "orders.notification":
                    // do something
                    return Ok();
                default:
                    return BadRequest();
            }
    }