← Blog

·

WhatsApp Cloud API with Java (Spring Boot): Sending Messages and Webhooks from Scratch

Updated on October 29, 2026

To use the WhatsApp API with Java, you need two pieces: an HTTP client 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 processing the message. With Spring Boot, RestClient handles sending and a @RestController plus @Async handles the webhook, with no WhatsApp library at all.

This tutorial builds the project from scratch: sending text and template messages, a complete webhook, a bot that replies with buttons and a unit test for the signature. The code works directly with Meta or through Vectalk by changing two environment variables. If you prefer another language, see the Python with FastAPI and Node.js with Express versions.

How the flow works

  1. A customer sends a message to your number.
  2. Meta sends a POST with the event to your webhook.
  3. The controller validates the signature, returns 200 immediately and hands the event to an asynchronous service.
  4. The service decides on the reply and calls the Cloud API with RestClient.

The reply goes out inside the 24-hour customer service window opened by the customer’s message, so it can be free-form text or an interactive message. To start a conversation, you need an approved template. The concepts behind all this are in the official WhatsApp API guide.

What you need first

VariableWhat it isWhere to find it
PHONE_NUMBER_IDThe number’s ID on the Cloud APIApp Dashboard, WhatsApp section
ACCESS_TOKENToken with the whatsapp_business_messaging permissionPermanent system user access token
APP_SECRETThe app secret, used for the signatureApp settings > Basic
VERIFY_TOKENAny text you chooseYou define it and repeat it in the dashboard

Locally you need JDK 21 or later and Maven (the generated project already ships with mvnw). The code targets Spring Boot 4, which uses Jackson 3. It also works on Spring Boot 3.2 or later: just swap the JsonMapper import as noted in section 4.

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

1. Create the project

Generate the skeleton with Spring Initializr, using only the web dependency:

curl https://start.spring.io/starter.zip \
  -d type=maven-project -d language=java -d javaVersion=21 \
  -d dependencies=web -d groupId=br.exemplo -d artifactId=whatsapp-bot \
  -d packageName=br.exemplo.bot -d baseDir=whatsapp-bot -o whatsapp-bot.zip
unzip whatsapp-bot.zip && cd whatsapp-bot

Configure src/main/resources/application.properties to read everything from environment variables:

whatsapp.api-url=${API_URL:https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID:}/messages}
whatsapp.access-token=${ACCESS_TOKEN}
whatsapp.app-secret=${APP_SECRET:}
whatsapp.verify-token=${VERIFY_TOKEN}
whatsapp.webhook-key=${WEBHOOK_KEY:}
spring.threads.virtual.enabled=true

The last line turns on Java 21 virtual threads, which Spring Boot also uses in the executor for @Async tasks. API_URL points to Meta by default; the Vectalk section shows how to switch it.

All the files below live in src/main/java/br/exemplo/bot/.

2. Sending messages with RestClient

RestClient arrived in Spring Framework 6.1 and is the recommended synchronous option for HTTP calls. The client is built with RestClient.builder() because, in Spring Boot 4, the RestClient.Builder bean is only configured by spring-boot-starter-restclient, which the web starter doesn’t include. Create WhatsAppClient.java:

package br.exemplo.bot;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientResponseException;

@Component
public class WhatsAppClient {

    private static final Logger log = LoggerFactory.getLogger(WhatsAppClient.class);
    private final RestClient http;

    public WhatsAppClient(@Value("${whatsapp.api-url}") String apiUrl,
                          @Value("${whatsapp.access-token}") String token) {
        this.http = RestClient.builder()
                .baseUrl(apiUrl)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token)
                .build();
    }

    public String send(Map<String, Object> payload) {
        Map<String, Object> body = new HashMap<>(payload);
        body.put("messaging_product", "whatsapp");
        try {
            return http.post()
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(body)
                    .retrieve()
                    .body(String.class);
        } catch (RestClientResponseException e) {
            log.error("API {}: {}", e.getStatusCode(), e.getResponseBodyAsString());
            throw e;
        }
    }

    public String sendText(Map<String, String> dest, String text) {
        Map<String, Object> p = new HashMap<>(dest);
        p.put("type", "text");
        p.put("text", Map.of("body", text));
        return send(p);
    }

    public String sendTemplate(String to, String name, String lang, List<String> bodyParams) {
        var params = bodyParams.stream()
                .map(v -> Map.of("type", "text", "text", v))
                .toList();
        return send(Map.of(
                "to", to,
                "type", "template",
                "template", Map.of(
                        "name", name,
                        "language", Map.of("code", lang),
                        "components", List.of(Map.of("type", "body", "parameters", params)))));
    }

    public String sendButtons(Map<String, String> dest, String text, Map<String, String> buttons) {
        var list = buttons.entrySet().stream()
                .map(b -> Map.of("type", "reply",
                        "reply", Map.of("id", b.getKey(), "title", b.getValue())))
                .toList();
        Map<String, Object> p = new HashMap<>(dest);
        p.put("type", "interactive");
        p.put("interactive", Map.of(
                "type", "button",
                "body", Map.of("text", text),
                "action", Map.of("buttons", list)));
        return send(p);
    }

}

