---
updatedAt: 2026-10-30T07:36:11.000Z
agentTools:
  projectIndex: https://docs.wati.io/llms.txt
---

# Send Template Messages - V3

```python Python
import os
import requests

# Python with requests. One deliberate send; no automatic retry.
host = os.environ["WATI_API_HOST"].rstrip("/")  # e.g. https://live-mt-server.wati.io, without tenant ID
payload = {"template_name": os.environ["WATI_TEMPLATE_NAME"],
           "broadcast_name": os.environ["WATI_BROADCAST_NAME"],
           "recipients": [{"target": os.environ["WATI_TARGET"], "local_message_id": os.environ["WATI_LOCAL_MESSAGE_ID"]}]}
try:
    response = requests.post(host + "/api/ext/v3/messageTemplates/send",
        headers={"Authorization": "Bearer " + os.environ["WATI_API_TOKEN"]}, json=payload, timeout=30)
except requests.RequestException as exc:
    raise RuntimeError("Outcome unknown: reconcile history/status before any resend") from exc
if not 200 <= response.status_code < 300:
    raise RuntimeError(f"HTTP {response.status_code}: inspect the response and recovery guidance; no automatic retry")
try:
    data = response.json()
except ValueError as exc:
    raise RuntimeError("Outcome unknown: expected JSON; reconcile before retrying") from exc
if data.get("success") is not True:
    raise RuntimeError("Business failure: " + str(data.get("error")) + "; reconcile before any retry")
if not data.get("broadcast_id") or not isinstance(data.get("recipients"), list) or len(data["recipients"]) != 1:
    raise RuntimeError("Incomplete recipient result: reconcile the requested target before retrying")
recipient = data["recipients"][0]
if recipient.get("errors") or recipient.get("local_message_id") != os.environ["WATI_LOCAL_MESSAGE_ID"]:
    raise RuntimeError("Recipient failed or correlation differs; broadcast=" + str(data["broadcast_id"]) + "; errors=" + str(recipient.get("errors")))
print("Accepted broadcast:", data["broadcast_id"], "— delivery is not confirmed")

```

```javascript JavaScript
// Node.js with built-in fetch. One deliberate send; no automatic retry.
const env = process.env;
for (const name of ["WATI_API_HOST", "WATI_API_TOKEN", "WATI_TARGET", "WATI_TEMPLATE_NAME", "WATI_BROADCAST_NAME", "WATI_LOCAL_MESSAGE_ID"])
  if (!env[name]) throw new Error(`Missing ${name}`);
const host = env.WATI_API_HOST.replace(/\/$/, ""); // host only, without tenant ID
const payload = {template_name: env.WATI_TEMPLATE_NAME, broadcast_name: env.WATI_BROADCAST_NAME,
  recipients: [{target: env.WATI_TARGET, local_message_id: env.WATI_LOCAL_MESSAGE_ID}]};
async function sendOnce() {
  let response;
  try {
    response = await fetch(host + "/api/ext/v3/messageTemplates/send", {method: "POST",
      headers: {Authorization: `Bearer ${env.WATI_API_TOKEN}`, "Content-Type": "application/json"},
      body: JSON.stringify(payload), signal: AbortSignal.timeout(30000)});
  } catch (error) { throw new Error("Outcome unknown: reconcile history/status before any resend"); }
  if (!response.ok) throw new Error(`HTTP ${response.status}: inspect response and recovery guidance; no automatic retry`);
  let data;
  try { data = await response.json(); }
  catch (error) { throw new Error("Outcome unknown: expected JSON; reconcile before retrying"); }
  if (data.success !== true) throw new Error("Business failure: " + String(data.error) + "; do not replay blindly");
if (!data.broadcast_id || !Array.isArray(data.recipients) || data.recipients.length !== 1)
  throw new Error("Incomplete recipient result: reconcile the requested target before retrying");
const recipient = data.recipients[0];
if ((recipient.errors && (!Array.isArray(recipient.errors) || recipient.errors.length > 0)) ||
    recipient.local_message_id !== env.WATI_LOCAL_MESSAGE_ID)
  throw new Error("Recipient failed or correlation differs: " + JSON.stringify({broadcast_id: data.broadcast_id, errors: recipient.errors}));
console.log("Accepted broadcast:", data.broadcast_id, "— delivery is not confirmed");
}
sendOnce().catch(error => { console.error(error.message); process.exitCode = 1; });

```

