WhatsApp Notifications
Send WhatsApp messages to your users through the Notifications API. This integration supports both simple text messages and rich template-based messages with formatted content.
Prerequisites
Before implementing WhatsApp notifications, ensure you have:
- Authentication token for the WhatsApp API
- Phone number ID registered with WhatsApp Business API
- Pre-approved message templates (for template messages)
- API subscription key
You can access your WhatsApp authentication tokens and phone number IDs through the WhatsApp Developer Hub.
Sending Text Messages
Text messages allow you to send simple content without formatting or media.
Endpoint
POST https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1/WhatsApp/Send/TextOnly
Request Headers
Header | Required | Description |
---|---|---|
Ocp-Apim-Subscription-Key | Yes | Your API subscription key |
correlationid | No | Unique identifier for tracking the request |
x-ls-party-id | No | Party identifier for the sender |
Request Body
{
"authToken": "YOUR_WHATSAPP_AUTH_TOKEN",
"phoneNumberId": "YOUR_WHATSAPP_PHONE_ID",
"sendToPhoneNumber": "RECIPIENT_PHONE_NUMBER",
"countryCode": "COUNTRY_CODE",
"messageBody": "Your message text here"
}
Response
A successful request returns:
{
"statusCode": 0,
"message": "Message sent successfully"
}
Sending Template Messages
Template messages use pre-approved formats with placeholders for dynamic content.
Endpoint
POST https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1/WhatsApp/Send/Template
Request Headers
Same headers as text-only messages.
Request Body
{
"authToken": "YOUR_WHATSAPP_AUTH_TOKEN",
"phoneNumberId": "YOUR_WHATSAPP_PHONE_ID",
"sendToPhoneNumber": "RECIPIENT_PHONE_NUMBER",
"countryCode": "COUNTRY_CODE",
"templateName": "your_template_name",
"languageCode": "en_US",
"components": [
{
"type": "body",
"parameters": [
{
"type": "text",
"text": "Parameter value 1"
},
{
"type": "text",
"text": "Parameter value 2"
}
]
}
]
}
Component Types
WhatsApp templates support these component types:
header
: The template header (supports text, image, document, or video)body
: The main content section (supports text parameters)button
: Interactive buttons (URLs or quick replies)
Header Component Example
{
"type": "header",
"parameters": [
{
"type": "image",
"image": {
"link": "https://example.com/image.jpg"
}
}
]
}
Error Handling
The API returns standard HTTP status codes:
200 OK
: Request successful400 Bad Request
: Invalid parameters
Error responses include a descriptive message:
{
"statusCode": 1,
"message": "Error description"
}
Implementation Examples
- C#
- Java
- JavaScript
- Python
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class WhatsAppService
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
private readonly string _subscriptionKey;
public WhatsAppService(string subscriptionKey)
{
_httpClient = new HttpClient();
_subscriptionKey = subscriptionKey;
}
public async Task<string> SendTextMessage(string authToken, string phoneNumberId,
string recipientNumber, string countryCode, string messageText)
{
var request = new
{
authToken = authToken,
phoneNumberId = phoneNumberId,
sendToPhoneNumber = recipientNumber,
countryCode = countryCode,
messageBody = messageText
};
var content = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
var response = await _httpClient.PostAsync($"{_baseUrl}/WhatsApp/Send/TextOnly", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<string> SendTemplateMessage(string authToken, string phoneNumberId,
string recipientNumber, string countryCode, string templateName, string languageCode, object components)
{
var request = new
{
authToken = authToken,
phoneNumberId = phoneNumberId,
sendToPhoneNumber = recipientNumber,
countryCode = countryCode,
templateName = templateName,
languageCode = languageCode,
components = components
};
var content = new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _subscriptionKey);
var response = await _httpClient.PostAsync($"{_baseUrl}/WhatsApp/Send/Template", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import org.json.JSONObject;
import org.json.JSONArray;
public class WhatsAppNotificationService {
private final HttpClient httpClient;
private final String baseUrl = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1";
private final String subscriptionKey;
public WhatsAppNotificationService(String subscriptionKey) {
this.httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
this.subscriptionKey = subscriptionKey;
}
public String sendTextMessage(String authToken, String phoneNumberId,
String recipientNumber, String countryCode, String messageText)
throws Exception {
JSONObject requestBody = new JSONObject();
requestBody.put("authToken", authToken);
requestBody.put("phoneNumberId", phoneNumberId);
requestBody.put("sendToPhoneNumber", recipientNumber);
requestBody.put("countryCode", countryCode);
requestBody.put("messageBody", messageText);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/WhatsApp/Send/TextOnly"))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", subscriptionKey)
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
public String sendTemplateMessage(String authToken, String phoneNumberId,
String recipientNumber, String countryCode,
String templateName, String languageCode,
JSONArray components) throws Exception {
JSONObject requestBody = new JSONObject();
requestBody.put("authToken", authToken);
requestBody.put("phoneNumberId", phoneNumberId);
requestBody.put("sendToPhoneNumber", recipientNumber);
requestBody.put("countryCode", countryCode);
requestBody.put("templateName", templateName);
requestBody.put("languageCode", languageCode);
requestBody.put("components", components);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/WhatsApp/Send/Template"))
.header("Content-Type", "application/json")
.header("Ocp-Apim-Subscription-Key", subscriptionKey)
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}
async function sendWhatsAppTextMessage() {
const response = await fetch('https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1/WhatsApp/Send/TextOnly', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'your-subscription-key'
},
body: JSON.stringify({
authToken: 'your-whatsapp-auth-token',
phoneNumberId: 'your-phone-number-id',
sendToPhoneNumber: '1234567890',
countryCode: 'ZA',
messageBody: 'Hello! This is a test message.'
})
});
return await response.json();
}
async function sendWhatsAppTemplateMessage() {
const response = await fetch('https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1/WhatsApp/Send/Template', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'your-subscription-key'
},
body: JSON.stringify({
authToken: 'your-whatsapp-auth-token',
phoneNumberId: 'your-phone-number-id',
sendToPhoneNumber: '1234567890',
countryCode: 'ZA',
templateName: 'appointment_reminder',
languageCode: 'en_US',
components: [
{
type: 'body',
parameters: [
{ type: 'text', text: 'Tomorrow' },
{ type: 'text', text: '3:00 PM' }
]
}
]
})
});
return await response.json();
}
import requests
import json
class WhatsAppNotification:
def __init__(self, subscription_key):
self.base_url = "https://apis.lightstone.co.za/lightstone-capabilities-notifications-api/v1"
self.subscription_key = subscription_key
self.headers = {
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Key": subscription_key
}
def send_text_message(self, auth_token, phone_number_id, recipient_number, country_code, message_text):
"""
Send a simple text message via WhatsApp
Args:
auth_token (str): WhatsApp API authentication token
phone_number_id (str): WhatsApp Business phone number ID
recipient_number (str): Recipient's phone number
country_code (str): Country code (e.g., 'ZA')
message_text (str): Message content to send
Returns:
dict: API response
"""
request_data = {
"authToken": auth_token,
"phoneNumberId": phone_number_id,
"sendToPhoneNumber": recipient_number,
"countryCode": country_code,
"messageBody": message_text
}
response = requests.post(
f"{self.base_url}/WhatsApp/Send/TextOnly",
headers=self.headers,
data=json.dumps(request_data)
)
return response.json()
def send_template_message(self, auth_token, phone_number_id, recipient_number, country_code,
template_name, language_code, components):
"""
Send a template-based message via WhatsApp
Args:
auth_token (str): WhatsApp API authentication token
phone_number_id (str): WhatsApp Business phone number ID
recipient_number (str): Recipient's phone number
country_code (str): Country code (e.g., 'ZA')
template_name (str): Name of the pre-approved template
language_code (str): Language code for the template (e.g., 'en_US')
components (list): Template components with parameters
Returns:
dict: API response
"""
request_data = {
"authToken": auth_token,
"phoneNumberId": phone_number_id,
"sendToPhoneNumber": recipient_number,
"countryCode": country_code,
"templateName": template_name,
"languageCode": language_code,
"components": components
}
response = requests.post(
f"{self.base_url}/WhatsApp/Send/Template",
headers=self.headers,
data=json.dumps(request_data)
)
return response.json()
# Usage examples
if __name__ == "__main__":
# Initialize with your subscription key
whatsapp_client = WhatsAppNotification("your-subscription-key")
# Send a text message
text_result = whatsapp_client.send_text_message(
auth_token="your-whatsapp-auth-token",
phone_number_id="your-phone-number-id",
recipient_number="1234567890",
country_code="ZA",
message_text="Hello! This is a test message sent from Python."
)
print(f"Text message result: {text_result}")
# Send a template message
template_components = [
{
"type": "body",
"parameters": [
{"type": "text", "text": "Tomorrow"},
{"type": "text", "text": "2:30 PM"}
]
}
]
template_result = whatsapp_client.send_template_message(
auth_token="your-whatsapp-auth-token",
phone_number_id="your-phone-number-id",
recipient_number="1234567890",
country_code="ZA",
template_name="appointment_reminder",
language_code="en_US",
components=template_components
)
print(f"Template message result: {template_result}")
Best Practices
- Always validate phone numbers before sending messages
- Include country code in international format (example: "ZA" for South Africa)
- Keep text messages concise and clear
- Test templates thoroughly before sending to customers
- Implement error handling for failed message deliveries
- Cache authentication tokens when possible to improve performance
- Add correlation IDs to trace message flows across systems
Rate Limits and Performance
- The WhatsApp API imposes rate limits on message sending
- Batch multiple recipients when possible to reduce API calls
- Implement exponential backoff for retry logic
- Monitor delivery success rates to optimize sending patterns
Was this page useful?