Send WhatsApp messages from C# with a typed HttpClient and PostAsJsonAsync to /v26.0/<PHONE_NUMBER_ID>/messages. Receive webhooks with MapGet for verification and MapPost for events. The POST reads the body once, checks X-Hub-Signature-256 with CryptographicOperations.FixedTimeEquals, queues the bytes for a BackgroundService and returns 200. The Program.cs below does both on .NET 10 with no NuGet packages.
Create the project
.NET 10 is the current LTS release. Its latest patch, 10.0.14, shipped on October 25, 2026, and support runs until November 14, 2028. Both .NET 8 and .NET 9 reach end of support on November 10, 2026 (.NET support policy, accessed 2026-11-04), so start new services on 10.
dotnet new web creates the ASP.NET Core Empty project, and under SDK 10 it targets net10.0 (dotnet new templates).
dotnet new web -o WhatsAppDotnet
cd WhatsAppDotnet
export WHATSAPP_TOKEN="ACCESS_TOKEN"
export PHONE_NUMBER_ID="PHONE_NUMBER_ID"
export APP_SECRET="APP_SECRET"
export VERIFY_TOKEN="VERIFY_TOKEN"
Replace the generated Program.cs with the file below. For web projects, the hosting package behind BackgroundService “is referenced implicitly from the shared framework”, and an explicit reference “isn’t required” (hosted services in ASP.NET Core).
GRAPH_VERSION defaults to v26.0, which the Graph API changelog lists as released July 29, 2026 (Graph API changelog, accessed 2026-11-04). GRAPH_BASE defaults to https://graph.facebook.com, so you can point the client at a mock. The token and phone number ID come from the test number guide.
Program.cs
// Program.cs
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Threading.Channels;
using Microsoft.AspNetCore.Mvc;
var cli = args is ["text" or "template", ..];
var builder = WebApplication.CreateBuilder(cli ? Array.Empty<string>() : args);
var config = builder.Configuration; // includes environment variables
builder.Services.AddHttpClient<WhatsAppSender>(http =>
{
var graphBase = (config["GRAPH_BASE"] ?? "https://graph.facebook.com").TrimEnd('/');
var graphVersion = config["GRAPH_VERSION"] ?? "v26.0";
http.BaseAddress = new Uri($"{graphBase}/{graphVersion}/");
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", config["WHATSAPP_TOKEN"]);
http.Timeout = TimeSpan.FromSeconds(15); // our choice; Meta documents none
});
builder.Services.AddSingleton(Channel.CreateBounded<byte[]>(
new BoundedChannelOptions(100) { FullMode = BoundedChannelFullMode.Wait, SingleReader = true }));
builder.Services.AddHostedService<WebhookWorker>();
var app = builder.Build();
// ---- CLI: dotnet run -- text TO BODY | template TO NAME LANGUAGE [PARAMS...] ----
if (cli)
{
Required(config, "WHATSAPP_TOKEN");
Required(config, "PHONE_NUMBER_ID");
var sender = app.Services.GetRequiredService<WhatsAppSender>();
using var cts = new CancellationTokenSource(TimeSpan.FromMinutes(2));
try
{
var sent = args switch
{
["text", var to, var body] => await sender.SendTextAsync(to, body, cts.Token),
["template", var to, var name, var language, .. var parameters] =>
await sender.SendTemplateAsync(to, name, language, parameters, cts.Token),
_ => throw new ArgumentException("usage: dotnet run -- text TO BODY | template TO NAME LANGUAGE [PARAMS...]"),
};
Console.WriteLine($"accepted: {sent.MessageId} {sent.MessageStatus}");
Console.WriteLine($"wa_id: {sent.WaId}");
}
catch (WhatsAppError e)
{
Console.Error.WriteLine(e.Message);
if (e.Code == 131047) Console.Error.WriteLine("Window closed: send an approved template instead.");
if (e.Code == 190) Console.Error.WriteLine("Token expired: create a new access token.");
Environment.ExitCode = 1;
}
catch (ArgumentException e)
{
Console.Error.WriteLine(e.Message);
Environment.ExitCode = 2;
}
return;
}
// ---- Webhook server: dotnet run ----
var appSecret = Encoding.UTF8.GetBytes(Required(config, "APP_SECRET"));
var verifyToken = Required(config, "VERIFY_TOKEN");
app.MapGet("/webhook", (
[FromQuery(Name = "hub.mode")] string? mode,
[FromQuery(Name = "hub.verify_token")] string? token,
[FromQuery(Name = "hub.challenge")] string? challenge) =>
mode == "subscribe" && token == verifyToken && challenge is not null
? Results.Text(challenge, "text/plain")
: Results.StatusCode(StatusCodes.Status403Forbidden));
app.MapPost("/webhook", async (HttpRequest request, Channel<byte[]> queue, CancellationToken ct) =>
{
using var buffer = new MemoryStream();
await request.Body.CopyToAsync(buffer, ct); // the only read: the body can't be rewound
var raw = buffer.ToArray(); // the exact bytes Meta signed
if (!ValidSignature(appSecret, raw, request.Headers["X-Hub-Signature-256"].ToString()))
return Results.StatusCode(StatusCodes.Status401Unauthorized);
return queue.Writer.TryWrite(raw)
? Results.Ok()
: Results.StatusCode(StatusCodes.Status503ServiceUnavailable); // queue full: Meta retries a non-200
});
app.Run();
static string Required(IConfiguration settings, string key) =>
settings[key] is { Length: > 0 } value ? value : throw new InvalidOperationException($"set the {key} environment variable");
static bool ValidSignature(byte[] secret, byte[] payload, string header)
{
if (!header.StartsWith("sha256=", StringComparison.Ordinal)) return false;
var expected = Encoding.ASCII.GetBytes(Convert.ToHexStringLower(HMACSHA256.HashData(secret, payload)));
var received = Encoding.ASCII.GetBytes(header["sha256=".Length..]);
return CryptographicOperations.FixedTimeEquals(expected, received);
}
// ---- Sending ----
record SendResult(string MessageId, string? WaId, string? MessageStatus);
sealed class WhatsAppSender(HttpClient http, IConfiguration config, ILogger<WhatsAppSender> log)
{
const int MaxAttempts = 4;
// Member names match Meta's snake_case fields, so the Web camelCase policy leaves them alone.
public Task<SendResult> SendTextAsync(string to, string body, CancellationToken ct) =>
SendAsync(new
{
messaging_product = "whatsapp",
recipient_type = "individual",
to,
type = "text",
text = new { preview_url = false, body },
}, ct);
// A bare value becomes a positional parameter, name=value a named one.
public Task<SendResult> SendTemplateAsync(string to, string name, string language, string[] parameters, CancellationToken ct)
{
object template = parameters.Length == 0
? (object)new { name, language = new { code = language } }
: new
{
name,
language = new { code = language },
components = new[]
{
new
{
type = "body",
parameters = parameters.Select(p => p.Split('=', 2) is [var key, var value]
? (object)new { type = "text", parameter_name = key, text = value }
: new { type = "text", text = p }).ToArray(),
},
},
};
return SendAsync(new { messaging_product = "whatsapp", recipient_type = "individual", to, type = "template", template }, ct);
}
async Task<SendResult> SendAsync<T>(T message, CancellationToken ct)
{
var path = $"{config["PHONE_NUMBER_ID"]}/messages";
for (var attempt = 0; ; attempt++)
{
using var response = await http.PostAsJsonAsync(path, message, ct);
var json = await response.Content.ReadAsStringAsync(ct);
var error = WhatsAppError.From((int)response.StatusCode, json);
if (error is null) return Parse(json);
var wait = error.Code switch
{
131056 => TimeSpan.FromSeconds(Math.Pow(4, attempt)), // pair rate: Meta's 4^X, so 1, 4, 16 s
130429 => TimeSpan.FromSeconds(1 << attempt), // throughput: our choice, 1, 2, 4 s
_ => TimeSpan.Zero, // everything else: fix it, don't retry
};
if (wait == TimeSpan.Zero || attempt == MaxAttempts - 1) throw error;
log.LogWarning("code {Code}, retrying in {Seconds} s", error.Code, wait.TotalSeconds);
await Task.Delay(wait, ct);
}
}
static SendResult Parse(string json)
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var message = root.GetProperty("messages")[0];
string? waId = root.TryGetProperty("contacts", out var contacts) && contacts.GetArrayLength() > 0
&& contacts[0].TryGetProperty("wa_id", out var w) ? w.GetString() : null;
string? status = message.TryGetProperty("message_status", out var s) ? s.GetString() : null;
return new SendResult(message.GetProperty("id").GetString()!, waId, status);
}
}
sealed class WhatsAppError(int status, int code, string errorMessage, string? details, string? traceId)
: Exception($"HTTP {status}, code {code}: {errorMessage} {details} (fbtrace_id {traceId})")
{
public int Status { get; } = status;
public int Code { get; } = code;
public static WhatsAppError? From(int status, string json)
{
try
{
using var doc = JsonDocument.Parse(json);
if (!doc.RootElement.TryGetProperty("error", out var e))
return status < 400 ? null : new WhatsAppError(status, 0, "no error object in the response", null, null);
return new WhatsAppError(status,
e.TryGetProperty("code", out var c) && c.TryGetInt32(out var n) ? n : 0,
e.TryGetProperty("message", out var m) ? m.GetString() ?? "" : "",
e.TryGetProperty("error_data", out var d) && d.TryGetProperty("details", out var dd) ? dd.GetString() : null,
e.TryGetProperty("fbtrace_id", out var t) ? t.GetString() : null);
}
catch (JsonException)
{
return new WhatsAppError(status, 0, "body is not JSON", json, null);
}
}
}
// ---- Receiving ----
sealed class WebhookWorker(Channel<byte[]> queue, ILogger<WebhookWorker> log) : BackgroundService
{
readonly HashSet<string> seen = []; // in-memory dedupe for the demo; use a unique index in production
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var raw in queue.Reader.ReadAllAsync(stoppingToken))
{
try { Process(raw); }
catch (Exception e) { log.LogError(e, "could not process payload"); }
}
}
void Process(byte[] raw)
{
using var doc = JsonDocument.Parse(raw);
var root = doc.RootElement;
if (Str(root, "object") != "whatsapp_business_account") return;
foreach (var entry in Arr(root, "entry"))
foreach (var change in Arr(entry, "changes"))
{
if (Str(change, "field") != "messages" || !change.TryGetProperty("value", out var value)) continue;
foreach (var msg in Arr(value, "messages"))
{
var id = Str(msg, "id");
if (!seen.Add($"msg:{id}")) continue;
var sender = Str(msg, "from") ?? Str(msg, "from_user_id");
var type = Str(msg, "type");
var text = type == "text" && msg.TryGetProperty("text", out var t) ? Str(t, "body") : $"[{type}]";
log.LogInformation("message {Id} from {Sender} at {Timestamp}: {Text}", id, sender, Str(msg, "timestamp"), text);
}
foreach (var st in Arr(value, "statuses"))
{
var id = Str(st, "id");
var status = Str(st, "status");
if (!seen.Add($"status:{id}:{status}")) continue;
var recipient = Str(st, "recipient_id") ?? Str(st, "recipient_user_id");
log.LogInformation("status {Status} for {Id} to {Recipient}", status, id, recipient);
if (status == "failed" && st.TryGetProperty("errors", out var errors))
log.LogWarning("errors: {Errors}", errors.GetRawText());
}
}
}
static string? Str(JsonElement e, string name) =>
e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String
? v.GetString() : null;
static IEnumerable<JsonElement> Arr(JsonElement e, string name) =>
e.ValueKind == JsonValueKind.Object && e.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array
? v.EnumerateArray() : Enumerable.Empty<JsonElement>();
}
The CLI takes the same arguments as the Go version and the PHP script. The template line builds the body of Meta’s positional-parameter sample, with Jessica and SKBUP2-4CPIG9 as the two body values:
dotnet run -- text +16505551234 "Your order shipped"
dotnet run -- template +16505551234 order_confirmation en_US Jessica SKBUP2-4CPIG9
dotnet run
Sending: snake_case names, errors and retries
AddHttpClient<WhatsAppSender> registers a typed client, which “is registered as transient with DI”. The factory behind it avoids “Resource exhaustion problems by pooling HttpMessageHandler instances” and stale DNS by cycling them (IHttpClientFactory in ASP.NET Core).
PostAsJsonAsync “uses JsonSerializerDefaults.Web options for serialization” (PostAsJsonAsync). Those defaults apply a camelCase policy, so a C# property named PreviewUrl would go out as previewUrl instead of Meta’s preview_url. The anonymous types above use Meta’s own names, such as messaging_product and preview_url. If you switch to classes, put [JsonPropertyName("preview_url")] on each property.
A successful response carries the message ID in messages[0].id. Meta says the ID appears again in the sent, delivered and read webhooks. A success response “only indicates that the API successfully accepted your request” (Meta send messages, accessed 2026-11-04). contacts[0].input echoes the to you sent, and Meta notes that wa_id “May not match input value”. message_status appears only for template messages that Meta is pacing. A text body holds at most 4,096 characters (Meta text messages).
SendAsync branches on error.code, as Meta’s error page advises, because titles may be deprecated (Meta error codes, accessed 2026-11-04). Two codes get a retry. 131056 is the pair rate limit. Meta says to “retry after 4^X seconds (starting with X=0 and increasing X by 1 after each failure)” (Meta about the platform, accessed 2026-11-04). The loop resends to the same recipient, the only one that has to wait. In a send queue, delay that recipient alone, as the outbound rate limiter does.
For 130429, Meta’s fix is to “Try again later or reduce the frequency” of sends. The 1, 2 and 4 second waits are this file’s choice. Each registered number supports up to 80 messages per second by default (Meta throughput). Cloud API rate limits explains both limits.
Every other code throws. 131047 means the customer service window has closed and only a template can go out (error 131047). The CLI also prints a hint for 131047 and 190.
| Code | Meaning on Meta’s error page | What this file does |
|---|---|---|
| 131056 | Too many messages to the same recipient in a short time | Retries after 1, 4 and 16 seconds (4^X), same recipient only |
| 130429 | Cloud API throughput reached | Retries after 1, 2 and 4 seconds |
| 131047 | More than 24 hours since the user’s last reply | Throws; send a template instead |
| 190 | Access token expired | Throws; get a new access token |
The rest of the codes are in the error codes reference. Named parameters such as first_name=Jessica are covered in the template variables guide.
Receiving: dotted keys and a body read once
C# parameter names can’t contain dots, so the GET binds each key with [FromQuery(Name = "hub.mode")] (minimal API parameter binding). Results.Text returns the challenge as a bare text/plain body. Meta sends webhooks only after a 200 that includes the challenge (Meta create a webhook endpoint, accessed 2026-11-04). PHP rewrites the dots to underscores (Meta Graph API webhooks, accessed 2026-11-04), which ASP.NET Core doesn’t do.
The same binding page warns that “The request body isn’t buffered by default. After the body is read, it’s not rewindable.” The POST copies request.Body into a MemoryStream once and keeps the byte array. The hash runs on those bytes, and the worker parses the same array. Hashing a re-serialized object fails, as the signature verification guide shows with accented text.
HMACSHA256.HashData “Computes the HMAC of data using the SHA-256 algorithm” in one static call (HMACSHA256.HashData). Convert.ToHexStringLower, available since .NET 9, turns the 32 bytes into lowercase hex (Convert.ToHexStringLower). FixedTimeEquals compares “in a way that doesn’t leak timing information”, and returns early only when the lengths differ (CryptographicOperations.FixedTimeEquals). A valid header always has 64 hex characters, so an early false only reveals a malformed header.
Return 200 before the work
Meta’s throughput page asks webhook servers for a “Median latency not to exceed 250ms” and fewer than 1% of responses above one second (Meta throughput). The POST does no database or AI work. It writes the bytes to a bounded Channel and answers. Microsoft’s binding page shows the same hand-off with a 202. Meta’s endpoint guide asks for a 200, so the code returns Results.Ok().
The channel holds 100 payloads. When it is full, TryWrite returns false and the handler answers 503. Meta retries failed deliveries “with decreasing frequency until the request succeeds, for up to 7 days” (Meta webhooks overview, accessed 2026-11-04). The capacity and the 503 are this file’s choices.
The channel lives in memory. Microsoft’s hosted services page warns that if the process fails, “StopAsync might not be called”, and anything still queued is lost after its 200. For a queue that survives a crash, write the raw bytes to durable storage before answering, as webhook queue architecture describes.
Senders and dedupe
The worker reads the sender from from, then from from_user_id. Meta’s BSUID page says from “Will be omitted if the phone number cannot be included”. from_user_id is “set to the user’s BSUID” (Meta business-scoped user IDs, accessed 2026-11-04). Statuses use recipient_id, then recipient_user_id. Business-scoped user IDs covers the contact table side.
Retries “can result in duplicate webhook notifications”, so the worker keys messages on msg:<id> and statuses on status:<id>:<status>. A delivered and a read status share one ID and are separate events. The HashSet is lost on restart and isn’t shared between instances, so production needs a unique index in your database.
Test it
dotnet run prints the address in its Now listening on: line. Use it as BASE. The GET should print 123:
BASE="http://localhost:5090"
curl "$BASE/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
Sign Meta’s text webhook sample, compacted to one line, and post it:
cat > sample.json <<'EOF'
{"object":"whatsapp_business_account","entry":[{"id":"102290129340398","changes":[{"value":{"messaging_product":"whatsapp","metadata":{"display_phone_number":"15550783881","phone_number_id":"106540352242922"},"contacts":[{"profile":{"name":"Sheena Nelson"},"wa_id":"16505551234"}],"messages":[{"from":"16505551234","id":"wamid.HBgLMTY1MDM4Nzk0MzkVAgASGBQzQTRBNjU5OUFFRTAzODEwMTQ0RgA=","timestamp":"1749416383","type":"text","text":{"body":"Does it come in another color?"}}]},"field":"messages"}]}]}
EOF
SIG=$(openssl dgst -sha256 -hmac "$APP_SECRET" sample.json | awk '{print $NF}')
curl -i -X POST "$BASE/webhook" \
-H "Content-Type: application/json" \
-H "X-Hub-Signature-256: sha256=$SIG" \
--data-binary @sample.json
The first run returns 200 and the console logs the message line. A repeat returns 200 and logs nothing. Edit one character of sample.json without re-signing and the server returns 401. To register the callback URL in the App Dashboard, expose the port through a public HTTPS address, such as an ngrok tunnel.
Z-API Omni team