← Blog

·

WhatsApp Cloud API with C

Updated on October 29, 2026

To use the WhatsApp API with C#, you need an HttpClient that calls POST /<PHONE_NUMBER_ID>/messages on the Cloud API and a webhook endpoint that answers Meta’s verification challenge, validates the X-Hub-Signature-256 signature and returns 200 before doing any processing. In ASP.NET Core, all of that fits in a minimal API with a Channel<T> queue and a BackgroundService that consumes the events, with no WhatsApp package at all.

This tutorial builds the project from scratch in five files: sending text, template messages and buttons, a complete webhook, background processing and testing with curl. The code runs directly against Meta or through Vectalk by changing two environment variables. The same bot is also available in Python, Node.js and Java with Spring Boot.

Bot architecture

  1. A customer sends a message to your number.
  2. Meta sends a POST with the event to your webhook.
  3. The endpoint reads the raw body, validates the HMAC, writes the event to a Channel<byte[]> and returns 200.
  4. A BackgroundService reads the queue, decides on the reply and calls the Cloud API.

Separating receiving from processing is what keeps the webhook fast. Meta retries events that don’t get a 200, immediately and then with decreasing frequency for up to 7 days, so a slow endpoint produces duplicates. To understand the platform before diving into code, see the guide to the official WhatsApp API.

Prerequisites

VariableWhat it isWhere to find it
PHONE_NUMBER_IDThe number’s ID in the Cloud APIApp Dashboard, WhatsApp section
ACCESS_TOKENToken with the whatsapp_business_messaging permissionPermanent system user token
APP_SECRETThe app secret, used for the signatureApp settings > Basic
VERIFY_TOKENA string of your choiceYou define it and repeat it in the dashboard

On your machine: .NET 8 SDK or later. The code uses primary constructors, from C# 12.

dotnet new web -n WhatsAppBot
cd WhatsAppBot

The web template creates an empty ASP.NET Core project with a Program.cs. No extra NuGet package is needed: System.Text.Json, System.Threading.Channels and IHttpClientFactory ship with the framework.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

1. Program.cs: webhook and dependency injection

Replace the contents of Program.cs:

using System.Net.Http.Headers;
using System.Threading.Channels;

var builder = WebApplication.CreateBuilder(args);
var cfg = builder.Configuration;
var verifyToken = cfg["VERIFY_TOKEN"] ?? throw new InvalidOperationException("VERIFY_TOKEN");
var appSecret = cfg["APP_SECRET"] ?? "";
var webhookKey = cfg["WEBHOOK_KEY"] ?? "";

builder.Services.AddSingleton(Channel.CreateBounded<byte[]>(
    new BoundedChannelOptions(1000) { SingleReader = true }));
builder.Services.AddHttpClient("whatsapp", c =>
    c.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", cfg["ACCESS_TOKEN"]));
builder.Services.AddSingleton<WhatsAppClient>();
builder.Services.AddHostedService<WebhookWorker>();

var app = builder.Build();

app.MapGet("/webhook", (HttpRequest req) =>
{
    var q = req.Query;
    return q["hub.mode"] == "subscribe" && q["hub.verify_token"] == verifyToken
        ? Results.Text(q["hub.challenge"].ToString())
        : Results.StatusCode(403);
});

app.MapPost("/webhook", async (HttpRequest req, Channel<byte[]> queue) =>
{
    if (webhookKey != "" && req.Query["key"] != webhookKey)
        return Results.StatusCode(403);

    using var ms = new MemoryStream();
    await req.Body.CopyToAsync(ms);
    var body = ms.ToArray();

    if (!Signature.IsValid(appSecret, body, req.Headers["X-Hub-Signature-256"]))
        return Results.Unauthorized();

    // Queue full: return 503 and Meta will retry later
    return queue.Writer.TryWrite(body) ? Results.Ok() : Results.StatusCode(503);
});

app.Run();

What each part does:

  • GET /webhook handles verification. When you save the URL in the dashboard, Meta sends hub.mode=subscribe, hub.verify_token and hub.challenge. If the token matches, the response is 200 with hub.challenge as plain text, which is exactly what Results.Text produces. Any other response leaves the webhook unverified.
  • POST /webhook reads the body as bytes, validates the signature and enqueues it. There is no deserialization here: the JSON is only parsed in the worker.
  • Channel.CreateBounded caps the queue at 1,000 events. With TryWrite, a spike beyond that returns 503 instead of blowing up the process’s memory, and Meta retries later.
  • AddHttpClient("whatsapp") registers a named client in IHttpClientFactory, which manages the connection lifecycle. Creating new HttpClient() on every send exhausts sockets under load.

WEBHOOK_KEY is optional and is meant for the Vectalk scenario, explained further down.

2. Signature.cs: validating X-Hub-Signature-256

Every POST from Meta carries the header X-Hub-Signature-256: sha256=<hash>, where the hash is an HMAC-SHA256 of the raw body computed with the app secret. Create Signature.cs:

using System.Security.Cryptography;
using System.Text;

static class Signature
{
    public static bool IsValid(string secret, byte[] body, string? header)
    {
        if (secret.Length == 0) return true; // no secret (e.g. via Vectalk, protected by WEBHOOK_KEY)
        if (string.IsNullOrEmpty(header) || !header.StartsWith("sha256=")) return false;

        byte[] received;
        try { received = Convert.FromHexString(header.AsSpan(7)); }
        catch (FormatException) { return false; }

        var expected = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), body);
        return CryptographicOperations.FixedTimeEquals(expected, received);
    }
}

