Invia messaggi WhatsApp da C# con un HttpClient tipizzato e PostAsJsonAsync verso /v26.0/<PHONE_NUMBER_ID>/messages. Ricevi i webhook con MapGet per la verifica e MapPost per gli eventi. Il POST legge il corpo una sola volta, controlla X-Hub-Signature-256 con CryptographicOperations.FixedTimeEquals, mette i byte in coda per un BackgroundService e restituisce 200. Il Program.cs qui sotto fa entrambe le cose su .NET 10, senza pacchetti NuGet.
Creare il progetto
.NET 10 è la release LTS attuale. La sua ultima patch, la 10.0.14, è uscita il 25 ottobre 2026, e il supporto dura fino al 14 novembre 2028. Sia .NET 8 sia .NET 9 arrivano a fine supporto il 10 novembre 2026 (criteri di supporto di .NET, consultato il 2026-11-04), quindi avvia i nuovi servizi sulla 10.
dotnet new web crea il progetto ASP.NET Core Empty, e con l’SDK 10 punta a net10.0 (modelli di dotnet new).
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"
Sostituisci il Program.cs generato con il file qui sotto. Nei progetti web, il pacchetto di hosting dietro BackgroundService «è referenziato implicitamente dal framework condiviso», e un riferimento esplicito «non è necessario» (servizi ospitati in ASP.NET Core).
GRAPH_VERSION vale per default v26.0, che il changelog della Graph API indica come rilasciata il 29 luglio 2026 (changelog della Graph API, consultato il 2026-11-04). GRAPH_BASE vale per default https://graph.facebook.com, così puoi puntare il client verso un mock. Il token e l’ID del numero di telefono vengono dalla guida al numero di test.
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>();
}
La CLI accetta gli stessi argomenti della versione in Go e dello script PHP. La riga del modello costruisce il corpo dell’esempio di Meta con parametri posizionali, con Jessica e SKBUP2-4CPIG9 come i due valori del corpo:
dotnet run -- text +16505551234 "Your order shipped"
dotnet run -- template +16505551234 order_confirmation en_US Jessica SKBUP2-4CPIG9
dotnet run
Invio: nomi snake_case, errori e nuovi tentativi
AddHttpClient<WhatsAppSender> registra un client tipizzato, che «viene registrato come transient con la DI». La factory che lo gestisce evita i «problemi di esaurimento delle risorse grazie al pooling delle istanze di HttpMessageHandler» e i DNS obsoleti facendole ruotare (IHttpClientFactory in ASP.NET Core).
PostAsJsonAsync «usa le opzioni JsonSerializerDefaults.Web per la serializzazione» (PostAsJsonAsync). Questi default applicano una policy camelCase, quindi una proprietà C# chiamata PreviewUrl uscirebbe come previewUrl invece del preview_url di Meta. I tipi anonimi qui sopra usano i nomi di Meta, come messaging_product e preview_url. Se passi a delle classi, metti [JsonPropertyName("preview_url")] su ogni proprietà.
Una risposta riuscita porta l’ID del messaggio in messages[0].id. Meta dice che l’ID ricompare nei webhook sent, delivered e read. Una risposta di successo «indica solo che l’API ha accettato la tua richiesta» (Meta, invio dei messaggi, consultato il 2026-11-04). contacts[0].input ripete il to che hai inviato, e Meta osserva che wa_id «potrebbe non coincidere con il valore di input». message_status compare solo per i messaggi modello di cui Meta sta regolando il ritmo. Un body di testo contiene al massimo 4.096 caratteri (Meta, messaggi di testo).
SendAsync decide in base a error.code, come consiglia la pagina degli errori di Meta, perché i titoli possono essere deprecati (Meta, codici di errore, consultato il 2026-11-04). Due codici danno luogo a un nuovo tentativo. Il 131056 è il limite di frequenza per coppia. Meta dice di «riprovare dopo 4^X secondi (partendo da X=0 e aumentando X di 1 dopo ogni errore)» (Meta, informazioni sulla piattaforma, consultato il 2026-11-04). Il ciclo reinvia allo stesso destinatario, l’unico che deve aspettare. In una coda di invio, ritarda solo quel destinatario, come fa il limitatore di frequenza in uscita.
Per il 130429, la soluzione di Meta è «riprovare più tardi o ridurre la frequenza» degli invii. Le attese di 1, 2 e 4 secondi sono una scelta di questo file. Ogni numero registrato supporta per default fino a 80 messaggi al secondo (Meta, throughput). Limiti di frequenza della Cloud API spiega entrambi i limiti.
Tutti gli altri codici sollevano un’eccezione. Il 131047 significa che la finestra di assistenza clienti si è chiusa e può partire solo un modello (errore 131047). La CLI stampa anche un suggerimento per il 131047 e il 190.
| Codice | Significato nella pagina degli errori di Meta | Cosa fa questo file |
|---|---|---|
| 131056 | Troppi messaggi allo stesso destinatario in poco tempo | Ritenta dopo 1, 4 e 16 secondi (4^X), solo verso lo stesso destinatario |
| 130429 | Throughput della Cloud API raggiunto | Ritenta dopo 1, 2 e 4 secondi |
| 131047 | Più di 24 ore dall’ultima risposta dell’utente | Solleva un’eccezione; invia invece un modello |
| 190 | Token di accesso scaduto | Solleva un’eccezione; ottieni un nuovo token di accesso |
Gli altri codici sono nel riferimento dei codici di errore. I parametri nominati come first_name=Jessica sono trattati nella guida alle variabili dei modelli.
Ricezione: chiavi con il punto e un corpo letto una volta
I nomi dei parametri C# non possono contenere punti, quindi il GET lega ogni chiave con [FromQuery(Name = "hub.mode")] (binding dei parametri nelle minimal API). Results.Text restituisce il challenge come semplice corpo text/plain. Meta invia i webhook solo dopo un 200 che include il challenge (Meta, creare un endpoint webhook, consultato il 2026-11-04). PHP riscrive i punti come underscore (Meta, webhook della Graph API, consultato il 2026-11-04), cosa che ASP.NET Core non fa.
La stessa pagina sul binding avverte: «Il corpo della richiesta non è bufferizzato per default. Dopo che il corpo è stato letto, non è possibile riavvolgerlo.» Il POST copia request.Body in un MemoryStream una sola volta e conserva l’array di byte. L’hash viene calcolato su quei byte, e il worker analizza lo stesso array. L’hash di un oggetto riserializzato fallisce, come mostra la guida alla verifica della firma con un testo accentato.
HMACSHA256.HashData «calcola l’HMAC dei dati usando l’algoritmo SHA-256» con una sola chiamata statica (HMACSHA256.HashData). Convert.ToHexStringLower, disponibile da .NET 9, trasforma i 32 byte in esadecimale minuscolo (Convert.ToHexStringLower). FixedTimeEquals confronta «in un modo che non fa trapelare informazioni sui tempi», e termina in anticipo solo quando le lunghezze sono diverse (CryptographicOperations.FixedTimeEquals). Un header valido ha sempre 64 caratteri esadecimali, quindi un false anticipato rivela solo un header malformato.
Restituire 200 prima del lavoro
La pagina sul throughput di Meta chiede ai server dei webhook una «latenza mediana non superiore a 250 ms» e meno dell’1% di risposte oltre un secondo (Meta, throughput). Il POST non fa alcun lavoro su database o AI. Scrive i byte in un Channel limitato e risponde. La pagina sul binding di Microsoft mostra lo stesso passaggio con un 202. La guida di Meta sugli endpoint chiede un 200, quindi il codice restituisce Results.Ok().
Il canale contiene 100 payload. Quando è pieno, TryWrite restituisce false e l’handler risponde 503. Meta ritenta le consegne fallite «con frequenza decrescente finché la richiesta non va a buon fine, per un massimo di 7 giorni» (Meta, panoramica dei webhook, consultato il 2026-11-04). La capacità e il 503 sono scelte di questo file.
Il canale vive in memoria. La pagina di Microsoft sui servizi ospitati avverte che, se il processo si interrompe, «StopAsync potrebbe non essere chiamato», e tutto ciò che è ancora in coda va perso dopo il suo 200. Per una coda che sopravviva a un crash, scrivi i byte grezzi su uno storage durevole prima di rispondere, come descrive l’architettura a coda per i webhook.
Mittenti e deduplicazione
Il worker legge il mittente da from, poi da from_user_id. La pagina di Meta sui BSUID dice che from «viene omesso se il numero di telefono non può essere incluso». from_user_id è «impostato sul BSUID dell’utente» (Meta, business-scoped user ID, consultato il 2026-11-04). Gli stati usano recipient_id, poi recipient_user_id. Business-scoped user ID copre il lato della tabella dei contatti.
I nuovi tentativi «possono generare notifiche webhook duplicate», quindi il worker usa come chiave msg:<id> per i messaggi e status:<id>:<status> per gli stati. Uno stato delivered e uno read condividono lo stesso ID e sono eventi separati. L’HashSet si perde al riavvio e non è condiviso tra istanze, quindi in produzione serve un indice univoco nel tuo database.
Provarlo
dotnet run stampa l’indirizzo nella riga Now listening on:. Usalo come BASE. Il GET dovrebbe stampare 123:
BASE="http://localhost:5090"
curl "$BASE/webhook?hub.mode=subscribe&hub.verify_token=$VERIFY_TOKEN&hub.challenge=123"
Firma l’esempio di webhook di testo di Meta, compattato su una riga, e invialo:
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
La prima esecuzione restituisce 200 e la console registra la riga del messaggio. Una ripetizione restituisce 200 e non registra nulla. Modifica un carattere di sample.json senza firmarlo di nuovo e il server restituisce 401. Per registrare l’URL di callback nell’App Dashboard, esponi la porta tramite un indirizzo HTTPS pubblico, come un tunnel ngrok.
Il team di Z-API Omni