> For the complete documentation index, see [llms.txt](https://squarebox-ai.gitbook.io/squarebox/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://squarebox-ai.gitbook.io/squarebox/untitled/api-docs/squarebox-external-api-documentation.md).

# SquareBox External API Documentation

Welcome to the SquareBox External API! This documentation covers how to generate API keys and send WhatsApp messages using our external messaging API.

## Table of Contents

* [Overview](#overview)
* [Getting Started](#getting-started)
* [Authentication](#authentication)
* [API Endpoints](#api-endpoints)
* [Webhooks](#webhooks)
* [Cost Management](#cost-management)
* [Rate Limiting](#rate-limiting)
* [Examples](#examples)
* [Error Handling](#error-handling)

## Overview

The SquareBox External API allows external platforms to send WhatsApp messages using secure API keys. This API is perfect for:

* CRM integrations (Salesforce, HubSpot, etc.)
* E-commerce platforms
* Customer support tools
* Marketing automation platforms

## Getting Started

### 1. Generate API Key

1. Log into your SquareBox account
2. Go to **Settings** → **API Keys**
3. Click **"Create New API Key"**
4. Provide a name and description (e.g., "LeadSquared Integration")
5. **Important**: Copy the API key immediately - it won't be shown again!

### 2. Get Your Line ID

1. Go to **Lines** in your SquareBox dashboard
2. Note the **Line ID** you want to send messages from
3. Ensure the line is active and has sufficient credits

## Authentication

Use this header:

* X-API-Key: sb\_your\_api\_key\_here

Example:

```http
X-API-Key: sb_live_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz
```

Notes:

* Usage is tracked per key (timestamp and IP) for audit/analytics.
* Credit checks run before send calls; responses include estimated\_cost. Actual deductions occur via webhook on status update.

## Base URL

* Production: `https://app.squarebox.ai`

## API Endpoints

### Send Text Message

Send a plain text WhatsApp message to a customer.

```http
POST /api/external/messaging/send_text_message
```

**Headers:**

```http
X-API-Key: sb_your_api_key_here
Content-Type: application/json
```

**Request Body:**

```json
{
  "phone_number": "919876543210",
  "line_id": 123,
  "message": "Hello! Your order has been confirmed.",
  "customer_name": "John Doe",
  "customer_email": "john@example.com"
}
```

**Parameters:**

* `phone_number` (required): Customer's phone number with country code (e.g., "919876543210")
* `line_id` (required): Your Line ID from SquareBox dashboard
* `message` (required): The text message to send
* `customer_name` (optional): Customer's name (creates new customer if not exists)
* `customer_email` (optional): Customer's email (creates new customer if not exists)

**Success Response (200):**

```json
{
  "success": true,
  "message": "Message sent successfully",
  "data": {
    "message_id": 456,
    "external_id": "wamid.abc123",
    "status": "sent",
    "customer_id": 789,
    "conversation_id": 101,
    "estimated_cost": 0.50
  }
}
```

### Send Template Message

Send a WhatsApp template message with dynamic variables.

```http
POST /api/external/messaging/send_template_message
```

**Headers:**

```http
X-API-Key: sb_your_api_key_here
Content-Type: application/json
```

**Request Body:**

```json
{
  "phone_number": "919876543210",
  "line_id": 123,
  "template_id": "welcome_template",
  "template_variables": {
    "customer_name": "John Doe",
    "company_name": "SquareBox"
  },
  "customer_name": "John Doe",
  "customer_email": "john@example.com"
}
```

**Parameters:**

* `phone_number` (required): Customer's phone number with country code
* `line_id` (required): Your Line ID from SquareBox dashboard
* `template_id` (required): WhatsApp template ID (get from your templates)
* `placeholder_values` (required): Dynamic values to replace in template
* `customer_name` (optional): Customer's name
* `customer_email` (optional): Customer's email

**Success Response (200):**

```json
{
  "success": true,
  "message": "Template message sent successfully",
  "data": {
    "message_id": 456,
    "external_id": "wamid.abc123",
    "status": "sent",
    "customer_id": 789,
    "conversation_id": 101,
    "template_name": "Welcome Template",
    "estimated_cost": 0.50
  }
}
```

### Send Media Message

Send a media message (image, video, audio, or document).

```http
POST /api/external/messaging/send_media_message
```

**Headers (any one):**

```http
Authorization: Bearer sb_your_api_key_here
X-API-Key: sb_your_api_key_here
API-Key: sb_your_api_key_here
Content-Type: multipart/form-data
```

**Form Data:**

* `phone_number`: "919876543210"
* `line_id`: "123"
* `media_type`: "image" (options: image, video, audio, document)
* `media_url`: "<https://example.com/image.jpg>"
* `caption`: "Check out our latest product!" (optional)
* `customer_name`: "John Doe" (optional)
* `customer_email`: "<john@example.com>" (optional)

**Success Response (200):**

```json
{
  "success": true,
  "message": "Media message sent successfully",
  "data": {
    "message_id": 456,
    "external_id": "wamid.abc123",
    "status": "sent",
    "customer_id": 789,
    "conversation_id": 101,
    "media_type": "image",
    "estimated_cost": 0.50
  }
}
```

### Get Customer Info

Retrieve customer information and conversation status.

```http
GET /api/external/messaging/get_customer_info?phone_number=919876543210&line_id=123
```

**Headers:**

```http
X-API-Key: sb_your_api_key_here
```

**Query Parameters:**

* `phone_number` (required): Customer's phone number with country code
* `line_id` (required): Your Line ID from SquareBox dashboard

**Success Response (200):**

```json
{
  "success": true,
  "data": {
    "customer": {
      "id": 789,
      "name": "John Doe",
      "phone_number": "919876543210",
      "email": "john@example.com",
      "active": true,
      "created_at": "2024-01-15T10:30:00Z"
    },
    "conversation": {
      "id": 101,
      "resolved": false,
      "last_message_at": "2024-01-15T10:30:00Z",
      "message_count": 5
    }
  }
}
```

### Get Credit Balance

Check your current credit balance.

```http
GET /api/external/messaging/credit_balance?line_id=123
```

**Headers:**

```http
Authorization: Bearer sb_your_api_key_here
```

**Query Parameters:**

* `line_id` (required): Your Line ID from SquareBox dashboard

**Success Response (200):**

```json
{
  "success": true,
  "data": {
    "balance": 150.75,
    "currency": "INR",
    "business_name": "My Business",
    "last_updated": "2024-01-15T10:30:00Z"
  }
}
```

### Estimate Message Cost

Get cost estimation for sending messages to specific countries.

```http
GET /api/external/messaging/estimate_cost?line_id=123&country_code=91&message_type=text
```

**Headers:**

```http
Authorization: Bearer sb_your_api_key_here
```

**Query Parameters:**

* `line_id` (required): Your Line ID from SquareBox dashboard
* `country_code` (optional): Country code (e.g., "91" for India, "1" for US)
* `message_type` (optional): Type of message (text, template, media)

**Success Response (200):**

```json
{
  "success": true,
  "data": {
    "estimated_cost": 0.50,
    "currency": "INR",
    "country": "India",
    "country_code": "91",
    "message_type": "text"
  }
}
```

### Get Available Templates

Retrieve all available WhatsApp templates for your line.

```http
GET /api/external/messaging/templates?line_id=123
```

**Headers:**

```http
Authorization: Bearer sb_your_api_key_here
```

**Query Parameters:**

* `line_id` (required): Your Line ID from SquareBox dashboard

**Success Response (200):**

```json
{
  "success": true,
  "data": {
    "templates": [
      {
        "id": 1,
        "name": "Welcome Template",
        "category": "marketing",
        "language": "en",
        "status": "approved",
        "variables": ["customer_name", "company_name"]
      }
    ],
    "count": 1
  }
}
```

### Bulk Send Messages

Send multiple messages in a single API call (up to 50 messages).

```http
POST /api/external/messaging/bulk_send
```

**Headers:**

```http
X-API-Key: sb_your_api_key_here
Content-Type: application/json
```

**Request Body:**

```json
{
  "line_id": 123,
  "messages": [
    {
      "phone_number": "919876543210",
      "type": "text",
      "message": "Hello John!",
      "customer_name": "John Doe",
      "customer_email": "john@example.com"
    },
    {
      "phone_number": "919876543211",
      "type": "template",
      "template_id": 1,
      "template_variables": {
        "customer_name": "Jane Doe",
        "company_name": "SquareBox"
      },
      "customer_name": "Jane Doe"
    }
  ]
}
```

**Success Response (200):**

```json
{
  "success": true,
  "message": "Bulk send completed: 2 successful, 0 failed",
  "data": {
    "total_messages": 2,
    "successful": 2,
    "failed": 0,
    "results": [
      {
        "phone_number": "919876543210",
        "success": true,
        "message_id": 456,
        "error": null
      },
      {
        "phone_number": "919876543211",
        "success": true,
        "message_id": 457,
        "error": null
      }
    ]
  }
}
```

## Webhooks

### Configure Webhook URL

Set up a webhook URL to receive real-time updates about message status and cost deductions.

```http
POST /api/external/messaging/configure_webhook
```

**Headers:**

```http
X-API-Key: sb_your_api_key_here
Content-Type: application/json
```

**Request Body:**

```json
{
  "webhook_url": "https://your-domain.com/webhook/squarebox"
}
```

**Success Response (200):**

```json
{
  "success": true,
  "message": "Webhook URL configured successfully",
  "data": {
    "webhook_url": "https://your-domain.com/webhook/squarebox",
    "configured_at": "2024-01-15T10:30:00Z"
  }
}
```

### Get Webhook Configuration

Retrieve your current webhook configuration.

```http
GET /api/external/messaging/webhook_config
```

**Headers (any one):**

```http
Authorization: Bearer sb_your_api_key_here
X-API-Key: sb_your_api_key_here
API-Key: sb_your_api_key_here
```

**Success Response (200):**

```json
{
  "success": true,
  "data": {
    "webhook_url": "https://your-domain.com/webhook/squarebox",
    "configured_at": "2024-01-15T10:30:00Z",
    "webhook_secret": "abc123def456..."
  }
}
```

### Test Webhook Configuration

Test your webhook configuration by sending a test payload.

```http
POST /api/external/messaging/test_webhook
```

**Headers (any one):**

```http
Authorization: Bearer sb_your_api_key_here
X-API-Key: sb_your_api_key_here
API-Key: sb_your_api_key_here
```

**Success Response (200):**

```json
{
  "success": true,
  "message": "Webhook test successful",
  "data": {
    "status_code": 200,
    "response_body": "OK"
  }
}
```

### Webhook Events

Your webhook endpoint will receive the following events:

#### Message Status Updated

```json
{
  "event": "message_status_updated",
  "timestamp": "2024-01-15T10:30:00Z",
  "business_id": 123,
  "data": {
    "message_id": 456,
    "external_id": "wamid.abc123",
    "status": "delivered",
    "customer": {
      "id": 789,
      "phone_number": "919876543210",
      "name": "John Doe"
    },
    "conversation_id": 101,
    "line_id": 123,
    "message_type": "text",
    "created_at": "2024-01-15T10:25:00Z",
    "updated_at": "2024-01-15T10:30:00Z"
  }
}
```

#### Cost Deducted

```json
{
  "event": "cost_deducted",
  "timestamp": "2024-01-15T10:30:00Z",
  "business_id": 123,
  "data": {
    "message_id": 456,
    "external_id": "wamid.abc123",
    "cost_amount": 0.50,
    "currency": "INR",
    "category": "marketing",
    "customer_country": "India",
    "remaining_balance": 149.25,
    "description": "Charged for marketing message sent to 919876543210"
  }
}
```

### Webhook Security

All webhook payloads include a signature header for verification:

```http
X-SquareBox-Signature: abc123def456...
```

To verify the signature:

```javascript
const crypto = require('crypto');
const secret = 'your_webhook_secret';
const signature = req.headers['x-squarebox-signature'];
const payload = JSON.stringify(req.body);
const expectedSignature = crypto.createHmac('sha256', secret).update(payload).digest('hex');

if (signature === expectedSignature) {
  // Webhook is authentic
} else {
  // Reject webhook
}
```

## Cost Management

### How Costs Work

1. **Cost Estimation**: Use the `estimate_cost` endpoint to check message costs before sending
2. **Credit Check**: The API checks if you have sufficient credits before sending messages
3. **Cost Deduction**: Credits are deducted via webhook when message status becomes 'sent'
4. **Real-time Updates**: Receive webhook notifications when costs are deducted

### Cost Structure

* **Country-based pricing**: Different costs for different countries
* **Message type pricing**: Templates may have different costs than text messages
* **Real-time deduction**: Only charged when message is successfully sent
* **Transparent billing**: Full cost breakdown in webhook notifications

## Rate Limiting

* 100 requests per hour per API key
* 10 requests per minute for all endpoints
* When limits are exceeded, you will receive HTTP 429 with an error message

## Examples

### cURL Examples

#### Send Text Message

```bash
curl -X POST https://app.squarebox.ai/api/external/messaging/send_text_message \
  -H "X-API-Key: sb_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "phone_number": "919876543210",
    "line_id": 123,
    "message": "Hello! Your order has been confirmed.",
    "customer_name": "John Doe",
    "customer_email": "john@example.com"
  }'
```

#### Check Credit Balance

```bash
curl -X GET "https://app.squarebox.ai/api/external/messaging/credit_balance?line_id=123" \
  -H "X-API-Key: sb_your_api_key_here"
```

#### Estimate Cost

```bash
curl -X GET "https://app.squarebox.ai/api/external/messaging/estimate_cost?line_id=123&country_code=91" \
  -H "X-API-Key: sb_your_api_key_here"
```

#### Bulk Send Messages

```bash
curl -X POST https://app.squarebox.ai/api/external/messaging/bulk_send \
  -H "X-API-Key: sb_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "line_id": 123,
    "messages": [
      {
        "phone_number": "919876543210",
        "type": "text",
        "message": "Hello John!",
        "customer_name": "John Doe"
      },
      {
        "phone_number": "919876543211",
        "type": "text",
        "message": "Hello Jane!",
        "customer_name": "Jane Doe"
      }
    ]
  }'
```

#### Configure Webhook

```bash
curl -X POST https://app.squarebox.ai/api/external/messaging/configure_webhook \
  -H "X-API-Key: sb_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "webhook_url": "https://your-domain.com/webhook/squarebox"
  }'
```

### JavaScript Example

```javascript
// Send text message with cost estimation
const sendTextMessage = async () => {
  const response = await fetch('https://app.squarebox.ai/api/external/messaging/send_text_message', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sb_your_api_key_here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      phone_number: '919876543210',
      line_id: 123,
      message: 'Hello! Your order has been confirmed.',
      customer_name: 'John Doe',
      customer_email: 'john@example.com'
    })
  });
  
  const result = await response.json();
  console.log('Estimated cost:', result.data.estimated_cost);
  console.log('Message ID:', result.data.message_id);
};

// Check credit balance
const checkBalance = async () => {
  const response = await fetch('https://app.squarebox.ai/api/external/messaging/credit_balance?line_id=123', {
    headers: {
      'Authorization': 'Bearer sb_your_api_key_here'
    }
  });
  
  const result = await response.json();
  console.log('Current balance:', result.data.balance);
};
```

### Python Example

```python
import requests

# Send text message
def send_text_message():
    url = 'https://app.squarebox.ai/api/external/messaging/send_text_message'
    headers = {
        'Authorization': 'Bearer sb_your_api_key_here',
        'Content-Type': 'application/json'
    }
    data = {
        'phone_number': '919876543210',
        'line_id': 123,
        'message': 'Hello! Your order has been confirmed.',
        'customer_name': 'John Doe',
        'customer_email': 'john@example.com'
    }
    
    response = requests.post(url, headers=headers, json=data)
    result = response.json()
    print(f"Estimated cost: {result['data']['estimated_cost']}")

# Bulk send messages
def bulk_send_messages():
    url = 'https://app.squarebox.ai/api/external/messaging/bulk_send'
    headers = {
        'Authorization': 'Bearer sb_your_api_key_here',
        'Content-Type': 'application/json'
    }
    data = {
        'line_id': 123,
        'messages': [
            {
                'phone_number': '919876543210',
                'type': 'text',
                'message': 'Hello John!',
                'customer_name': 'John Doe'
            },
            {
                'phone_number': '919876543211',
                'type': 'text',
                'message': 'Hello Jane!',
                'customer_name': 'Jane Doe'
            }
        ]
    }
    
    response = requests.post(url, headers=headers, json=data)
    result = response.json()
    print(f"Successfully sent: {result['data']['successful']} messages")
```

## Error Handling

### Error Response Format

```json
{
  "success": false,
  "error": "Error message description",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

### Common Error Codes

| Code | Description           | Solution                               |
| ---- | --------------------- | -------------------------------------- |
| 400  | Bad Request           | Check request parameters               |
| 401  | Unauthorized          | Verify API key is correct              |
| 402  | Payment Required      | Add credits to your account            |
| 403  | Forbidden             | Check if API key has permissions       |
| 404  | Not Found             | Verify line\_id or template\_id exists |
| 422  | Unprocessable Entity  | Check phone number format              |
| 429  | Too Many Requests     | Wait before making more requests       |
| 500  | Internal Server Error | Contact support                        |

### Common Errors

#### Insufficient Credits

```json
{
  "success": false,
  "error": "Insufficient credits to send message",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

#### Rate Limit Exceeded

```json
{
  "success": false,
  "error": "Hourly rate limit exceeded",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

#### Invalid Phone Number

```json
{
  "success": false,
  "error": "Invalid phone number format",
  "timestamp": "2024-01-15T10:30:00Z"
}
```

## Support

For API support and questions:

* **Email**: <api-support@squarebox.ai>
* **Documentation**: <https://docs.squarebox.ai>
* **Status Page**: <https://status.squarebox.ai>

***

*Last updated: January 15, 2024*
