Send WhatsApp Messages from Java (Spring Boot) — API Client and Webhook Example
Spring Boot already ships with everything needed to talk to the TextMeFlow API — no third-party SDK, no code generation. RestClient (built into Spring Framework since 6.1) handles sending messages, a small retry loop handles rate limits, and javax.crypto.Mac verifies inbound webhooks. This guide walks through all three with code you can drop straight into a service class.
Before you start
- Create a free TextMeFlow account — 50 messages a month, forever, no credit card and no Meta Business verification.
- Scan the QR code from the portal with the phone that holds the WhatsApp number you want to send from.
- Copy your API key from the dashboard.
The full endpoint reference lives at /en/docs/api; everything below targets POST /v1/messages.
Sending a message
A minimal client is a RestClient bean, a record for the request body, and a bearer token:
public record SendRequest(String to, String text, String mediaUrl) {}
public record SendResponse(String messageId, String status) {}
@Service
public class TextMeFlowClient {
private final RestClient restClient;
public TextMeFlowClient(@Value("${textmeflow.api-key}") String apiKey) {
this.restClient = RestClient.builder()
.baseUrl("https://api.textmeflow.eu/v1")
.defaultHeader("Authorization", "Bearer " + apiKey)
.build();
}
public SendResponse send(SendRequest message) {
return restClient.post()
.uri("/messages")
.contentType(MediaType.APPLICATION_JSON)
.body(message)
.retrieve()
.body(SendResponse.class);
}
}
Keep the to field in E.164 format (+ and country code) — anything else gets rejected with a 422. mediaUrl is optional and accepts any publicly reachable file up to 100 MB (image, PDF, voice note); leave it null for a plain text message. A 202 means the message is queued, not delivered yet — the messageId in the response is what you use to check real status later.
Retrying on 429 without hammering the API
TextMeFlow rate-limits by design — a burst cap per minute and an hourly ceiling per plan, documented on the rate limits page. A 429 response body includes reason (burst_exceeded or hourly_exceeded) and retryAfterSeconds, so there's no need to guess a backoff interval:
public record RateLimitBody(String reason, int retryAfterSeconds) {}
public SendResponse sendWithRetry(SendRequest message, int maxAttempts) throws InterruptedException {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return restClient.post()
.uri("/messages")
.contentType(MediaType.APPLICATION_JSON)
.body(message)
.retrieve()
.body(SendResponse.class);
} catch (HttpClientErrorException.TooManyRequests ex) {
RateLimitBody rl = ex.getResponseBodyAs(RateLimitBody.class);
long waitMs = rl.retryAfterSeconds() * 1000L * attempt;
Thread.sleep(waitMs);
}
}
throw new IllegalStateException("gave up after " + maxAttempts + " attempts");
}
Five attempts is plenty in practice. Multiplying the hinted wait by the attempt number adds a safety margin on top of what the API already told you, without resorting to a fixed Thread.sleep(5000) that either wastes time or retries too soon. For the full reasoning on polling GET /v1/messages/{id} versus just trusting webhooks for delivery status, see the rate limits and status guide.
Receiving replies: a signed webhook handler
Every inbound WhatsApp reply gets POSTed to the endpoint you configure in /admin/webhook, signed with X-TextMeFlow-Signature: sha256=<hex> — an HMAC-SHA256 of the raw request body using the secret shown once at creation time. Binding the raw bytes (not a parsed DTO) is what makes the signature check valid:
@RestController
public class WebhookController {
@Value("${textmeflow.webhook-secret}")
private String secret;
@PostMapping("/webhooks/textmeflow")
public ResponseEntity<Void> handle(@RequestBody byte[] rawBody,
@RequestHeader("X-TextMeFlow-Signature") String signature,
@RequestHeader("X-TextMeFlow-Event-Id") String eventId) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
String expected = "sha256=" + HexFormat.of().formatHex(mac.doFinal(rawBody));
if (!MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8))) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
// INSERT ... ON CONFLICT (event_id) DO NOTHING, then hand off to an async handler.
return ResponseEntity.ok().build();
}
}
MessageDigest.isEqual runs in constant time, so there's no separate timing-safe comparison to write. X-TextMeFlow-Event-Id is stable across retries, so a unique constraint on that column is enough to avoid double-processing: TextMeFlow retries undelivered webhooks up to 5 times with increasing backoff, and anything but a 2xx within 10 seconds counts as a failed attempt. Return 200 immediately and push the actual work onto an @Async method or a queue — a slow handler looks identical to a timeout from TextMeFlow's side and gets retried needlessly. The full header list and payload shape are in the webhook docs; the signature mechanics are covered in more depth in verifying WhatsApp webhook signatures.
Wrapping up
A Spring Boot integration needs three things: a RestClient call with a bearer token, a retry loop that respects retryAfterSeconds, and a constant-time HMAC check on the way in — all of it built into the framework, no extra dependency to manage. Start free and you can have a send path and a webhook handler both running in under an hour.
Want to send WhatsApp messages via API yourself?
Free forever up to 50 messages/month. Scan a QR and send your first message within 5 minutes.
Free forever