Three details that save debugging time:

  • Meta’s error body goes to the log. RestClientResponseException carries the JSON with code and error_data.details. Without it, all you get is “400 Bad Request”. The WhatsApp API error codes table helps you read it.
  • The recipient is a Map. Usually it is {"to": "5511..."}, but users with a username may arrive with only a BSUID, and then the send uses recipient. The topic is covered in usernames and BSUID.
  • Template parameters in the right order. If the count doesn’t match the approved template, the API returns error 132000. See errors 132000 and 132012.

To test sending on its own, an approved template is enough: client.sendTemplate("5511999999999", "hello_world", "en_US", List.of()).

3. Webhook verification (GET)

When you save the URL in the dashboard, Meta sends a GET with hub.mode=subscribe, hub.verify_token and hub.challenge. If the token matches, respond 200 with the hub.challenge value as plain text. Any other response leaves the webhook unverified, and no events are sent.

Create WebhookController.java:

package br.exemplo.bot;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/webhook")
public class WebhookController {

    private final String verifyToken;
    private final String webhookKey;
    private final SignatureVerifier signature;
    private final MessageProcessor processor;

    public WebhookController(@Value("${whatsapp.verify-token}") String verifyToken,
                             @Value("${whatsapp.webhook-key}") String webhookKey,
                             SignatureVerifier signature,
                             MessageProcessor processor) {
        this.verifyToken = verifyToken;
        this.webhookKey = webhookKey;
        this.signature = signature;
        this.processor = processor;
    }

    @GetMapping(produces = MediaType.TEXT_PLAIN_VALUE)
    public ResponseEntity<String> verify(
            @RequestParam(name = "hub.mode", required = false) String mode,
            @RequestParam(name = "hub.verify_token", required = false) String token,
            @RequestParam(name = "hub.challenge", required = false) String challenge) {
        if ("subscribe".equals(mode) && verifyToken.equals(token)) {
            return ResponseEntity.ok(challenge);
        }
        return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
    }

    @PostMapping
    public ResponseEntity<Void> receive(
            @RequestBody byte[] body,
            @RequestHeader(name = "X-Hub-Signature-256", required = false) String header,
            @RequestParam(name = "key", required = false) String key) {
        if (!webhookKey.isEmpty() && !webhookKey.equals(key)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (!signature.isValid(body, header)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        processor.process(body); // @Async: returns immediately
        return ResponseEntity.ok().build();
    }
}

The key piece is @RequestBody byte[] body. It hands you the bytes exactly as they arrived, without going through Jackson. That is mandatory for the signature, as the next section explains.

4. Validate the X-Hub-Signature-256 signature

Every POST from Meta carries X-Hub-Signature-256: sha256=<hash>, where the hash is an HMAC-SHA256 of the body, computed with the app secret. Without this check, anyone who discovers the URL can fake customer messages. Create SignatureVerifier.java:

package br.exemplo.bot;

import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.HexFormat;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class SignatureVerifier {

    private final String appSecret;

    public SignatureVerifier(@Value("${whatsapp.app-secret}") String appSecret) {
        this.appSecret = appSecret;
    }

    public boolean isValid(byte[] body, String header) {
        if (appSecret.isEmpty()) {
            return true; // no secret configured (e.g. via Vectalk, protected by WEBHOOK_KEY)
        }
        if (header == null) {
            return false;
        }
        String expected = "sha256=" + hmacHex(body);
        return MessageDigest.isEqual(
                expected.getBytes(StandardCharsets.UTF_8),
                header.getBytes(StandardCharsets.UTF_8));
    }

    String hmacHex(byte[] body) {
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            return HexFormat.of().formatHex(mac.doFinal(body));
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
}

Two things to watch:

  • Always the original bytes. If the controller received an already deserialized object and you serialized it again to compute the HMAC, any difference in whitespace or field order would change the hash.
  • Constant-time comparison. MessageDigest.isEqual doesn’t stop at the first differing byte, which avoids leaking information through response timing.

The article on how to validate the webhook signature digs into the most common mistakes.

5. Process in the background

Meta expects a 200. If delivery fails, it retries immediately and then a few more times, with decreasing frequency, for up to 7 days. That is why processing leaves the request thread and ignores IDs it has already seen. First, enable @Async on the main class (WhatsappBotApplication.java, generated by Initializr):

package br.exemplo.bot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class WhatsappBotApplication {
    public static void main(String[] args) {
        SpringApplication.run(WhatsappBotApplication.class, args);
    }
}

Now the payload types, in WebhookPayload.java. Records with only the fields we use. The JsonMapper configured by Spring Boot doesn’t fail on unknown properties, so the rest of the payload is ignored:

package br.exemplo.bot;

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

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,
                          @JsonProperty("from_user_id") String fromUserId,
                          String id, String type, Text text, Interactive interactive) {}

    public record Text(String body) {}

    public record Interactive(String type, @JsonProperty("button_reply") Reply buttonReply) {}

    public record Reply(String id, String title) {}
}

The @JsonProperty annotation stays in the com.fasterxml.jackson.annotation package even in Jackson 3. Finally, MessageProcessor.java, with the bot logic:

package br.exemplo.bot;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import tools.jackson.databind.json.JsonMapper; // Spring Boot 3.x: com.fasterxml.jackson.databind.ObjectMapper

@Service
public class MessageProcessor {

