# WhatsApp API

## Overview

This document describes the WhatsApp messaging API functionality provided by the Unecast platform. The API supports sending various types of WhatsApp messages including text, images, documents, and template messages.

## Message Types

The API supports the following message types:

### Text Messages

Simple text messages with optional preview URL support.

### Template Messages

Pre-approved WhatsApp business template messages with dynamic content support.

### Image Messages

Image messages with optional captions.

### Document Messages

Document sharing with automatic filename detection and optional captions.

## API Endpoints

### Send Message v2

Endpoint (POST): `https://api.unecast.com/v2/send`

Description: Sends a message via WhatsApp channel

## Request Schema

### Required Fields

| Field  | Type         | Description               | Validation        |
| ------ | ------------ | ------------------------- | ----------------- |
| `to`   | string/array | Recipient phone number(s) | Max 18 characters |
| `from` | string       | Sender ID                 | Max 18 characters |

### Optional Fields

| Field           | Type   | Description           | Validation                     | Default |
| --------------- | ------ | --------------------- | ------------------------------ | ------- |
| `channel`       | string | Communication channel | Must be 'sms' or 'whatsapp'    | -       |
| `message`       | string | Message content       | Required when no template\_id  | -       |
| `priority`      | number | Message priority      | 0-3 (0=lowest, 3=highest)      | 0       |
| `media_url`     | string | Media file URL        | Valid URI format               | -       |
| `template_id`   | string | WhatsApp template ID  | -                              | -       |
| `template_data` | object | Template parameters   | Only allowed with template\_id | -       |

### Validation Rules

Recipient (`to`)

* Single recipient: String with max 18 characters
* Multiple recipients: Array of strings, minimum 1 recipient
* Format: Phone numbers without special characters

Message Content

* With `template_id`: Message is optional
* Without `template_id`: Message is required
* Cannot be empty when required

Priority Levels

* `0`: Lowest priority (default)
* `1`: Low priority
* `2`: High priority
* `3`: Highest priority

Channel

* Must be either `"sms"` or `"whatsapp"`
* Case-sensitive validation

## Response Format

### Success Response

```json
{
  "status": "success",
  "message": "Message sent successfully",
  "code":200,
  "data": [{
      "message_id": "c19d896841ee247b",
      "message_count": 1,
      "from": "15551377539",
      "to": "94766354698",
      "message": "Your Message Here",
      "timestamp": "2025-10-19T06:45:31.571Z"
    }]
}
```

### Error Response

```json
{
  "status": "error",
  "message": "Error description",
  "code": 400,
  "data": {
    // API response data
  } 
}
```

## Examples

{% stepper %}
{% step %}

### Send Simple Text Message

Request:

```json
POST /v2/send
Content-Type: application/json

{
  "from": "YourBrand",
  "to": "1234567890",
  "channel": "whatsapp",
  "message": "Hello! Welcome to our service.",
  "priority": 1
}
```

{% endstep %}

{% step %}

### Send Template Message

Request:

```json
POST /v2/send
Content-Type: application/json

{
  "from": "YourBrand",
  "to": "1234567890",
  "channel": "whatsapp",
  "template_id": "welcome_template",
  "template_data": {
    "name": "welcome_template",
    "language": {
      "code": "en_US"
    },
    "components": [
      {
        "type": "body",
        "parameters": [
          {
            "type": "text",
            "text": "John Doe"
          }
        ]
      }
    ]
  }
}
```

{% endstep %}

{% step %}

### Send Image Message

Request:

```json
POST /v2/send
Content-Type: application/json

{
  "from": "YourBrand",
  "to": "1234567890",
  "channel": "whatsapp",
  "message": "Check out our new product!",
  "media_url": "https://example.com/product-image.jpg",
  "template_data": {
    "type": "image"
  }
}
```

{% endstep %}

{% step %}

### Send Document

Request:

```json
POST /v2/send
Content-Type: application/json

{
  "from": "YourBrand",
  "to": "1234567890",
  "channel": "whatsapp",
  "message": "Here's your requested document",
  "media_url": "https://example.com/invoice.pdf",
  "template_data": {
    "type": "document"
  }
}
```

{% endstep %}

{% step %}

### Send to Multiple Recipients

Request:

```json
POST /v2/send
Content-Type: application/json

{
  "from": "YourBrand",
  "to": ["1234567890", "0987654321", "1122334455"],
  "channel": "whatsapp",
  "message": "Broadcast message to multiple recipients",
  "priority": 2
}
```

{% endstep %}
{% endstepper %}

## Technical Implementation Notes

### HTTP Client Fallback System