Two details matter:

  • The HMAC is computed over the bytes that arrived, not over an object that was deserialized and serialized again. A single space or a different field order changes the hash. That’s why the endpoint copies req.Body into a MemoryStream instead of binding a type as a parameter.
  • CryptographicOperations.FixedTimeEquals compares in constant time, so the response time doesn’t reveal how many bytes matched. Comparing strings with == works, but it’s the wrong choice here.

The article on how to validate the webhook signature lists the most common mistakes, such as proxies that modify the body.

3. WhatsAppClient.cs: sending with HttpClient

using System.Net.Http.Json;

public class WhatsAppClient(IHttpClientFactory factory, IConfiguration cfg, ILogger<WhatsAppClient> log)
{
    private readonly string _url = cfg["API_URL"]
        ?? $"https://graph.facebook.com/v26.0/{cfg["PHONE_NUMBER_ID"]}/messages";

    public async Task<string> SendAsync(IDictionary<string, string> dest, string type, object content,
                                        CancellationToken ct = default)
    {
        var payload = dest.ToDictionary(d => d.Key, d => (object)d.Value);
        payload["messaging_product"] = "whatsapp";
        payload["type"] = type;
        payload[type] = content;

        var http = factory.CreateClient("whatsapp");
        using var res = await http.PostAsJsonAsync(_url, payload, ct);
        var body = await res.Content.ReadAsStringAsync(ct);
        if (!res.IsSuccessStatusCode)
        {
            log.LogError("API {Status}: {Body}", (int)res.StatusCode, body);
            res.EnsureSuccessStatusCode();
        }
        return body;
    }

    public Task<string> SendTextAsync(IDictionary<string, string> dest, string text, CancellationToken ct = default) =>
        SendAsync(dest, "text", new { body = text }, ct);

    public Task<string> SendTemplateAsync(string to, string name, string lang, string[] values,
                                          CancellationToken ct = default) =>
        SendAsync(new Dictionary<string, string> { ["to"] = to }, "template", new
        {
            name,
            language = new { code = lang },
            components = new[]
            {
                new { type = "body", parameters = values.Select(v => new { type = "text", text = v }).ToArray() }
            }
        }, ct);

    public Task<string> SendButtonsAsync(IDictionary<string, string> dest, string text,
                                         (string Id, string Title)[] buttons, CancellationToken ct = default) =>
        SendAsync(dest, "interactive", new
        {
            type = "button",
            body = new { text },
            action = new
            {
                buttons = buttons.Select(b => new { type = "reply", reply = new { id = b.Id, title = b.Title } })
            }
        }, ct);
}

Notes:

  • Anonymous types become Meta’s exact JSON. PostAsJsonAsync uses System.Text.Json with the Web defaults, which camelCase property names and leave dictionary keys untouched. Since the fields are already lowercase in the code and messaging_product is a dictionary key, the payload comes out in the expected format with no extra configuration.
  • The error body goes to the log. Meta returns an error object with code and error_data.details. That text is what solves most problems; the table of WhatsApp API error codes helps you interpret it.
  • Template messages require the exact number of parameters. If values has one item more or less than the approved template, the response is error 132000, explained in errors 132000 and 132012.
  • dest is a dictionary because the recipient can be to (phone number) or recipient (BSUID), when the customer uses a username. See WhatsApp usernames and BSUID.

