WhatsApp official API in Spring Boot: RestClient
Integrate the official WhatsApp API into Spring Boot via CRPRO Hub: RestClient to send, @RequestBody byte[] and MessageDigest.isEqual for the signature.
In Spring Boot, the CRPRO Hub integration uses RestClient to call the API and a controller to receive the webhook. The pitfalls are familiar to anyone handling webhooks in Java: the body must arrive as bytes, before any conversion to an object; the signature needs constant-time comparison; and slow processing cannot hold up the response. This article brings both sides with minimal code. The Jackson imports change between major Spring Boot versions, so check the ObjectMapper package on your version.
Where the key and the secret live
Short answer: in environment variables, read through Spring properties. The API key (hub_pk_...) and the webhook secret (whsec_...) stay out of the repository.
Create the API key in the Hub dashboard with the messages:send and webhooks:write scopes (authentication) and store the value, which is shown only once. The whsec_ secret is also shown once, in the POST /api/v1/webhooks response. If you lose it, rotate; there is no recovery.
# application.properties (valores vindos do ambiente)
crprohub.api-key=${CRPRO_API_KEY}
crprohub.webhook-secret=${CRPRO_WEBHOOK_SECRET}How to send a message with RestClient
Short answer: build a RestClient with baseUrl and the Authorization header as default, and call post().uri().header().contentType().body().retrieve().body(). The Hub answers 202 with status accepted.
- Spring's documentation creates the client with RestClient.builder(), baseUrl and defaultHeader, and states that once created, a RestClient is safe to use from multiple threads. Create one and reuse it.
- retrieve() alone does nothing: you need a terminal operation, like body(Class) or toEntity(Class).
- By default, 4xx and 5xx responses throw an exception; onStatus lets you handle specific codes. To read the status and error body, the documentation points to RestClientResponseException and its subclasses.
- The Idempotency-Key is mandatory and must be stable per logical message. 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.
@Component
public class CrproHubClient {
private final RestClient http;
public CrproHubClient(@Value("${crprohub.api-key}") String apiKey) {
this.http = RestClient.builder()
.baseUrl("https://crprohub.com/api/v1")
.defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
.build();
}
@SuppressWarnings("unchecked")
public String enviarTexto(String canal, String para, String texto, String chave) {
Map<String, Object> resposta = http.post()
.uri("/channels/{canal}/messages", canal)
.header("Idempotency-Key", chave)
.contentType(MediaType.APPLICATION_JSON)
.body(Map.of("to", para, "type", "text", "text", Map.of("body", texto)))
.retrieve() // 4xx e 5xx lancam excecao por padrao
.body(Map.class); // 202: aceita, nao entregue
return (String) ((Map<String, Object>) resposta.get("data")).get("message_id");
}
}How to receive the webhook with @RequestBody byte[]
Short answer: a @PostMapping that receives the body as byte[], checks the HMAC with MessageDigest.isEqual and answers 200. Receiving it as an object would make Spring convert the JSON before you see the bytes, and the signature covers the exact 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. @RequestHeader with defaultValue avoids a 400 for a missing header, and an invalid signature falls to 401. Java's documentation describes MessageDigest.isEqual as a time-constant comparison: all bytes of the first argument are examined, and the time depends only on its length. So the expected value, computed by you, goes first, and the received value goes second.
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"]}'@RestController
public class CrproWebhookController {
private final String segredo;
private final ObjectMapper mapper = new ObjectMapper();
private final Set<String> vistos = ConcurrentHashMap.newKeySet(); // use armazenamento compartilhado em producao
private final ExecutorService fila = Executors.newFixedThreadPool(4);
public CrproWebhookController(@Value("${crprohub.webhook-secret}") String segredo) {
this.segredo = segredo;
}
@PostMapping("/webhooks/crprohub")
public ResponseEntity<Void> receber(
@RequestBody byte[] corpo, // bytes exatos, sem conversao
@RequestHeader(value = "X-Hub-Timestamp", defaultValue = "") String timestamp,
@RequestHeader(value = "X-Hub-Delivery-Id", defaultValue = "") String entrega,
@RequestHeader(value = "X-Hub-Signature-256", defaultValue = "") String assinatura) throws Exception {
if (!assinaturaValida(timestamp, entrega, assinatura, corpo)) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
JsonNode evento = mapper.readTree(corpo);
if (vistos.add(evento.get("id").asText())) {
fila.submit(() -> tratar(evento));
}
return ResponseEntity.ok().build(); // 2xx rapido
}
boolean assinaturaValida(String timestamp, String entrega, String assinatura, byte[] corpo) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(segredo.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
mac.update((timestamp + "." + entrega + ".").getBytes(StandardCharsets.UTF_8));
byte[] esperado = mac.doFinal(corpo);
String hex = assinatura.replaceFirst("^sha256=", "");
if (!hex.matches("[0-9a-f]{64}")) {
return false;
}
return MessageDigest.isEqual(esperado, HexFormat.of().parseHex(hex)); // esperado primeiro
}
private void tratar(JsonNode evento) { /* chame o CrproHubClient aqui */ }
}{
"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: the controller validates, records the id and hands 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 in-memory set vanishes on restart and is not shared across instances; in production, use a table with a unique constraint on the event id. The body id stays the same on retry and replay, and is the right key. Recording the id before the work finishes has a risk: if the work fails, the Hub's retry is discarded. Mark it done at the end of the work, and use the body's message_id as the basis of the send's Idempotency-Key, so a repeated handling does not duplicate the reply.
| Controller 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 pauses, reactivate with PATCH /api/v1/webhooks/{id} and {"status":"active"}. Diagnosis is on the webhooks page.
How to test the signature without the Hub
Short answer: compute the HMAC in the test with the same formula and call the assinaturaValida method, or use Spring's MockMvc to post the body with the headers. Cover the correct case and the swapped case.
In a unit test, instantiate the controller with a fixed secret, compute the signature of a body with a known timestamp and delivery id and confirm assinaturaValida returns true; change one character of the signature and confirm false. For a real delivery, use POST /api/v1/webhooks/{id}/test, up to 10 times per hour per endpoint. The quickstart shows the first call end to end.
Frequently asked questions
Can I receive the webhook directly as a Java object?
Not if you want to check the signature. Spring converts the JSON before you see the bytes. Receive byte[], check the HMAC and only then parse the JSON.
Why MessageDigest.isEqual and not Arrays.equals?
Because isEqual examines every byte and its time does not depend on the content, as Java's documentation describes. Arrays.equals stops at the first different byte and leaks timing.
Does RestClient throw on 4xx and 5xx?
Yes, by default. Use onStatus to handle specific codes, or catch RestClientResponseException to read the status and error body.
What is the minimum Java version?
The example uses HexFormat, which requires Java 17. On older versions, change the hex decoding.
Fontes
Documentação oficial da Meta, conferida em 31 de outubro de 2026.