WhatsApp API in Java: HttpClient, Templates and Webhooks

Send WhatsApp messages from Java with the official Cloud API: java.net.http for text and templates, async sends, and a webhook with the signature check.

Illustration: a Java class in an editor next to a phone receiving a WhatsApp delivery update (sample data)

To send a WhatsApp message from Java, use the JDK’s java.net.http.HttpClient to POST JSON to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with a Bearer access token. Meta’s Cloud API is plain HTTPS, so you don’t need a WhatsApp SDK: the JDK handles the HTTP, and Jackson builds and reads the JSON.

This guide gives one compiled, tested Java class: a send helper, a text message, a template message, error handling, asynchronous sends with CompletableFuture, and a webhook on the JDK’s built-in HttpServer that answers Meta’s handshake and checks the X-Hub-Signature-256 signature. A Spring Boot version of the webhook follows. It uses Graph API v27.0, the latest in Meta’s changelog (released 4 November 2026). For other languages, see the Python, Node.js and C# guides.

Key takeaways

  • Meta doesn’t publish a Java SDK for the Cloud API. Its own Java tutorial uses java.net.http directly.
  • You need Java 17 or later for this code (HexFormat), and one dependency: Jackson for JSON.
  • Use sendAsync or virtual threads (Java 21) in production, so a slow call never blocks a request thread.
  • For the webhook, hash the raw request bytes with your app secret and compare with MessageDigest.isEqual.
  • Community Java libraries aren’t Meta’s. Avoid any that log in to WhatsApp Web: they can get a number banned.

Is there an official WhatsApp Java SDK?

No. Meta’s Cloud API documentation describes HTTP requests only, and Meta’s own developer blog post on adding WhatsApp to Java projects uses the JDK’s HTTP client with Java 11 or greater, no SDK. That’s the honest answer to the “WhatsApp API Java SDK” search:

OptionWho makes itWhen to use it
java.net.http plus Jackson (this guide)The JDK and Jackson; you write about 20 linesMost projects: always matches Meta’s current format
Community Cloud API wrappers on GitHub or MavenIndependent developers, not MetaIf you want typed classes; check it calls graph.facebook.com and keeps up with new versions
Libraries that drive WhatsApp WebIndependent developersNever for a business number: not the official API

WhatsApp says unofficial apps break its Terms of Service and can lead to a ban; more in official vs unofficial WhatsApp APIs. The Cloud API itself costs nothing extra to call from Java. You pay mainly for the messages you send, as explained in is the WhatsApp API free?.

What you need before you start

  • Java 17 or later. HttpClient arrived in Java 11; HexFormat, used for the signature, in Java 17.
  • Jackson: add com.fasterxml.jackson.core:jackson-databind (a 2.x release) with Maven or Gradle.
  • A phone number ID, not the phone number itself; see how to find your phone number ID.
  • A permanent system-user access token. The one in API Setup is temporary; the Cloud API setup guide shows how to make a permanent one.
  • Your app secret and a verify token you invent, for the webhook, and a test recipient who has agreed to hear from you, such as your own phone on Meta’s test number.

The code reads four environment variables: WHATSAPP_TOKEN, PHONE_NUMBER_ID, APP_SECRET and VERIFY_TOKEN.

A send helper with java.net.http

Create WhatsApp.java. Imports go at the top (com.fasterxml.jackson.databind.*, java.net.*, java.net.http.*, java.io.*, java.nio.charset.StandardCharsets, java.security.*, java.time.Duration, java.util.*, java.util.concurrent.*, javax.crypto.Mac, javax.crypto.spec.SecretKeySpec and com.sun.net.httpserver.*). Inside public class WhatsApp { … }:

