Skip to Content

How to send a message on WhatsApp in C#?

WhatsApp has become one of the most popular messaging platforms in the world. With over 2 billion users, it is used for both personal and business communication. Sending messages programmatically on WhatsApp can be very useful for developers looking to integrate WhatsApp messaging into their applications.

In this article, we will learn how to send a WhatsApp message using C#. We will go through the steps to set up a C# project, get the required libraries, create a WhatsApp client, and send a simple text message. By the end of this article, you should have a good understanding of how to get started with sending WhatsApp messages programmatically in C#.

Prerequisites

Before we dive into the code, there are a few prerequisites required to follow along:

  • Visual Studio 2019 (or higher version)
  • .NET Framework 4.5 (or higher version)
  • NuGet Package Manager in Visual Studio
  • WhatsApp Business API account and credentials

Make sure to have Visual Studio installed with the NuGet Package Manager. You will also need a WhatsApp Business API account which can be obtained by registering as a WhatsApp Business account user. This will provide you with the credentials required to authenticate and use the WhatsApp APIs.

Create a C# project

Open Visual Studio and create a new C# console application project. You can give it any name of your choice. Once the project is created, the next step is to install the required libraries to use the WhatsApp Business API.

Install WhatsApp Business API libraries

The WhatsApp Business API provides .NET libraries to easily integrate WhatsApp capabilities into C# applications. We will leverage these libraries to send messages. Here are the two libraries that need to be installed:

  • Twilio.WhatsApp – Provides capabilities to send and receive messages
  • Twilio.Http – Handles authentication and HTTP requests

To install these libraries, open the NuGet Package Manager in your project. Search for ‘Twilio.WhatsApp’ and ‘Twilio.Http’ and install the latest version of both the packages. This will download the libraries and automatically add references in your project.

Create a WhatsApp client

With the libraries installed, we can now create a WhatsApp client that will be used to send messages. Add a new C# file to your project and include the following namespaces:

using Twilio.WhatsApp;
using Twilio.Http;
using Twilio.Rest.WhatsApp.V1.Service; 

Next, we need to initialize the client with our WhatsApp Business API credentials (Account SID, Auth Token):

public static WhatsAppClient GetWhatsAppClient()  
{
  // Replace with your actual credentials
  const string accountSid = "ACxx"; 
  const string authToken = "xx";
  
  TwilioClient twilioClient = new TwilioClient(accountSid, authToken);
  
  return new WhatsAppClient(twilioClient);
}

This initializes an instance of the WhatsAppClient that can be used to send requests to the WhatsApp Business API. The TwilioClient handles authentication while the WhatsAppClient allows us to send messages.

Send a WhatsApp message

Now let’s look at how to actually send a WhatsApp message using the client we initialized. Add the following code to send a simple text message:

public static void SendWhatsAppMessage()
{
  var client = GetWhatsAppClient();
  
  var message = client.Messages
                   .Create("whatsapp:+14155238886", // Replace with your WhatsApp number
                           from: "whatsapp:+14157654321", // Replace with a WhatsApp number you own
                           body: "Hello from C#!");
}

Here we are sending a message “Hello from C#!” to a WhatsApp number we specify. The from number should be a WhatsApp number associated with your business account. When this code runs, the recipient will receive the text message from your business account number.

And that’s it! With just a few lines of code, we can now send automated WhatsApp messages using C#. The WhatsAppBusiness API takes care of the complexities behind the scenes and provides a simple interface to interact with WhatsApp from .NET applications.

Send WhatsApp message with media

The WhatsApp Business API also allows sending messages with media attachments like images, documents and videos. Here is some sample code to send a message with an image attached:

public static void SendImageMessage()  
{
  var client = GetWhatsAppClient();
  
  var message = client.Messages.Create("whatsapp:+14155238886",
                                      from: "whatsapp:+14157654321",
                                      mediaUrl: "https://example.com/image.png"); 
}

The mediaUrl parameter allows attaching a media file by specifying its URL. This image will be bundled and sent along with the message. You can also attach documents, videos, audio and other media in a similar way.