```java Java
// Java 11+ and org.json. One deliberate send; no automatic retry.
import java.net.URI;
import java.net.http.*;
import java.time.Duration;
import org.json.*;

public class WatiExample {
  static String env(String name) {
    String value = System.getenv(name);
    if (value == null || value.isEmpty()) throw new IllegalArgumentException("Missing " + name);
    return value;
  }
  public static void main(String[] args) throws Exception {
    String host = env("WATI_API_HOST").replaceAll("/$", ""); // host only, without tenant ID
    JSONObject payload = new JSONObject().put("template_name", env("WATI_TEMPLATE_NAME"))
        .put("broadcast_name", env("WATI_BROADCAST_NAME"))
        .put("recipients", new JSONArray().put(new JSONObject().put("target", env("WATI_TARGET")).put("local_message_id", env("WATI_LOCAL_MESSAGE_ID"))));
    HttpRequest request = HttpRequest.newBuilder(URI.create(host + "/api/ext/v3/messageTemplates/send"))
        .timeout(Duration.ofSeconds(30)).header("Authorization", "Bearer " + env("WATI_API_TOKEN"))
        .header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(payload.toString())).build();
    HttpResponse<String> response;
    try { response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); }
    catch (java.io.IOException | InterruptedException error) {
      if (error instanceof InterruptedException) Thread.currentThread().interrupt();
      throw new IllegalStateException("Outcome unknown: reconcile history/status before any resend", error);
    }
    if (response.statusCode() < 200 || response.statusCode() >= 300)
      throw new IllegalStateException("HTTP " + response.statusCode() + ": inspect response; no automatic retry");
    JSONObject data = new JSONObject(response.body());
    if (!Boolean.TRUE.equals(data.opt("success"))) throw new IllegalStateException("Business failure: " + data.optString("error", "unspecified") + "; do not replay blindly");
    JSONArray recipients = data.optJSONArray("recipients");
    if (data.optString("broadcast_id").isEmpty() || recipients == null || recipients.length() != 1)
      throw new IllegalStateException("Incomplete recipient result: reconcile before retrying");
    JSONObject recipient = recipients.getJSONObject(0);
    JSONArray errors = recipient.optJSONArray("errors");
    if ((errors != null && errors.length() > 0) || !env("WATI_LOCAL_MESSAGE_ID").equals(recipient.optString("local_message_id")))
      throw new IllegalStateException("Recipient failed or correlation differs; broadcast=" + data.optString("broadcast_id") + "; errors=" + String.valueOf(errors));
    System.out.println("Accepted broadcast: " + data.getString("broadcast_id") + "; delivery is not confirmed");
  }
}

```

```php PHP
<?php
// PHP with cURL. One deliberate send; no automatic retry.
function envRequired(string $name): string {
    $value = getenv($name);
    if ($value === false || $value === '') throw new RuntimeException("Missing $name");
    return $value;
}
$host = rtrim(envRequired('WATI_API_HOST'), '/'); // host only, without tenant ID
$payload = ['template_name' => envRequired('WATI_TEMPLATE_NAME'), 'broadcast_name' => envRequired('WATI_BROADCAST_NAME'), 'recipients' => [['target' => envRequired('WATI_TARGET'), 'local_message_id' => envRequired('WATI_LOCAL_MESSAGE_ID')]]];
$curl = curl_init($host . '/api/ext/v3/messageTemplates/send');
curl_setopt_array($curl, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . envRequired('WATI_API_TOKEN'), 'Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR)]);
$raw = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($raw === false) throw new RuntimeException('Outcome unknown: reconcile history/status before any resend');
if ($status < 200 || $status >= 300) throw new RuntimeException("HTTP $status: inspect response and recovery guidance; no automatic retry");
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if (($data['success'] ?? null) !== true) throw new RuntimeException('Business failure: ' . ($data['error'] ?? 'unspecified') . '; do not replay blindly');
if (empty($data['broadcast_id']) || !is_array($data['recipients'] ?? null) || count($data['recipients']) !== 1)
    throw new RuntimeException('Incomplete recipient result: reconcile the requested target before retrying');
$recipient = $data['recipients'][0];
if (!empty($recipient['errors']) || ($recipient['local_message_id'] ?? null) !== envRequired('WATI_LOCAL_MESSAGE_ID'))
    throw new RuntimeException('Recipient failed or correlation differs: ' . json_encode(['broadcast_id' => $data['broadcast_id'], 'errors' => $recipient['errors'] ?? null]));
echo 'Accepted broadcast: ' . $data['broadcast_id'] . ' — delivery is not confirmed';

```