    private static final Logger log = LoggerFactory.getLogger(MessageProcessor.class);
    private static final Map<String, String> ANSWERS = Map.of(
            "hours", "We're open Monday to Friday, 9 a.m. to 6 p.m.",
            "pricing", "See the full price list at https://example.com/pricing",
            "human", "Sure! An agent will continue the conversation right here.");

    private static final Map<String, String> MENU = new LinkedHashMap<>();
    static { // LinkedHashMap keeps the button order
        MENU.put("hours", "Opening hours");
        MENU.put("pricing", "Pricing");
        MENU.put("human", "Talk to an agent");
    }

    private final JsonMapper mapper;
    private final WhatsAppClient client;
    private final Set<String> processed = ConcurrentHashMap.newKeySet(); // in production: Redis or a database

    public MessageProcessor(JsonMapper mapper, WhatsAppClient client) {
        this.mapper = mapper;
        this.client = client;
    }

    @Async
    public void process(byte[] body) {
        WebhookPayload payload = mapper.readValue(body, WebhookPayload.class);
        for (var entry : nonNull(payload.entry())) {
            for (var change : nonNull(entry.changes())) {
                if (change.value() == null) continue;
                for (var msg : nonNull(change.value().messages())) {
                    if (!processed.add(msg.id())) continue; // Meta may resend it
                    try {
                        handle(msg);
                    } catch (RuntimeException e) {
                        log.error("failed to reply to {}", msg.id(), e);
                    }
                }
            }
        }
    }

    private void handle(WebhookPayload.Message msg) {
        Map<String, String> dest = msg.from() != null
                ? Map.of("to", msg.from())
                : Map.of("recipient", msg.fromUserId());

        if ("text".equals(msg.type())) {
            String text = msg.text().body().strip().toLowerCase();
            if (Set.of("hi", "hello", "hey", "menu").contains(text)) {
                client.sendButtons(dest, "Hi! How can I help?", MENU);
            } else {
                client.sendText(dest, "Sorry, I didn't get that. Type *menu* to see the options.");
            }
        } else if ("interactive".equals(msg.type())
                && "button_reply".equals(msg.interactive().type())) {
            String choice = msg.interactive().buttonReply().id();
            client.sendText(dest, ANSWERS.getOrDefault(choice, "Invalid option."));
        } else {
            client.sendText(dest, "For now I only understand text and buttons.");
        }
    }

    private static <T> List<T> nonNull(List<T> list) {
        return Optional.ofNullable(list).orElse(List.of());
    }
}

A few notes on this code:

  • @Async only works when called from another bean. The controller calls processor.process(...), which goes through the Spring proxy and runs on another thread. If you called process from inside MessageProcessor itself, it would run synchronously.
  • Status events (sent, delivered, read, failed) arrive on the same webhook, under value.statuses, and this bot ignores them. To handle them, see message status via webhook.
  • In Jackson 3, read exceptions are RuntimeExceptions, so readValue doesn’t require a try/catch. On Spring Boot 3.x with ObjectMapper, wrap the call and handle IOException.

Reply button limits: up to 3 buttons, title up to 20 characters and id up to 256. For lists and other formats, see interactive messages.

6. Unit test for the signature

The signature is the part that breaks most often in production, so it is worth a test that depends on neither Spring nor the network. In src/test/java/br/exemplo/bot/SignatureVerifierTest.java:

package br.exemplo.bot;

import static org.junit.jupiter.api.Assertions.*;

import java.nio.charset.StandardCharsets;

import org.junit.jupiter.api.Test;

class SignatureVerifierTest {

