WhatsApp API in Kotlin: Send Messages With Ktor and Coroutines

Send WhatsApp messages from Kotlin with the official Cloud API: Ktor client, data classes, coroutines, and a Ktor webhook that checks the signature.

Illustration: Kotlin code in an editor next to a phone receiving a WhatsApp order update (sample data)

To send a WhatsApp message from Kotlin, POST JSON to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with a Bearer access token, from server-side code. Meta’s Cloud API is plain HTTPS, so the Ktor client, @Serializable data classes and a suspend function are all you need. There’s no Kotlin SDK to install.

This guide covers typed messages with kotlinx.serialization, a coroutine send function, sending to many numbers safely, and a Ktor webhook that checks the X-Hub-Signature-256 signature, plus why none of it belongs in an Android app. It uses Graph API v27.0, the latest in Meta’s changelog (4 November 2026). If you’d rather use the JDK’s own HTTP client, see the Java guide.

Key takeaways

  • Meta publishes no Kotlin SDK. Call the Cloud API over HTTPS with the Ktor client (or any JVM HTTP client).
  • Model messages as data classes with @SerialName, and set encodeDefaults = true, or messaging_product silently disappears.
  • Send to many people with coroutines and a Semaphore, so you control how many calls run at once.
  • In the Ktor webhook, read the body as ByteArray, check the signature on those bytes, then parse.
  • Never put the access token in an Android app. The app calls your server, and your server calls Meta.

Is there a Kotlin WhatsApp SDK?

No. Meta’s Cloud API documentation describes HTTP requests only, so the honest answer to “WhatsApp API Kotlin library” is to use a normal HTTP client:

OptionGood forNote
Ktor client plus kotlinx.serialization (this guide)Kotlin services, coroutines all the way downSame team as the Ktor server used for the webhook
java.net.http or OkHttp from KotlinExisting JVM code, Spring BootThe Java guide shows this route
Libraries that log in to WhatsApp WebNothing a business should runNot the official API, and WhatsApp can ban the number

Why the unofficial route is risky: official vs unofficial WhatsApp APIs.

Set up the project

You need a Cloud API phone number ID (see how to find it), a permanent system-user access token (the Cloud API setup guide shows how), your app secret, a verify token you invent, and a test recipient such as your own phone on Meta’s test number. Add these to the build.gradle.kts of your existing JVM project (one that already has repositories { mavenCentral() }), with the versions current on Ktor’s and kotlinx.serialization’s pages today:

Linebuild.gradle.kts
1plugins { kotlin("jvm") version "2.4.10"; kotlin("plugin.serialization") version "2.4.10" }
2dependencies { val ktor = "3.6.2"
3implementation("io.ktor:ktor-client-core:$ktor"); implementation("io.ktor:ktor-client-cio:$ktor")
4implementation("io.ktor:ktor-client-content-negotiation:$ktor"); implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor")
5implementation("io.ktor:ktor-server-core:$ktor"); implementation("io.ktor:ktor-server-netty:$ktor") }

The code reads WHATSAPP_TOKEN, PHONE_NUMBER_ID, APP_SECRET and VERIFY_TOKEN from the environment.

Model the message with data classes

Kotlin property names are camelCase and Meta’s fields are snake_case, so @SerialName maps them. Put these in Models.kt:

LineModels.kt
1val WaJson = Json { encodeDefaults = true; explicitNulls = false; ignoreUnknownKeys = true }
2@Serializable data class Text(val body: String, @SerialName("preview_url") val previewUrl: Boolean = false)
3@Serializable data class Parameter(val text: String, val type: String = "text", @SerialName("parameter_name") val parameterName: String? = null)
4@Serializable data class Component(val type: String, val parameters: List<Parameter>)
5@Serializable data class Language(val code: String)
6@Serializable data class Template(val name: String, val language: Language, val components: List<Component> = emptyList())
7@Serializable data class OutgoingMessage(val to: String, val type: String, val text: Text? = null, val template: Template? = null, @SerialName("messaging_product") val messagingProduct: String = "whatsapp", @SerialName("recipient_type") val recipientType: String = "individual")
8@Serializable data class MessageId(val id: String)
9@Serializable data class SendResponse(val messages: List<MessageId> = emptyList())
10@Serializable data class GraphError(val message: String = "", val code: Int = 0, @SerialName("fbtrace_id") val traceId: String? = null)
11@Serializable data class ErrorEnvelope(val error: GraphError)

Line 1 matters. kotlinx.serialization skips properties still at their default unless encodeDefaults is on, so without it messaging_product never reaches Meta. explicitNulls = false drops null fields, and ignoreUnknownKeys lets you read Meta’s responses without modelling every field.

A suspend send function with the Ktor client

Ktor recommends reusing one client. Keep it in an object (imports come from io.ktor, kotlinx.coroutines, kotlinx.serialization, javax.crypto and java.security; your IDE adds them):