LineWhatsApp.java
1static final String API_VERSION = "v27.0";
2static final String TOKEN = System.getenv("WHATSAPP_TOKEN"), APP_SECRET = System.getenv("APP_SECRET"), VERIFY_TOKEN = System.getenv("VERIFY_TOKEN");
3static final URI MESSAGES = URI.create("https://graph.facebook.com/" + API_VERSION + "/" + System.getenv("PHONE_NUMBER_ID") + "/messages");
4static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
5static final ObjectMapper JSON = new ObjectMapper();
6static HttpRequest request(Map<String, Object> payload) throws IOException {
7return HttpRequest.newBuilder(MESSAGES).timeout(Duration.ofSeconds(10)).header("Authorization", "Bearer " + TOKEN).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(payload))).build(); }
8static JsonNode read(HttpResponse<String> res) throws IOException {
9JsonNode data = JSON.readTree(res.body());
10if (res.statusCode() / 100 != 2) throw new WhatsAppException(data.path("error"));
11return data; }
12static JsonNode send(Map<String, Object> payload) throws IOException, InterruptedException {
13return read(HTTP.send(request(payload), HttpResponse.BodyHandlers.ofString())); }

One shared HttpClient reuses connections, and writeValueAsString escapes quotes and line breaks, so never build the JSON by joining strings. Keep the version in API_VERSION and check the Graph API changelog when you build.

Send a text message

Free-form text reaches a customer only inside the 24-hour customer service window, which opens when they message you. Map.of builds the body in Meta’s exact field names:

StepJava
SendJsonNode data = send(Map.of("messaging_product", "whatsapp", "recipient_type", "individual", "to", "919800000000", "type", "text", "text", Map.of("preview_url", false, "body", "Hi Priya, your appointment is confirmed for 4 pm tomorrow.")));
Message IDString id = data.path("messages").path(0).path("id").asText();
  • to is the number with its country code. The one above is a placeholder.
  • Save the message ID (wamid…): delivery and read statuses at your webhook refer to it.
  • A 200 means Meta accepted the request, not that it was delivered. Statuses arrive later.

Outside the window you get error 131047; see the WhatsApp 24-hour rule.

Send a template message

Approved templates are the only messages you can send outside a customer service window. For a template order_update with the body “Hi {{1}}, your order {{2}} has shipped.”:

StepJava
Body valuesList<Map<String, Object>> params = List.of(Map.of("type", "text", "text", "Priya"), Map.of("type", "text", "text", "ORD-1042"));
TemplateMap<String, Object> template = Map.of("name", "order_update", "language", Map.of("code", "en"), "components", List.of(Map.of("type", "body", "parameters", params)));
Sendsend(Map.of("messaging_product", "whatsapp", "recipient_type", "individual", "to", "919800000000", "type", "template", "template", template));
Named parameterMap.of("type", "text", "parameter_name", "first_name", "text", "Priya"), for templates created with named variables

Positional values follow the order of {{1}}, {{2}}; named values can be in any order. Meta only sends templates whose status is APPROVED, and the name and language code must match exactly. If you prefer typed code, Java records work too: Jackson 2.12 and later serialises them, and PropertyNamingStrategies.SNAKE_CASE turns messagingProduct into messaging_product. Media headers and buttons are extra components, shown in how to send a WhatsApp template message with the API.

Errors and asynchronous sends

The helper throws a small unchecked exception that carries Meta’s numeric code. Add it inside the class:

LineWhatsApp.java
1static class WhatsAppException extends RuntimeException { final int code; final String details; final String traceId;
2WhatsAppException(JsonNode e) { super(e.path("message").asText("WhatsApp API error")); code = e.path("code").asInt(); details = e.path("error_data").path("details").asText(""); traceId = e.path("fbtrace_id").asText(""); } }
Usetry { send(payload); } catch (WhatsAppException e) { if (e.code == 131047) { /* send a template */ } else log(e.code + " " + e.details + " " + e.traceId); }
CodeMeaningWhat to do
190Access token expired or invalidUse a permanent system-user token
131047More than 24 hours since the customer last messagedSend an approved template
132001Template doesn’t exist in that language or isn’t approvedCopy the name and language code from WhatsApp Manager
130429Throughput limit reachedQueue sends and retry with a growing delay