    private final SignatureVerifier verifier = new SignatureVerifier("test-secret");
    private final byte[] body = "{\"entry\":[]}".getBytes(StandardCharsets.UTF_8);

    @Test
    void acceptsValidSignature() {
        String header = "sha256=" + verifier.hmacHex(body);
        assertTrue(verifier.isValid(body, header));
    }

    @Test
    void rejectsTamperedBody() {
        String header = "sha256=" + verifier.hmacHex(body);
        byte[] tampered = "{\"entry\": []}".getBytes(StandardCharsets.UTF_8);
        assertFalse(verifier.isValid(tampered, header));
    }

    @Test
    void rejectsMissingHeader() {
        assertFalse(verifier.isValid(body, null));
    }
}

The second test shows why the original bytes matter: a single extra space in the JSON is enough to invalidate the signature. Run it with ./mvnw test.

7. Run and test locally

export VERIFY_TOKEN="any-text-you-like"
export ACCESS_TOKEN="EAAG..."
export APP_SECRET="your-app-secret"
export PHONE_NUMBER_ID="123456789012345"
./mvnw spring-boot:run

In another terminal, test verification and a signed event without depending on Meta:

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

BODY='{"entry":[{"changes":[{"value":{"messages":[{"from":"5511999999999","id":"wamid.test1","type":"text","text":{"body":"menu"}}]}}]}]}'
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$APP_SECRET" | awk '{print $NF}')
curl -i -X POST http://localhost:8080/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 right away, and then the bot sends the menu to the number in the from field (use your own test number). A 401 means the signature is wrong; check that APP_SECRET is the same in both terminals.

To receive real events, Meta requires a public URL with a valid TLS certificate (self-signed won’t work). In production, put a reverse proxy with HTTPS in front of the application, such as Nginx, Caddy or your cloud’s load balancer. In development, a tunnel does the job: see test the webhook locally with ngrok. Then, under App Dashboard > WhatsApp > Configuration, enter the callback URL and the verify token and subscribe to the messages field.

Production checklist

  • Persistent deduplication. The in-memory Set disappears on restart and isn’t shared across replicas. Use Redis or a table with a unique key on the message id.
  • A real queue. @Async is fine for quick replies. If processing calls AI or slow systems, publish the event to a queue (RabbitMQ, Kafka, SQS) and consume it in another service. If the webhook will run on serverless functions, see serverless webhook.
  • Secrets out of the code. Keep the token and app secret in environment variables or a secrets vault.

How to do it with Vectalk

Vectalk is a proxy for the official WhatsApp Cloud API: send payloads and webhook events are the same as Meta’s, so the project works without changing its logic. Three things change:

  1. URL and token. Set API_URL=https://apis.vectalk.com.br/api/messages and use an instance token generated in Vectalk as ACCESS_TOKEN. With it, the phone_number_id is resolved automatically.
  2. Registering the webhook via API. Register the URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name. You can have several URLs per instance.
  3. Protecting the endpoint. The Vectalk webhook documentation doesn’t describe a signature header. Leave APP_SECRET empty, set WEBHOOK_KEY to a long random value and register the URL as https://bot.yourcompany.com/webhook?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": "Java Bot"}'

Vectalk expects a 200 in under 20 seconds and resends the event if it doesn’t get one, which the deduplication already covers. Create your account at apps.vectalk.com.br/register and see the other endpoints in the documentation.

Frequently asked questions

Is there an official Meta SDK for Java?

You don’t need one. The Cloud API is HTTP with JSON, and Spring’s RestClient covers sending. Calling the API directly also lets you use new features as soon as Meta documents them, without waiting for a library update.

Can I use WebClient instead of RestClient?

Yes. WebClient makes sense if the application is already reactive (Spring WebFlux). In a Spring MVC application with virtual threads, the synchronous RestClient is simpler to read and debug, which is why this tutorial uses it.

Why doesn’t the signature match if APP_SECRET is correct?

In most cases, the HMAC is being computed over a body different from the one received: a filter that reads and rewrites the body, an object that was deserialized and serialized again, or a charset conversion. Receive byte[] in the controller and compute the hash over those bytes.

Can the bot start the conversation?

Free-form text 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 sendTemplate with an approved template.


Official sources consulted on October 29, 2026: Create a webhook endpoint (Meta), Webhooks overview (Meta), Interactive reply buttons (Meta), Pricing (Meta), Spring Framework: REST Clients, Spring Boot: Task Execution and Scheduling, Introducing Jackson 3 support in Spring, 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.