{% stepper %}
{% step %}
Primary: Axios HTTP client
{% endstep %}

{% step %}
Fallback 1: cURL (Unix/Linux systems)
{% endstep %}

{% step %}
Fallback 2: PowerShell (Windows systems)
{% endstep %}

{% step %}
Fallback 3: wget (Unix/Linux systems)
{% endstep %}
{% endstepper %}

### Document Filename Detection

When sending documents, the system automatically:

* Extracts filename from the provided URL
* Adds default `.pdf` extension if no extension is detected
* Uses `"document.pdf"` as fallback filename

### Template Language Support

* Default language: `"en_US"`
* Supports custom language codes in template data
* Language code format follows WhatsApp Business API standards

## Message Length Limitations

The API enforces different message length limits based on the message type and content:

### WhatsApp Text Messages

| Message Type                    | Character Limit   | Notes                                                 |
| ------------------------------- | ----------------- | ----------------------------------------------------- |
| Standard Text Messages          | 4,096 characters  | For regular text messages without templates           |
| Media Messages (Image/Document) | 1,024 characters  | For captions with image or document attachments       |
| Template Messages               | No enforced limit | Template messages bypass character count restrictions |

### SMS Messages

| Message Type      | Character Limit                          | Notes                                       |
| ----------------- | ---------------------------------------- | ------------------------------------------- |
| Standard SMS      | No Limit ( Recommended 1,600 characters) | Automatically split into multiple SMS parts |
| GSM Character Set | Variable                                 | Uses GSM character counting algorithm       |

### Implementation Details

Character Counting Algorithm

The system uses `getCharCount()` from GSM Character Utils which:

* Counts characters using GSM 7-bit encoding rules
* Calculates message segments for SMS delivery
* Handles special characters and Unicode properly

### Message Segmentation

SMS Segmentation

* Single SMS: Up to 160 GSM characters or 70 Unicode characters
* Multi-part SMS: Automatically split by the system
* Message Count: Calculated using `charCount.msgCount`
* Maximum Limit: 1,600 characters total across all segments

WhatsApp Segmentation

* Single Message: Always counted as 1 message regardless of length
* No Auto-splitting: Messages are sent as single units
* Media Messages: Image/document messages with captions count as 1 message

### Error Messages

Length-Related Errors

| Error Message                                                                                            | Trigger Condition                         | Solution                              |
| -------------------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------- |
| "WhatsApp message content cannot exceed 4096 characters. Please shorten your message or use a template." | WhatsApp text message > 4,096 characters  | Reduce message length or use template |
| "WhatsApp media captions cannot exceed 1024 characters. Please shorten your caption."                    | WhatsApp media caption > 1,024 characters | Reduce caption length                 |

## Best Practices for Message Length

WhatsApp Best Practices

* Keep text messages under 4,096 characters for optimal delivery
* Limit media captions to 1,024 characters to avoid rejection
* Use templates for longer content to bypass length restrictions
* Consider user experience — shorter messages are more readable

SMS Best Practices

* Stay under 160 characters to avoid message splitting costs
* Use GSM character set when possible to maximize character count
* Monitor message count for billing and delivery optimization
* Consider concatenated SMS limits for longer messages

Template Message Best Practices

* No character limits apply to approved WhatsApp business templates
* Template parameters can contain longer content
* Use templates for consistent, longer messaging scenarios

## Character Set Considerations

GSM 7-bit Character Set

* Standard characters: A-Z, a-z, 0-9, basic punctuation
* Extended characters: €, \[, ], {, }, , ^, \~, | (count as 2 characters)
* Optimal for SMS: Maximizes character count per message segment

Unicode (UCS-2) Character Set

* All languages supported: Including emoji, special symbols
* Reduced capacity: 70 characters per SMS segment
* WhatsApp friendly: Full Unicode support without penalties

## Integration Notes

The message length validation is implemented in the `sendV2Messages` function within `smsServiceV2.js` and occurs before message queuing. This ensures:

* Early validation prevents invalid messages from entering the system
* Clear error messages help developers understand limitations
* Service-specific rules are enforced based on the delivery channel
* Template bypass allows flexible content for approved templates

## Rate Limiting and Best Practices

* Message Priority: Use priority levels appropriately to ensure important messages are delivered first
* Media URLs: Ensure media URLs are publicly accessible and properly formatted
* Phone Numbers: Always validate phone numbers before sending
* Template Messages: Use approved WhatsApp Business templates only
* Error Handling: Implement proper error handling for all API calls

***

Last Updated: October 19, 2025\
API Version: v2\
Document Version: 1.1