Meta’s Java tutorial recommends asynchronous calls in production, so the calling thread isn’t blocked while Meta answers. The JDK client does this with sendAsync:

LineWhatsApp.java
1static CompletableFuture<JsonNode> sendAsync(Map<String, Object> payload) throws IOException {
2return HTTP.sendAsync(request(payload), HttpResponse.BodyHandlers.ofString()).thenApply(res -> { try { return read(res); } catch (IOException e) { throw new UncheckedIOException(e); } }); }
UsesendAsync(payload).thenAccept(d -> save(d.path("messages").path(0).path("id").asText())).exceptionally(err -> { log(err.getCause()); return null; });

On Java 21 or later there’s a simpler route: keep the blocking send() and run each send on a virtual thread, for example with Executors.newVirtualThreadPerTaskExecutor(). The full list of codes is in WhatsApp API error codes.

A webhook with the JDK’s built-in HttpServer

Meta sends customer messages and delivery statuses to a URL you own: a GET handshake once, then signed POSTs. The signature is sha256= plus an HMAC-SHA256 of the raw body keyed with your app secret. The JDK’s com.sun.net.httpserver is enough for this, with no framework. Add to the class:

LineWhatsApp.java
1public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/webhook", WhatsApp::webhook); server.start(); }
2static void webhook(HttpExchange ex) throws IOException {
3if ("GET".equals(ex.getRequestMethod())) { Map<String, String> q = query(ex.getRequestURI().getRawQuery());
4boolean ok = "subscribe".equals(q.get("hub.mode")) && VERIFY_TOKEN != null && VERIFY_TOKEN.equals(q.get("hub.verify_token"));
5reply(ex, ok ? 200 : 403, ok ? q.getOrDefault("hub.challenge", "") : ""); return; }
6byte[] body = ex.getRequestBody().readAllBytes();
7if (!"POST".equals(ex.getRequestMethod()) || !signatureOk(body, ex.getRequestHeaders().getFirst("X-Hub-Signature-256"))) { reply(ex, 401, ""); return; }
8reply(ex, 200, "OK");
9for (JsonNode entry : JSON.readTree(body).path("entry")) for (JsonNode change : entry.path("changes")) { JsonNode value = change.path("value");
10for (JsonNode m : value.path("messages")) System.out.println("message " + m.path("id").asText() + " from " + m.path("from").asText() + ": " + m.path("text").path("body").asText());
11for (JsonNode s : value.path("statuses")) System.out.println("status " + s.path("id").asText() + ": " + s.path("status").asText()); } }
12static boolean signatureOk(byte[] body, String header) { if (header == null || APP_SECRET == null) return false;
13try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(APP_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
14byte[] expected = ("sha256=" + HexFormat.of().formatHex(mac.doFinal(body))).getBytes(StandardCharsets.UTF_8);
15return MessageDigest.isEqual(expected, header.getBytes(StandardCharsets.UTF_8)); } catch (GeneralSecurityException e) { throw new IllegalStateException(e); } }
16static Map<String, String> query(String raw) { Map<String, String> out = new HashMap<>(); if (raw == null) return out;
17for (String pair : raw.split("&")) { int i = pair.indexOf('='); if (i > 0) out.put(URLDecoder.decode(pair.substring(0, i), StandardCharsets.UTF_8), URLDecoder.decode(pair.substring(i + 1), StandardCharsets.UTF_8)); } return out; }
18static void reply(HttpExchange ex, int status, String text) throws IOException { byte[] out = text.getBytes(StandardCharsets.UTF_8);
19ex.sendResponseHeaders(status, out.length == 0 ? -1 : out.length); try (OutputStream os = ex.getResponseBody()) { os.write(out); } }
  1. Handshake (lines 3 to 5): Meta sends hub.mode=subscribe, your verify token and a random hub.challenge. Return the challenge with 200, or 403 for a wrong token.
  2. Signature (lines 6, 7 and 12 to 15): the hash covers the exact bytes read from the request. MessageDigest.isEqual compares in constant time and returns false when the lengths differ.
  3. Answer first (line 8): the 200 goes out before processing. One POST can carry several entries and changes, and Jackson’s path() returns an empty node for anything missing, so the loops don’t throw.
  4. Threads: with no executor set, HttpServer handles requests one at a time. On Java 21, add server.setExecutor(Executors.newVirtualThreadPerTaskExecutor()); before server.start().