4. WebhookModels.cs: the typed payload

Records with only the fields the bot uses:

using System.Text.Json.Serialization;

public record WebhookPayload(List<Entry>? Entry);
public record Entry(List<Change>? Changes);
public record Change(string? Field, ChangeValue? Value);
public record ChangeValue(List<Message>? Messages);
public record Message(
    string? From,
    [property: JsonPropertyName("from_user_id")] string? FromUserId,
    string Id,
    string Type,
    TextBody? Text,
    Interactive? Interactive);
public record TextBody(string Body);
public record Interactive(string Type, [property: JsonPropertyName("button_reply")] Reply? ButtonReply);
public record Reply(string Id, string Title);

Deserialization uses JsonSerializerDefaults.Web, which matches names case-insensitively. So from maps to From and changes to Changes. Fields with underscores need JsonPropertyName. Unknown fields are ignored by default.

5. WebhookWorker.cs: the queue consumer

using System.Text.Json;
using System.Threading.Channels;

public class WebhookWorker(Channel<byte[]> queue, WhatsAppClient wa, ILogger<WebhookWorker> log)
    : BackgroundService
{
    private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
    private readonly HashSet<string> _processed = []; // in production: Redis or a database, with expiration

    private static readonly Dictionary<string, string> Answers = new()
    {
        ["horario"] = "We're open Monday to Friday, 9 a.m. to 6 p.m.",
        ["precos"] = "See the full price list at https://example.com/precos",
        ["humano"] = "Sure! An agent will continue the conversation here.",
    };

    protected override async Task ExecuteAsync(CancellationToken stop)
    {
        await foreach (var body in queue.Reader.ReadAllAsync(stop))
        {
            try
            {
                var payload = JsonSerializer.Deserialize<WebhookPayload>(body, Json);
                var messages = (payload?.Entry ?? [])
                    .SelectMany(e => e.Changes ?? [])
                    .SelectMany(c => c.Value?.Messages ?? []);
                foreach (var msg in messages)
                {
                    if (!_processed.Add(msg.Id)) continue; // Meta may resend
                    await HandleAsync(msg, stop);
                }
            }
            catch (Exception e) when (e is not OperationCanceledException)
            {
                log.LogError(e, "failed to process event");
            }
        }
    }

    private async Task HandleAsync(Message msg, CancellationToken ct)
    {
        IDictionary<string, string> dest = msg.From is not null
            ? new Dictionary<string, string> { ["to"] = msg.From }
            : new Dictionary<string, string> { ["recipient"] = msg.FromUserId! };

        switch (msg.Type)
        {
            case "text":
                var text = msg.Text!.Body.Trim().ToLowerInvariant();
                if (text is "hi" or "hello" or "menu")
                    await wa.SendButtonsAsync(dest, "Hi! How can I help?",
                        [("horario", "Business hours"), ("precos", "Pricing"), ("humano", "Talk to an agent")], ct);
                else
                    await wa.SendTextAsync(dest, "Sorry, I didn't get that. Type *menu* to see the options.", ct);
                break;

            case "interactive" when msg.Interactive?.Type == "button_reply":
                var choice = msg.Interactive!.ButtonReply!.Id;
                await wa.SendTextAsync(dest, Answers.GetValueOrDefault(choice, "Invalid option."), ct);
                break;

            default:
                await wa.SendTextAsync(dest, "For now I only understand text and buttons.", ct);
                break;
        }
    }
}

The parentheses in (payload?.Entry ?? []) make SelectMany run over the entry list or, if it isn’t in the payload, over an empty list.

About the worker:

  • A single reader. The Channel was created with SingleReader = true, and HashSet isn’t thread-safe; with only one consumer, the two fit together. If you need parallelism, switch to ConcurrentDictionary and run multiple readers.
  • Delivery statuses (sent, delivered, read, failed) arrive on the same webhook, under value.statuses, and are ignored here. To handle them, see message status via webhook.
  • Button limits: up to 3 per message, title up to 20 characters, id up to 256.

6. Run and test

ASP.NET Core reads environment variables into configuration by default, so cfg["VERIFY_TOKEN"] finds the exported variable:

export VERIFY_TOKEN="any-text-you-like"
export ACCESS_TOKEN="EAAG..."
export APP_SECRET="your-app-secret"
export PHONE_NUMBER_ID="123456789012345"
dotnet run --urls http://localhost:5000