LineWhatsApp.kt
1class WhatsAppException(val error: GraphError) : Exception(error.message) { val code get() = error.code }
2object WhatsApp { private const val API_VERSION = "v27.0"
3private val token = System.getenv("WHATSAPP_TOKEN") ?: error("WHATSAPP_TOKEN not set"); private val url = "https://graph.facebook.com/$API_VERSION/${System.getenv("PHONE_NUMBER_ID")}/messages"
4private val client = HttpClient(CIO) { install(ContentNegotiation) { json(WaJson) }; install(HttpTimeout) { requestTimeoutMillis = 10_000 } }
5suspend fun send(message: OutgoingMessage): String {
6val res = client.post(url) { header(HttpHeaders.Authorization, "Bearer $token"); contentType(ContentType.Application.Json); setBody(message) }
7val raw = res.bodyAsText()
8if (!res.status.isSuccess()) throw WhatsAppException(runCatching { WaJson.decodeFromString<ErrorEnvelope>(raw).error }.getOrElse { GraphError("HTTP ${res.status.value}") })
9return WaJson.decodeFromString<SendResponse>(raw).messages.first().id } }
  • Line 8 matters. Ktor doesn’t treat 4xx and 5xx answers as errors unless you turn on expectSuccess, so check the status and throw Meta’s error code.
  • The return value is the message ID (wamid…). Save it: delivery and read statuses at your webhook refer to it. Success means Meta accepted the request, not that it was delivered.

Send a text and a template

Two small helpers inside the object, and a main to try them:

StepKotlin
Textsuspend fun sendText(to: String, body: String) = send(OutgoingMessage(to = to, type = "text", text = Text(body)))
Templatesuspend fun sendTemplate(to: String, name: String, lang: String, vararg values: String) = send(OutgoingMessage(to = to, type = "template", template = Template(name, Language(lang), listOf(Component("body", values.map { Parameter(it) })))))
Try itfun main() = runBlocking { println(WhatsApp.sendTemplate("+919800000000", "order_update", "en", "Priya", "ORD-1042")) }
Named variableParameter("Priya", parameterName = "first_name"), for templates created with named parameters
  • Text reaches a customer only inside the 24-hour customer service window, which opens when they message you. See the 24-hour rule.
  • Templates are what you send outside the window. Meta sends only templates whose status is APPROVED, and the name and language code must match exactly.
  • Positional values fill {{1}}, {{2}} in order; named values can come in any order. The to number is a placeholder.

Headers, media and buttons are extra components, shown in how to send a template message with the API.

Send to many numbers with coroutines

One coroutine per number is easy, and that’s the trap: 5,000 numbers would fire 5,000 calls at once. A Semaphore caps how many run together:

LineBulk.kt
1suspend fun sendAll(numbers: List<String>, limit: Int = 10): List<Result<String>> = coroutineScope {
2val gate = Semaphore(limit)
3numbers.map { n -> async { gate.withPermit {
4try { Result.success(WhatsApp.sendTemplate(n, "order_update", "en", "Priya", "ORD-1042")) } catch (e: WhatsAppException) { Result.failure(e) } catch (e: IOException) { Result.failure(e) }
5} } }.awaitAll() }

Catching Meta’s errors and IOException (which covers network failures and Ktor’s request timeout) keeps one bad number from cancelling the batch, without breaking cancellation as runCatching would. Then act on the code:

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 instead
132001Template missing in that language, or not approvedCopy the name and language code from WhatsApp Manager
130429Throughput limit reachedLower limit, wait and retry with a growing delay

Every marketing recipient must have opted in to hear from your business; see WhatsApp opt-in. The full list of codes is in WhatsApp API error codes.

A webhook with the Ktor server

Meta sends customer messages and delivery statuses to a URL you own: a GET handshake once, then signed POSTs. The signature header is sha256= plus an HMAC-SHA256 of the body, keyed with your app secret. Data classes for the payload, with defaults so missing parts don’t throw:

LineWebhook.kt (payload)
1@Serializable data class WebhookPayload(val entry: List<Entry> = emptyList())
2@Serializable data class Entry(val changes: List<Change> = emptyList())
3@Serializable data class Change(val field: String = "", val value: ChangeValue = ChangeValue())
4@Serializable data class ChangeValue(val messages: List<InMessage> = emptyList(), val statuses: List<Status> = emptyList())
5@Serializable data class InMessage(val id: String, val from: String, val type: String, val text: Text? = null)
6@Serializable data class Status(val id: String, val status: String)

The server, the signature check and a channel that hands work to a background coroutine:

