Twilio Programmable Messaging Callback-Webhook URL For Whatsapp And C#/.Net

Twilio programmable messaging enables the communication between your application and clients. In this article, we will learn how to use Twilio programmable messaging callback URL for Whatsapp in c#/.Net; this typically listens to an incoming message from your client-end (Whatsapp) to your application.

To get started, you should have an account with Twilio and a WhatsApp number already dedicated to you on your Twilio console.

To test your number on Whatsapp. Send join tank-advice to your dedicated number.

Now, we are going to create a project that listens to incoming messages from end-users to our application and provides a response. This article is a continuation of our previous article on "How to integrate Chat-gpt using c#/.Net"; we are going to be building on the already existing project but you can as well follow along and it's also for you if you are trying to integrate with Twilio programmable messaging.

Let's get started

Let's install the twilio nuget packages using packet manager console

Create a new interface class, name it IWhatsappIncomingMessages.cs and add the following code

public interface IWhatsappIncomingMessageService 
{ 
    Task IncomingMessage(CustomerRequestModel incomingMessage);
}

Create a data model class; name it CustomerRequestModel.cs and add the following code

 public class CustomerRequestModel
    {
        public string Message { get; set; }
    }

CustomerRequestModel.cs contains a string property Message that is received from Twilio.

Create a service class that will extend the IWhatsappIncomingMessageService.cs and name it WhatsappIncomingMessagingService.cs; add the following code

 public class WhatsappIncomingMessageService : IWhatsappIncomingMessageService
    {
        private readonly IADProductService _productService;
        public WhatsappIncomingMessageService(IADProductService aDProductService)
        {
            _productService = aDProductService;
        }
        public async Task<string> IncomingMessage(CustomerRequestModel incomingMessage)
        {

            var returnedMessage = await _productService.GenerateAdContent(incomingMessage);
           var messages = returnedMessage.ADContent[2];
            return messages;


        }
    }

This preceding code implements the IADProductService from the previous article "Integrating with Chat-gpt".

Create an ApiController and name it WhatsappController.cs and extend TwilioController. Add the following code

using AdGenerateBot.ApplicationService.ADProduct;
using AdGenerateBot.ApplicationService.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Twilio.AspNet.Core;
using Twilio.TwiML;


namespace AdGenerateBot.API.Controllers
{
    [Route("api/whatsapp/[action]")]
    [ApiController]
    public class WhatsappController : TwilioController
    {
        private readonly IWhatsappIncomingMessageService _whatsappIncomingMessageService;
        public WhatsappController(IWhatsappIncomingMessageService whatsappIncomingMessageService)
        {
            _whatsappIncomingMessageService = whatsappIncomingMessageService;
        }



        [HttpPost]
        public async Task<IActionResult> IncomingMessages()
        {
            try
            {
                var message = new MessagingResponse();
                string messages = Request.Form["Body"];
                var customerResponse = new CustomerRequestModel
                {
                    Message = messages
                };
                var response = await _whatsappIncomingMessageService.IncomingMessage(customerResponse);
                return new MessagingResponse()
                  .Message($"{response}")
                  .ToTwiMLResult();


            }

            catch (System.Exception ex)
            {

                return BadRequest(ex.Message);
            }

        }
    }
}

The preceding code is a HTTP Post method that gets the value using Request.Form["Body"] and returns a response using ToTwiMLResult.

Configure the Webhook

To be able to use Twilio programmable messaging callback for WhatsApp, you need a callback URL. To get a callback URL without deploying our application we would use Ngrok. Ngrok creates tunnels and helps developers expose their local development server to the internet with little effort.

To get started, you need to have Ngrok set up. Download and follow the documentation. Run the Ngrok terminal and connect using the authtoken on your dashboard.

Auth-Token on your dashboard

Get the port number of your application and run this command to set up the tunnel.

ngrok http https://localhost:7069 --host-header=”localhost:7069"

You will get this response after setting and running the command. Copy the forwarding URL 6ac5-102-36-151-1.eu.ngrok.io

Head on to your console Twilio sandbox for WhatsApp and paste the URL in the callback and save it.

Test the application

To test what you have done ensure you have your application running on your local and the tunnel - ngrok is up with internet access.

Send a message to your Twilio phone number and wait for a response from Chat-gpt.

Thank you for reading.