Hey there, fellow developer! Ready to dive into the world of WhatsApp Business API integration? You're in the right place. We'll be using the WhatsappBusiness.CloudApi package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that package installed. Fire up your terminal and run:
dotnet add package WhatsappBusiness.CloudApi
Easy peasy, right?
Create a new C# project (I'm sure you can do this with your eyes closed), and add these using statements at the top of your file:
using WhatsappBusiness.CloudApi; using WhatsappBusiness.CloudApi.Configurations; using WhatsappBusiness.CloudApi.Interfaces;
Now, let's get that client set up:
var config = new WhatsAppBusinessCloudApiConfig { AccessToken = "YOUR_ACCESS_TOKEN", PhoneNumberId = "YOUR_PHONE_NUMBER_ID" }; var client = new WhatsAppBusinessClient(config);
Replace those placeholders with your actual credentials, and you're good to go!
Sending a text message is a breeze:
await client.SendTextMessageAsync("RECIPIENT_PHONE_NUMBER", "Hello, WhatsApp!");
Want to send an image? No problem:
await client.SendImageMessageAsync("RECIPIENT_PHONE_NUMBER", "IMAGE_URL", "Check out this cool image!");
Set up an endpoint in your application to receive webhooks. Here's a quick example using ASP.NET Core:
[HttpPost("webhook")] public IActionResult ReceiveWebhook([FromBody] dynamic data) { // Process the webhook data // You'll want to add proper error handling and validation here return Ok(); }
Always check the status of your messages:
var response = await client.SendTextMessageAsync("RECIPIENT_PHONE_NUMBER", "Hello, WhatsApp!"); if (response.IsSuccessful) { Console.WriteLine("Message sent successfully!"); } else { Console.WriteLine($"Error: {response.ErrorMessage}"); }
Spice things up with template messages:
await client.SendTemplateMessageAsync("RECIPIENT_PHONE_NUMBER", "YOUR_TEMPLATE_NAME", new[] { "PARAM1", "PARAM2" });
Want to add some buttons? Go for it:
var buttons = new List<WhatsAppButton> { new WhatsAppButton { Type = "reply", Title = "Yes" }, new WhatsAppButton { Type = "reply", Title = "No" } }; await client.SendInteractiveButtonsMessageAsync("RECIPIENT_PHONE_NUMBER", "Do you like coding?", buttons);
And there you have it! You're now equipped to integrate WhatsApp into your C# applications. Remember, practice makes perfect, so don't be afraid to experiment and push the boundaries of what you can do with this API.
Happy coding, and may your messages always be delivered!