The same webhook in Spring Boot

If your app already runs on Spring Boot, the only trick is to take the body as byte[], not as a parsed object, so the signature is checked on the original bytes. Reuse signatureOk and VERIFY_TOKEN from above, with the controller in the same package as WhatsApp:

LineWebhookController.java
1@RestController public class WebhookController {
2@GetMapping("/webhook") public ResponseEntity<String> verify(@RequestParam("hub.mode") String mode, @RequestParam("hub.verify_token") String token, @RequestParam("hub.challenge") String challenge) {
3return "subscribe".equals(mode) && token.equals(WhatsApp.VERIFY_TOKEN) ? ResponseEntity.ok(challenge) : ResponseEntity.status(403).build(); }
4@PostMapping("/webhook") public ResponseEntity<Void> receive(@RequestBody byte[] body, @RequestHeader(value = "X-Hub-Signature-256", required = false) String signature) {
5if (!WhatsApp.signatureOk(body, signature)) return ResponseEntity.status(401).build();
6events.publish(body); return ResponseEntity.ok().build(); } }

events.publish stands for your own hand-off, such as a queue or an @Async service, so the controller answers quickly. To go live, deploy behind a public HTTPS address with a valid certificate (Meta doesn’t accept self-signed ones), save https://your-domain/webhook and your verify token as the callback URL in your Meta app’s dashboard, and subscribe to the messages field.

Payloads and statuses are explained in WhatsApp Cloud API webhooks, and if nothing arrives, see WhatsApp webhook not receiving messages.

Java with Automate AI, or no code at all

If you’d rather not host the webhook and token handling, Automate AI connects your number to Meta and receives the webhooks for you. Your team gets a shared inbox, campaigns that send approved templates to groups now or on a schedule, and chatbots built without code.

For Java developers, Automate AI has its own REST API, with API keys, endpoints for contacts, messages, templates, campaigns and automations, developer webhooks with logs, and a Postman collection. There’s no Java SDK, but the same HttpClient pattern works against it. The API and webhooks are included on the AI + Automation Plan and Series 4; see the WhatsApp Business API page and pricing.

Frequently asked questions

How do I send a WhatsApp message with Java?

Build an HttpRequest with java.net.http, POST it to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with an Authorization: Bearer header, and send a JSON body with messaging_product: "whatsapp", to, type and the message object. Jackson turns a Map into that JSON.

Is there an official WhatsApp Java SDK?

Meta doesn’t publish one for the Cloud API. Meta’s own Java tutorial uses the JDK’s HTTP client directly. Libraries on GitHub and Maven are community projects, not Meta’s.

Which Java version do I need?

HttpClient needs Java 11, which is what Meta’s tutorial asks for. This guide uses Java 17 for HexFormat, and Java 21 if you want virtual threads.

Why does my Java webhook fail the signature check?

Usually because the body was parsed or converted to a string before hashing. Read the raw bytes (readAllBytes() or @RequestBody byte[] in Spring) and hash exactly those with your app secret.

Which Graph API version should I use?

The latest in Meta’s changelog. On 27 November 2026 that is v27.0, released on 4 November 2026. Keep it in one constant so upgrading is a one-line change.

Sources

  1. Meta: Send messages
  2. Meta: Templates overview
  3. Meta: Create a webhook endpoint
  4. Meta for Developers blog: Adding WhatsApp to your Java projects
  5. Meta: Graph API changelog
  6. WhatsApp Help Center: About unofficial WhatsApp apps

WhatsApp rules and prices change. We check these guides against Meta’s documentation, but always confirm current terms with Meta before you rely on them. Questions? Message us on WhatsApp at +91 836 977 8812.