Test the verification and a signed event:

curl "http://localhost:5000/webhook?hub.mode=subscribe&hub.verify_token=any-text-you-like&hub.challenge=42"

BODY='{"entry":[{"changes":[{"value":{"messages":[{"from":"5511999999999","id":"wamid.teste1","type":"text","text":{"body":"menu"}}]}}]}]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:5000/webhook \
  -H "Content-Type: application/json" \
  -H "X-Hub-Signature-256: sha256=$SIG" \
  --data-binary "$BODY"

The first command returns 42. The second returns 200, and the worker sends the menu to the number in the from field (use your own test number). A 401 means the signature is wrong.

For real events, Meta requires a public URL with a valid TLS certificate; self-signed certificates are not accepted. During development, use a tunnel, as shown in testing the webhook locally with ngrok. Then, in App Dashboard > WhatsApp > Configuration, enter the callback URL and the verify token and subscribe to the messages field.

To deploy, the .NET SDK builds a container image without a Dockerfile, using dotnet publish -t:PublishContainer. Put a reverse proxy with HTTPS in front of it.

Production checklist

  • Durable queue. The Channel lives in memory: if the process goes down, queued events are lost, and Meta does not resend anything that already got a 200. For high volume or slow processing, write the event to an external queue (Azure Service Bus, RabbitMQ, SQS) before responding. To run the webhook on functions, see serverless webhook.
  • Shared deduplication. With more than one instance, each instance’s HashSet can’t see the others. Use Redis or a table with a unique key.
  • Send throughput. The Cloud API has a messages-per-second limit per number; see throughput and rate limits.
  • Secrets. In production, use a vault (Azure Key Vault, AWS Secrets Manager) or orchestrator variables, never a version-controlled appsettings.json.

How to do it with Vectalk

Vectalk is a proxy for the official WhatsApp Cloud API: payloads and webhook events are the same as Meta’s, so the project works with no change in logic. Three adjustments:

  1. URL and token. Set API_URL=https://apis.vectalk.com.br/api/messages and use a Vectalk instance token in ACCESS_TOKEN. With it, the phone_number_id is resolved automatically.
  2. Webhook registered via API. Register the URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name. Each instance accepts multiple URLs.
  3. Endpoint protection. The Vectalk webhooks documentation does not describe a signature header. Leave APP_SECRET empty, set WEBHOOK_KEY to a long random value and register the URL with ?key=YOUR_VALUE.
curl -X POST https://apis.vectalk.com.br/api/webhooks \
  -H "Authorization: Bearer YOUR_VECTALK_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"instance_id": "YOUR_INSTANCE", "url": "https://bot.yourcompany.com/webhook?key=YOUR_VALUE", "name": "Bot .NET"}'

Vectalk expects a 200 within 20 seconds and resends if it doesn’t get one; deduplication already covers that case. Create your account at apps.vectalk.com.br/register and check the documentation.

Frequently asked questions

Is there an official Meta SDK for C#?

You don’t need one. The Cloud API is HTTP with JSON, and HttpClient with System.Text.Json covers both sending and receiving. Calling the API directly lets you use new features as soon as Meta documents them.

Does it work with controllers instead of a minimal API?

Yes. The point to watch is the same: in the POST, read Request.Body as bytes to validate the signature before deserializing. If the controller takes a typed [FromBody] parameter, the original body has already been consumed.

Can I process events directly in the endpoint, without a queue?

For testing, yes. In production, any slow call (database, AI, another API) delays the 200, and Meta resends the event. The queue separates the two with very little code.

Can the bot start the conversation?

Free-form messages and buttons only work inside the 24-hour window opened by the customer’s last message. To start or resume a conversation after that, use SendTemplateAsync with an approved template message.


Official sources consulted on October 29, 2026: Create a webhook endpoint (Meta), Webhooks overview (Meta), Interactive reply buttons (Meta), Minimal APIs (Microsoft), IHttpClientFactory (Microsoft), System.Threading.Channels (Microsoft), Background tasks with hosted services (Microsoft), CryptographicOperations.FixedTimeEquals (Microsoft), Vectalk: webhooks, Vectalk: authentication.

Try the official WhatsApp API today

Create your account, generate a token and send your first message with the quick-start guide. Same payloads and webhooks as Meta's Cloud API.