Send template messages

Apart from plain text, the WhatsApp Business API provides the ability to send structured template messages. These are advanced message formats defined by your business that allow adding sections, buttons, headings and more.

Here is some sample code to send a predefined template:

public static void SendTemplateMessage()
{
  var client = GetWhatsAppClient();

  var message = client.Messages.Create("whatsapp:+14155238886",
                                      from: "whatsapp:+14157654321",
                                      templateName: "survey_template",
                                      templateParameters: new Dictionary 
                                      {
                                        {"question", "Are you satisfied with our service?"},
                                        {"button1", "Satisfied"},
                                        {"button2", "Unsatisfied"}
                                      });
}

This will send a structured template message configured in your WhatsApp Business account. The templateName specifies the identifier for the template. The templateParameters allow setting custom values for the dynamic fields defined in the template.

Send messages to groups

The WhatsApp Business API also provides the capability to message groups and broadcast lists. Here is how you can send a message to a WhatsApp group:

public static void SendGroupMessage()
{
  var client = GetWhatsAppClient();

  var message = client.Messages.Create("group_id", 
                                      from: "whatsapp:+14157654321",
                                      body: "This is a message to your group!"); 
}

To get the group ID, you can list all groups associated with your business account. Then use the group ID to send messages targeted to that particular group.

Receive incoming messages

Two-way messaging is enabled with the WhatsApp Business API. This allows your application to not only send messages but also receive incoming messages.

Here is a simple example to print any incoming message:

public static void ReceiveIncomingMessage()
{
  var client = GetWhatsAppClient();

  client.OnMessageReceived += (sender, args) =>
  {
    Console.WriteLine(args.Message.From);
    Console.WriteLine(args.Message.Body);
  }
}

The OnMessageReceived event can be used to trigger a callback function whenever a new message comes in. This code will print the sender’s number and the text body.

Incoming messages can also be programmatically fetched at intervals using the Messages.GetMessage method.

Conclusion

This covers the basic capabilities to get started with the WhatsApp Business API in C#. The key steps are:

  • Install the Twilio NuGet libraries
  • Initialize a WhatsAppClient with credentials
  • Use the Messages resource to send text, media, templates
  • Add event handlers to react to incoming messages

Some other things you can do with the API include sending messages with quick replies, managing contacts, groups and more. Refer to the official WhatsApp Business API documentation for more details. Integrating WhatsApp messaging and notifications in a C# application can drive more user engagement for businesses.

Here are some additional tips when using the WhatsApp Business API from C#:

Error handling

Use try-catch blocks when calling the API to handle errors gracefully. The API throws exceptions for requests that fail validation or have issues.

Rate limiting

The WhatsApp Business API enforces rate limits on messages sent per second/day. If you hit the limit, the client will throw a TooManyRequestsException. Implement exponential backoff retries to handle this.

Async/await

The message sending methods can be used with async/await for asynchronous non-blocking messaging.

public async static Task SendAsyncMessage()
{
  //...

  await client.Messages.CreateAsync();
} 

Message status

Use the MessageStatus resource to check delivery status of messages sent. This can ensure your application handles failures.

var status = client.MessageStatus.Get("messageId");

if(status.Status == "failed")
{
  // Resend message
}

Message pricing

The WhatsApp Business API has a pricing model based on number of messages sent. Be aware of this pricing before sending large volumes of messages.

We have covered a lot of ground discussing how to send WhatsApp messages using the C# language and WhatsApp Business API. You should now have a good foundation to build on top of this and create more complex messaging flows and applications.

The official WhatsApp Business API documentation is an excellent resource for more details on all the capabilities of the API. Some other ideas for taking your WhatsApp application further could include:

  • Sending notifications and alerts to users
  • Building a WhatsApp bot with automatic replies
  • Integrating payments via WhatsApp
  • Analyzing user engagement based on messaging activity

If you have any other questions on using the WhatsApp Business API from C#, feel free to post them in the comments section below! I will try my best to address any queries you may have. Happy messaging!