WhatsApp official API in ASP.NET Core: HttpClient
Integrate the official WhatsApp API into ASP.NET Core via CRPRO Hub: a typed HttpClient, a minimal API webhook, HMACSHA256.HashData and FixedTimeEquals.
In ASP.NET Core, the CRPRO Hub integration has a typed client, registered with AddHttpClient, to send, and a minimal API endpoint to receive the webhook. What needs care in .NET is reading the body as bytes, the hex format of the signature and constant-time comparison. The code below uses .NET 8 or later features, such as the primary constructor; compile and test it before production.
How to build the typed HttpClient
Short answer: register a class with AddHttpClient<T>, configure BaseAddress, the Authorization header and the Timeout at registration, and receive the HttpClient through the constructor. The factory manages connection lifetime.
Microsoft's documentation describes the typed client as a class that wraps a configured HttpClient, registered with AddHttpClient and injected in the constructor. BaseAddress is combined with relative paths, and the default handler lifetime is 2 minutes. A URI detail, which does not come from that page, is that BaseAddress should end with a slash and the relative path should not start with one; otherwise the base path (/api/v1) is replaced.
- Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes (authentication). The value is shown only once.
- Keep the key and the secret out of code: environment variables, user-secrets in development, or your provider's vault.
- Use the Idempotency-Key header, mandatory on send, with a value stable per logical message.
- EnsureSuccessStatusCode throws HttpRequestException when the status is not 2xx, as the documentation describes.
# Variaveis de ambiente (o separador duplo vira ":" na configuracao)
CrproHub__ApiKey=hub_pk_EXEMPLO_NAO_REAL
CrproHub__WebhookSecret=whsec_EXEMPLO_NAO_REAL// CrproHubClient.cs
using System.Net.Http.Json;
using System.Text.Json;
public class CrproHubClient(HttpClient http)
{
public async Task<string?> EnviarTextoAsync(
string canal, string para, string texto, string chave, CancellationToken ct = default)
{
// Sem barra inicial: com BaseAddress terminada em barra, o caminho se soma ao /api/v1/
using var requisicao = new HttpRequestMessage(HttpMethod.Post, $"channels/{canal}/messages")
{
Content = JsonContent.Create(new { to = para, type = "text", text = new { body = texto } }),
};
requisicao.Headers.Add("Idempotency-Key", chave);
using var resposta = await http.SendAsync(requisicao, ct);
resposta.EnsureSuccessStatusCode(); // lanca HttpRequestException fora de 2xx
var json = await resposta.Content.ReadFromJsonAsync<JsonElement>(ct); // 202: aceita, nao entregue
return json.GetProperty("data").GetProperty("message_id").GetString();
}
}The same key with the same body returns the original response; with a different body, the Hub answers 409 IDEMPOTENCY_KEY_REUSED. The limits are 60 messages per minute per channel and 120 requests per minute per organization and credential. The 202 only says the message was accepted and queued; the final state arrives through the message.status webhook.
How to receive the webhook with a minimal API
Short answer: a MapPost that reads the body from HttpRequest.Body into a MemoryStream, computes the HMAC with HMACSHA256.HashData, compares with FixedTimeEquals and answers Results.Ok(). Do not receive the body as an object: model binding would consume the stream before you have the bytes.
The Hub signs timestamp.delivery_id.body with HMAC SHA-256 and sends the X-Hub-Timestamp, X-Hub-Delivery-Id, X-Hub-Signature-Version and X-Hub-Signature-256 headers, the last as sha256=HEX. HMACSHA256.HashData(key, data), static and available from .NET 6, returns the HMAC of the bytes. CryptographicOperations.FixedTimeEquals compares two byte sequences without leaking timing by content and only exits early if the lengths differ, according to the documentation. That is why the example decodes the hex with Convert.FromHexString and first checks it has 64 characters; malformed hex throws FormatException, treated as an invalid signature.
curl -X POST https://crprohub.com/api/v1/webhooks \
-H "Authorization: Bearer hub_pk_EXEMPLO_NAO_REAL" \
-H "Content-Type: application/json" \
-d '{"name":"Recebimento","url":"https://your-domain.com/webhooks/crprohub","event_types":["message.received"]}'// Program.cs
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<CrproHubClient>(cliente =>
{
cliente.BaseAddress = new Uri("https://crprohub.com/api/v1/");
cliente.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration["CrproHub:ApiKey"]);
cliente.Timeout = TimeSpan.FromSeconds(10);
});
var app = builder.Build();
var vistos = new System.Collections.Concurrent.ConcurrentDictionary<string, bool>();
app.MapPost("/webhooks/crprohub", async (HttpRequest request, CrproHubClient hub, IConfiguration config) =>
{
using var memoria = new MemoryStream();
await request.Body.CopyToAsync(memoria);
var corpo = memoria.ToArray(); // bytes exatos
if (!AssinaturaValida(request, corpo, config["CrproHub:WebhookSecret"]!))
return Results.Unauthorized();
using var documento = JsonDocument.Parse(corpo);
var evento = documento.RootElement.Clone();
if (vistos.TryAdd(evento.GetProperty("id").GetString()!, true)) // use armazenamento compartilhado em producao
{
// Em producao, entregue a uma fila em segundo plano (por exemplo, um BackgroundService).
_ = Task.Run(async () =>
{
if (evento.GetProperty("event").GetString() != "message.received") return;
var dados = evento.GetProperty("data");
await hub.EnviarTextoAsync(
evento.GetProperty("channel_id").GetString()!,
dados.GetProperty("from").GetString()!,
"Recebemos sua mensagem.",
"resp-" + dados.GetProperty("message_id").GetString());
});
}
return Results.Ok(); // 2xx rapido
});
app.Run();
static bool AssinaturaValida(HttpRequest r, byte[] corpo, string segredo)
{
var prefixo = Encoding.UTF8.GetBytes(r.Headers["X-Hub-Timestamp"] + "." + r.Headers["X-Hub-Delivery-Id"] + ".");
var assinado = prefixo.Concat(corpo).ToArray();
var esperado = HMACSHA256.HashData(Encoding.UTF8.GetBytes(segredo), assinado);
var hex = r.Headers["X-Hub-Signature-256"].ToString().Replace("sha256=", "");
if (hex.Length != 64) return false;
byte[] recebido;
try { recebido = Convert.FromHexString(hex); }
catch (FormatException) { return false; }
return CryptographicOperations.FixedTimeEquals(esperado, recebido); // tempo constante
}{
"id": "6f1f0f6a-3b2c-4d1e-9a8b-0c1d2e3f4a5b",
"event": "message.received",
"channel_id": "9f6a9c1e-2f3d-4a5b-8c7d-1e2f3a4b5c6d",
"occurred_at": "2026-08-21T12:00:00.000Z",
"data": {
"message_id": "wamid.EXEMPLO123",
"from": "5521999999999",
"type": "text",
"text": "Oi, ainda tem em estoque?"
}
}Queue, duplicates and a fast response
Short answer: answer 200 quickly and hand the work to a queue. The Hub expects a 2xx within 10 seconds, repeats a delivery up to nine times over about four days and pauses the endpoint after 20 consecutive failures.
The example's Task.Run is only illustrative: tasks fired that way are lost if the process restarts. In production, use a background queue, such as a BackgroundService that consumes from a channel or a message service. The ConcurrentDictionary is also local and vanishes on restart; use a table with a unique constraint on the event id. The body id stays the same on retry and replay. Mark the id as done only at the end of the work, or the Hub's retry, after a failure, will be discarded.
| Endpoint response | When | Effect on the Hub |
|---|---|---|
| 401 | Invalid or missing signature | Counts as a failure |
| 200 | New or repeated event | Delivery complete |
| 500 | Invalid JSON or exception | Retry |
If the endpoint is paused, reactivate with PATCH /api/v1/webhooks/{id} and {"status":"active"}. The walkthrough is on the webhooks page.
Binding errors and what the Hub sees
Short answer: in production, a minimal API binding failure writes 400 directly, without throwing; in development, it throws. Since the endpoint reads the body by hand, a 400 appears only if you return it.
ASP.NET Core's error handling documentation explains that ThrowOnBadRequest is true in development and false outside it, and that unsupported content in JSON binding yields 415. For a webhook, this reinforces the choice not to use object binding: your code decides the status and the Hub always sees 401, 200 or 500. If a problem details middleware is active, it only fills error responses with no body; check that it does not write a body into a 200.
How to test the endpoint
Short answer: sign a test body with the same formula and send it with HttpClient against the test server, passing the X-Hub-* headers. Test a correct signature, which should give 200, and a swapped one, which should give 401.
Use ASP.NET Core's own test server or run the app locally and fire POST /api/v1/webhooks/{id}/test, which sends a real event to your domain, up to 10 times per hour per endpoint. The webhooks page linked above gives the formula and the headers; the quickstart shows the first call.
Frequently asked questions
Why not receive the body as a C# object?
Because model binding consumes the stream and the signature covers the exact bytes. Read the raw body, check the HMAC and only then parse the JSON.
Why compare bytes and not the hex text?
Because FixedTimeEquals compares in constant time, and Convert.ToHexString returns uppercase, which would break a text comparison with the Hub's lowercase hex.
Must BaseAddress end with a slash?
Yes, to add relative paths without a leading slash. With a leading slash on the path, the /api/v1 part of the base is dropped.
Can I use Task.Run in production?
It is not recommended. A loose task is lost if the process restarts. Use a background queue and record the event state.
Fontes
Documentação oficial da Meta, conferida em 31 de outubro de 2026.