```csharp C#
// .NET 6+ console application. One deliberate send; no automatic retry.
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

static string Env(string name) => Environment.GetEnvironmentVariable(name) is string value && value.Length > 0
    ? value : throw new Exception("Missing " + name);
string host = Env("WATI_API_HOST").TrimEnd('/'); // host only, without tenant ID
using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Env("WATI_API_TOKEN"));
var payload = new { template_name = Env("WATI_TEMPLATE_NAME"), broadcast_name = Env("WATI_BROADCAST_NAME"),
    recipients = new[] { new { target = Env("WATI_TARGET"), local_message_id = Env("WATI_LOCAL_MESSAGE_ID") } } };
HttpResponseMessage response;
try { response = await client.PostAsJsonAsync(host + "/api/ext/v3/messageTemplates/send", payload); }
catch (Exception error) when (error is HttpRequestException || error is TaskCanceledException) {
    throw new Exception("Outcome unknown: reconcile history/status before any resend", error);
}
using var responseScope = response;
if (!response.IsSuccessStatusCode) throw new Exception($"HTTP {(int)response.StatusCode}: inspect response; no automatic retry");
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var data = document.RootElement;
if (!data.TryGetProperty("success", out var success) || success.ValueKind != JsonValueKind.True)
    throw new Exception("Business failure: " + (data.TryGetProperty("error", out var detail) ? detail.ToString() : "unspecified") + "; do not replay blindly");
if (!data.TryGetProperty("broadcast_id", out var broadcast) || broadcast.ValueKind != JsonValueKind.String || string.IsNullOrEmpty(broadcast.GetString()) ||
    !data.TryGetProperty("recipients", out var recipients) || recipients.ValueKind != JsonValueKind.Array || recipients.GetArrayLength() != 1)
    throw new Exception("Incomplete recipient result: reconcile before retrying");
var recipient = recipients[0];
if ((recipient.TryGetProperty("errors", out var errors) && errors.ValueKind != JsonValueKind.Null &&
     (errors.ValueKind != JsonValueKind.Array || errors.GetArrayLength() > 0)) ||
    !recipient.TryGetProperty("local_message_id", out var correlation) || correlation.GetString() != Env("WATI_LOCAL_MESSAGE_ID"))
    throw new Exception("Recipient failed or correlation differs; broadcast=" + broadcast.GetString() + "; errors=" + (errors.ValueKind == JsonValueKind.Undefined ? "not returned" : errors.ToString()));
Console.WriteLine($"Accepted broadcast: {broadcast.GetString()}; delivery is not confirmed");

```

```json Response Example
{
  "success": true,
  "broadcast_id": "<broadcast-id>",
  "recipients": [
    {
      "local_message_id": "<local-message-id>",
      "phone_number": "<returned-phone>",
      "target": "<returned-target>",
      "errors": []
    }
  ]
}
```

# Configure credentials

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Set WATI_API_HOST to your WATI API host only (for example https://live-mt-server.wati.io), without a workspace/tenant ID or /api suffix. Store your API token in WATI_API_TOKEN. Use the host provided for your account; do not move credentials between regions. See [Authentication](https://docs.wati.io/v2.6/reference/authentication). Examples require Python + requests, Node.js with fetch, Java 11+ + org.json, PHP + cURL, or .NET 6+.

# Select template and recipient

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Set WATI_TEMPLATE_NAME to an approved WhatsApp template for your sending channel, WATI_BROADCAST_NAME to a descriptive request name, WATI_LOCAL_MESSAGE_ID to a fresh correlation ID for this attempt, and WATI_TARGET to a supported recipient identifier from your contact data. This example sends a parameter-free template to one recipient on the default channel. For another sending channel, set the top-level channel to its supported name/number; a channel ID is not interchangeable. For parameterized/media templates, add exactly the custom_params required by that approved template; do not invent media parameter names. See [V3 template send](https://docs.wati.io/v2.6/reference/messagetemplate_sendtemplatemessages).

# Send once and inspect business results

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Confirm the target and template before executing. POST /api/ext/v3/messageTemplates/send. HTTP 200 can contain success=false and error. On success=true, retain broadcast_id and reconcile the returned recipients with the requested identifiers: invalid or unavailable recipients can be omitted. Inspect each recipient.errors array and compare the returned local_message_id with the one you supplied. The sample expects exactly one returned recipient; it reports an incomplete result rather than retrying the whole batch. Accepted recipients are not yet proof of delivery.

# Handle unknown outcomes

<!-- python@1 -->
<!-- javascript@1 -->
<!-- java@1 -->
<!-- php@1 -->
<!-- csharp@1 -->

Use current message-status/webhook or history capabilities to confirm the final outcome. A timeout, connection loss or 5xx can leave the result unknown; reconcile the original attempt before any resend. Do not retry the full batch to recover missing recipients. For HTTP 429, honor Retry-After when present; otherwise use bounded backoff and check applicable limits. For other 4xx, correct the request, permissions or account availability first. A local_message_id or broadcast_name is a correlation value, not a general idempotency guarantee. See [Errors](https://docs.wati.io/v2.6/reference/errors).