LineWebhook.kt (server)
1val APP_SECRET: String? = System.getenv("APP_SECRET"); val VERIFY_TOKEN: String? = System.getenv("VERIFY_TOKEN")
2fun signatureOk(body: ByteArray, header: String?): Boolean { val secret = APP_SECRET ?: return false; if (header == null) return false
3val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(secret.toByteArray(), "HmacSHA256")) }
4val expected = "sha256=" + mac.doFinal(body).joinToString("") { "%02x".format(it) }
5return MessageDigest.isEqual(expected.toByteArray(), header.toByteArray()) }
6fun main() { embeddedServer(Netty, port = 8080) { val events = Channel<WebhookPayload>(Channel.BUFFERED)
7launch { for (p in events) p.entry.flatMap { it.changes }.forEach { c -> c.value.messages.forEach { println("${it.from}: ${it.text?.body}") }; c.value.statuses.forEach { println("${it.id} ${it.status}") } } }
8routing { get("/webhook") { val q = call.request.queryParameters
9if (q["hub.mode"] == "subscribe" && VERIFY_TOKEN != null && q["hub.verify_token"] == VERIFY_TOKEN) call.respondText(q["hub.challenge"].orEmpty()) else call.respond(HttpStatusCode.Forbidden) }
10post("/webhook") { val body = call.receive<ByteArray>()
11if (!signatureOk(body, call.request.headers["X-Hub-Signature-256"])) { call.respond(HttpStatusCode.Unauthorized); return@post }
12call.respond(HttpStatusCode.OK); events.send(WaJson.decodeFromString<WebhookPayload>(body.decodeToString())) } } }.start(wait = true) }
  1. Handshake (lines 8 and 9): 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. Raw bytes first (lines 10 and 11): the hash must cover exactly what Meta sent, so receive a ByteArray and check it before parsing. MessageDigest.isEqual compares without leaking timing and returns false when the lengths differ.
  3. Answer, then work (lines 6, 7 and 12): the 200 goes out first and the payload goes into a channel. The coroutine on line 7 runs in the application’s scope, so slow work never holds up Meta’s request.

To go live, deploy behind HTTPS with a valid certificate (Meta doesn’t accept self-signed ones), save https://your-domain/webhook and your verify token in your Meta app’s dashboard, and subscribe to the messages field. Payload details are in WhatsApp Cloud API webhooks, and if nothing arrives, see webhook not receiving messages.

Android apps: why the token stays on your server

Kotlin often means Android, but don’t drop WhatsApp.send() into the app. An APK can be unpacked, and Meta’s security checklist says never to include your app secret in client-side or decompilable code, and to make app-token calls from your own servers. A Cloud API access token is just as sensitive: whoever pulls it out of your app can message anyone as your business, and the bill and the quality rating are yours.

JobWhere it runs
Open a chat with the businessThe Android app, with a wa.me link opened in an ACTION_VIEW intent. No token needed
Order updates, OTPs, repliesYour server, with the code in this guide
Ask for a message to be sentThe app calls your own API (Ktor client works on Android too), signed in as the user
Access token, app secret, webhookYour server only, in environment variables or a secrets manager

The Flutter guide covers this split in more depth, including WhatsApp OTP logins.

Kotlin with Automate AI, or no code at all

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

For your own Kotlin services, Automate AI has a REST API. Owners and managers create API keys on the Developer page (each key is shown once) and send them as Authorization: Bearer, so the same Ktor client works against it. There are endpoints for contacts, contact groups, chats and messages, templates and campaigns, developer webhooks with logs, and a Postman collection to try requests. The API and webhooks are 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 from Kotlin?

POST a JSON body to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages with an Authorization: Bearer header, from server-side code. With the Ktor client, setBody a @Serializable data class that has messaging_product, to, type and the message object.

Is there an official Kotlin SDK for the WhatsApp Cloud API?

No. Meta documents HTTP requests only. The Ktor client, OkHttp or the JDK’s java.net.http all work; avoid any library that logs in to WhatsApp Web.

Why is messaging_product missing from my JSON?

kotlinx.serialization skips properties that still hold their default value. Build your Json with encodeDefaults = true, or don’t give that property a default.

Can I call the WhatsApp API directly from an Android app?

You shouldn’t. The access token would ship inside the APK, where it can be extracted and used to message as your business. Let the app call your own server, and keep the token there.

Why does my Ktor webhook fail the signature check?

Usually because the body was parsed or re-encoded before hashing. Use call.receive<ByteArray>(), hash exactly those bytes with your app secret, and compare with the full header, including sha256=.

Which Graph API version should I use?

The latest in Meta’s changelog: on 4 December 2026, v27.0 (released 4 November 2026). Keep it in one constant.

Sources

  1. Meta: Send messages
  2. Meta: Templates overview
  3. Meta: Create a webhook endpoint
  4. Meta: Graph API changelog
  5. Meta: Facebook Login security (app secret and tokens)
  6. Ktor: Content negotiation and serialization in the client
  7. Ktor: Receiving requests on the server
  8. Kotlin: JSON configuration (kotlinx.serialization)

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.