In this article, you will learn how to build a real-world WhatsApp chatbot using ASP.NET Core and OpenAI. This bot can automatically reply to customer messages and can be turned into a SaaS product.
🚀 What You Will Build
- WhatsApp webhook API
- AI auto-reply system
- OpenAI integration
- Real-time message processing
📌 Prerequisites
- ASP.NET Core Web API
- OpenAI API Key
- WhatsApp Business API (Meta Cloud API or Twilio)
1. Setup WhatsApp Cloud API
Go to Meta Developer Portal and create WhatsApp Business app.
https://developers.facebook.com/
Get:
- Access Token
- Phone Number ID
- Webhook Verify Token
2. Create ASP.NET Core Web API
dotnet new webapi -n WhatsAppBot
3. Configure appsettings.json
"WhatsApp": {
"AccessToken": "YOUR_TOKEN",
"PhoneNumberId": "YOUR_PHONE_ID"
},
"OpenAI": {
"ApiKey": "YOUR_OPENAI_KEY"
}
4. Create OpenAI Service
public class OpenAIService
{
private readonly HttpClient _http;
public OpenAIService(HttpClient http)
{
_http = http;
}
public async Task<string> GetReply(string message, string apiKey)
{
var request = new
{
model = "gpt-4o-mini",
messages = new[]
{
new { role = "user", content = message }
}
};
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
var response = await _http.PostAsJsonAsync(
"https://api.openai.com/v1/chat/completions", request);
dynamic result = await response.Content.ReadFromJsonAsync<dynamic>();
return result.choices[0].message.content;
}
}
5. Create WhatsApp Webhook Controller
[ApiController]
[Route("api/webhook")]
public class WebhookController : ControllerBase
{
private readonly IConfiguration _config;
private readonly OpenAIService _ai;
private readonly HttpClient _http;
public WebhookController(IConfiguration config, OpenAIService ai, IHttpClientFactory factory)
{
_config = config;
_ai = ai;
_http = factory.CreateClient();
}
[HttpGet]
public IActionResult Verify(
[FromQuery] string hub_mode,
[FromQuery] string hub_verify_token,
[FromQuery] string hub_challenge)
{
if (hub_verify_token == "my_verify_token")
return Ok(hub_challenge);
return Unauthorized();
}
[HttpPost]
public async Task Receive([FromBody] dynamic data)
{
try
{
var message = data.entry[0].changes[0].value.messages[0].text.body;
var from = data.entry[0].changes[0].value.messages[0].from;
var reply = await _ai.GetReply(message, _config["OpenAI:ApiKey"]);
await SendWhatsAppMessage(from, reply);
return Ok();
}
catch
{
return Ok();
}
}
private async Task SendWhatsAppMessage(string to, string message)
{
var url = $"https://graph.facebook.com/v18.0/{_config["WhatsApp:PhoneNumberId"]}/messages";
var payload = new
{
messaging_product = "whatsapp",
to = to,
text = new { body = message }
};
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", _config["WhatsApp:AccessToken"]);
request.Content = JsonContent.Create(payload);
await _http.SendAsync(request);
}
}
6. Register Services
builder.Services.AddHttpClient<OpenAIService>();
builder.Services.AddHttpClient();
7. Test Flow
- User sends WhatsApp message
- Webhook receives message
- OpenAI generates reply
- Bot sends reply back
💡 Real Use Cases
- Customer support automation
- Order tracking bot
- FAQ chatbot
- Lead generation system
💰 Monetization Idea (IMPORTANT)
Turn this into SaaS:
- Charge ₹499/month per business
- Provide dashboard
- Add analytics
- Multi-business support
🔐 Best Practices
- Validate webhook requests
- Use logging (Serilog)
- Store chat history
- Add rate limiting
- Use retry policy
📌 Conclusion
You now have a real-world WhatsApp AI bot using ASP.NET Core and OpenAI. This can be scaled into a powerful business product.
No comments:
Post a Comment