API Reference

Complete API documentation for developers

Getting Started

The SMS Sending API allows you to send SMS messages programmatically using HTTP requests. This documentation covers the HTTP GET/POST interface for sending MT (Mobile Terminated) SMS messages through our SMS platform.

Base URL

https://api.panelsms.com/sendMtSms.php

Authentication

All requests require two authentication parameters:

  • user: Your username/email registered in the platform
  • apiKey: Your API key generated from the SMS panel

Getting Your API Key

Log in to your account and navigate to Settings → API Keys to generate your unique API key.

Supported Request Methods

The API supports both HTTP GET and POST methods for maximum flexibility.

GitHub Repository

Find complete code examples and SDKs for multiple programming languages in our public GitHub repository:

The repository includes implementations in:

  • PHP: Complete client library and examples
  • Python: Requests-based implementation
  • JavaScript: Browser and Node.js examples
  • Java: HTTP client implementations
  • C#: .NET client library
  • Shell Script: Bash implementation
  • R: Data science integration
  • Windows Batch: Batch file examples

Send SMS - Text, Flash & Binary Messages

Send a single SMS message to a destination number. Supports text messages, flash SMS, and binary SMS with various encodings.

GET POST https://api.panelsms.com/sendMtSms.php

Required Parameters

Parameter Type Description
user string User identifier within the platform (contact e-mail). Required
apiKey string User generates the apiKey at the SMS platform panel. Required
to string Phone number in international format (URL encoded). Example: %2B1222333444 for +1 222 333 444. Required
message string Content of the message (must be URL encoded). Required

Optional Parameters

Parameter Type Description
senderId string Sender of the message (alphanumeric ID or number)
transactionId string User-specified transaction ID; if not provided, the system generates one automatically
confirmation boolean Set to true or false to request delivery reports with SMS status
dcs integer Data Coding Scheme:
0: Default (ISO-8859-1 Latin1)
1: GSM7 Encoding (standard)
2: Binary SMS
3: ISO-8859-1 Latin1
4: Binary SMS
8: UCS2 Encoding (Unicode)
Note: Not all operators support all encodings. Contact your account manager for details.
udh string User Data Header (UDH) - binary structure for message formatting (used for flash SMS, concatenated messages, etc.)
validityPeriod string Message validity period in relative or absolute format. Note: Not all operators support this feature.
scheduledDeliveryTime string Scheduled delivery time in relative or absolute format (for delayed message sending)
responseType string Response format: json or xml. If not specified, returns plain text
callbackUrl string URL where delivery reports (DLR) will be sent (webhook)

HTTP GET Example

https://api.panelsms.com/sendMtSms.php?user=your_api_user&apiKey=your_api_key&to=recipient&message=your_message&responseType=json

PHP Example (Tested from GitHub)

<?php

// Target URL
$url = "https://api.panelsms.com/sendMtSms.php";

// JSON parameters
$data = array(
    "user" => "your_api_user",
    "apiKey" => "your_api_key",
    "to" => "recipient",
    "message" => "your_message"
);

// Configure HTTP POST request
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json",
        'method'  => 'POST',
        'content' => json_encode($data),
    ),
);

// Create the HTTP context
$context = stream_context_create($options);

// Perform the HTTP POST request and get the response
$response = file_get_contents($url, false, $context);

// Check if the request was successful
if ($response !== false) {
    echo "Server response:\n";
    echo json_encode(json_decode($response), JSON_PRETTY_PRINT);
} else {
    echo "Error in the request.\n";
}

?>

Python Example (Tested from GitHub)

import requests
import json

# Target URL
url = "https://api.panelsms.com/sendMtSms.php"

# JSON parameters
payload = {
    "user": "your_api_user",
    "apiKey": "your_api_key",
    "to": "recipient",
    "message": "your_message"
}

# Perform the HTTP POST request with JSON data
response = requests.post(url, json=payload)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    print("Server response:")
    print(json.dumps(response.json(), indent=2))
else:
    print(f"Error in the request. Status code: {response.status_code}")
    print(response.text)

JavaScript Example (Tested from GitHub)

async function sendPostRequest(url, data) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });

        // Check if the request was successful
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        // Return the response as text
        return await response.text();
    } catch (error) {
        console.error('Error in the request:', error);
        throw error;
    }
}

// Target URL
const url = 'https://api.panelsms.com/sendMtSms.php';

// JSON parameters
const data = {
    user: 'your_api_user',
    apiKey: 'your_api_key',
    to: 'recipient',
    message: 'your_message',
};

// Perform the HTTP POST request
sendPostRequest(url, data)
    .then((response) => {
        console.log('Server response:\n', response);
    })
    .catch((error) => {
        console.error('Error:', error);
    });

Responses

Response Type: Plain Text (default)

OK_1234569

Where 1234569 is the transaction ID.

Response Type: JSON

{
  "response": {
    "status": "OK",
    "transactionId": "1234569"
  }
}

Response Type: XML

<response>
  <status>OK</status>
  <transactionId>1234569</transactionId>
</response>

Error Response

ERROR_XXX

Where XXX is the numeric error code. See Error Codes section for details.

Message Types & Encoding

The SMS API supports different message types and encoding schemes depending on your needs and carrier support.

Standard Text Messages (DCS = 1)

GSM 7-bit encoding for standard text messages. Supports alphanumeric characters and special symbols. Maximum 160 characters per message.

Flash SMS / Class 0 Messages

Flash SMS messages appear as popup notifications and are not stored on the device. Use UDH parameter with appropriate header for flash messages.

udh=0100 (Flash SMS header)

Binary Messages (DCS = 2 or 4)

Binary SMS used for sending data, ringtones, logos, and other binary content. Message parameter should contain the binary data.

Unicode / UCS2 Messages (DCS = 8)

Used for messages containing special characters, accents, or non-Latin languages. Maximum 70 characters per message.

Example - Spanish with accents:

message=Hola%20%C3%A9sta%20es%20una%20prueba (URL encoded)

Delivery Reports & Status Callbacks

Get real-time delivery status updates for sent messages through Delivery Report (DLR) callbacks.

Enabling Delivery Reports

To receive delivery reports, include the following parameters in your request:

confirmation=true&callbackUrl=https://your-server.com/dlr-callback

Webhook Callback Example

When a message status changes, the system will send a POST request to your callback URL with the following data:

{
  "transactionId": "1234569",
  "status": "delivered",
  "destination": "+1222333444",
  "timestamp": "2024-01-15T10:30:45Z",
  "errorCode": null,
  "errorDescription": null
}

Possible Status Values

  • ENROUTE: Message is in transit
  • DELIVERED: Message successfully delivered to device
  • EXPIRED: Message validity period expired
  • DELETED: Message was deleted
  • UNDELIVERABLE: Message cannot be delivered
  • ACCEPTED: Accepted by the network
  • UNKNOWN: Status unknown
  • REJECTED: Message rejected by network
  • SKIPPED: Message skipped

PHP Webhook Handler Example

<?php
// Handle DLR callback
$json = file_get_contents('php://input');
$dlr = json_decode($json, true);

$transactionId = $dlr['transactionId'];
$status = $dlr['status'];
$destination = $dlr['destination'];
$timestamp = $dlr['timestamp'];

// Update your database
$pdo = new PDO('mysql:host=localhost;dbname=sms_db', 'user', 'password');
$stmt = $pdo->prepare("UPDATE messages SET status = ?, updated_at = ? WHERE transaction_id = ?");
$stmt->execute([$status, $timestamp, $transactionId]);

// Return success
http_response_code(200);
echo json_encode(['success' => true]);
?>

Scheduled Delivery & Validity Period

Schedule messages for future delivery or set a validity period for message retention.

Scheduled Delivery Time

Send messages at a specific time in the future using the scheduledDeliveryTime parameter.

scheduledDeliveryTime=2024-01-20T15:30:00

Validity Period

Set how long the network will attempt to deliver the message using the validityPeriod parameter.

validityPeriod=3600 (in seconds, or use absolute datetime format)

Example Request with Scheduled Delivery

https://api.panelsms.com/sendMtSms.php?user=your@email.com&apiKey=YOUR_API_KEY&to=%2B1222333444&message=Hello&scheduledDeliveryTime=2024-01-20T15:30:00&responseType=json

Note: Not all operators support scheduled delivery and validity period. Contact your account manager for operator-specific support.

Error Codes

The API returns specific error codes when a request fails. Use these codes to diagnose and fix integration issues.

Error Code Description Solution
1 Account is disabled or doesn't exist Verify your username/email in the panel. Contact support if account is locked.
2 Invalid API key Check your API key. Regenerate it from Settings → API Keys if needed.
3 Message submitted to a Roaming Network Message delivered to a roaming user. Standard delivery still occurs.
4 Invalid source address Verify the sender ID/phone number format is correct.
5 Invalid destination address Check phone number format. Must be in international format (e.g., +1 222 333 444).
6 Message queue full System is overloaded. Retry after a short delay.
7 Throttling error - rate limit exceeded Reduce request frequency or contact support for rate limit increase.
8 Invalid message data Check message encoding and content. Ensure proper URL encoding.
9 Insufficient credits/balance Add credits to your account to continue sending messages.
10 Invalid User Data Header (UDH) Check UDH format for flash SMS or binary messages.
11 Destination barred The destination number is blocked or restricted.
12 Invalid scheduled time Verify the scheduledDeliveryTime format (must be future date/time).
13 Message too long Reduce message length or implement message concatenation.
14 Invalid data coding scheme (DCS) Check DCS parameter value (0, 1, 2, 3, 4, or 8).
15 Operation not supported The requested operation is not available for your account. Contact support.

Common Use Cases & Examples

Real-world examples of integrating the SMS API into your applications.

Use Case 1: Two-Factor Authentication (2FA)

// Send OTP to user
$otp = rand(100000, 999999);
$message = urlencode("Your verification code is: $otp");

$url = "https://api.panelsms.com/sendMtSms.php?" .
    "user=your@email.com&" .
    "apiKey=YOUR_API_KEY&" .
    "to=" . urlencode($phoneNumber) . "&" .
    "message=$message&" .
    "senderId=VERIFY&" .
    "responseType=json";

$response = json_decode(file_get_contents($url), true);
if ($response['response']['status'] === 'OK') {
    $_SESSION['otp'] = $otp;
    $_SESSION['otp_expiry'] = time() + 600; // 10 minutes
}

Use Case 2: Order Notifications

// Send order confirmation
$orderId = '12345';
$message = urlencode("Order #$orderId confirmed. Track at: https://example.com/track/$orderId");

$params = [
    'user' => 'your@email.com',
    'apiKey' => 'YOUR_API_KEY',
    'to' => $customerPhone,
    'message' => $message,
    'senderId' => 'ORDER',
    'transactionId' => "order_$orderId",
    'confirmation' => 'true',
    'responseType' => 'json'
];

$url = 'https://api.panelsms.com/sendMtSms.php?' . http_build_query($params);
$response = file_get_contents($url);

Use Case 3: Appointment Reminders

// Schedule appointment reminder
$appointmentTime = '2024-02-10 14:30:00';
$message = urlencode("Reminder: Your appointment is tomorrow at 2:30 PM");

$params = [
    'user' => 'your@email.com',
    'apiKey' => 'YOUR_API_KEY',
    'to' => $patientPhone,
    'message' => $message,
    'senderId' => 'CLINIC',
    'scheduledDeliveryTime' => $appointmentTime,
    'confirmation' => 'true',
    'responseType' => 'json'
];

$url = 'https://api.panelsms.com/sendMtSms.php?' . http_build_query($params);
$response = file_get_contents($url);

Use Case 4: Promotional Campaign

// Send promotional message with DLR tracking
$campaign = 'SPRING2024';
$message = urlencode("Get 50% off! Use code SPRING2024. Valid until Feb 28");

foreach ($customers as $customer) {
    $params = [
        'user' => 'your@email.com',
        'apiKey' => 'YOUR_API_KEY',
        'to' => $customer['phone'],
        'message' => $message,
        'senderId' => 'PROMO',
        'transactionId' => $campaign . '_' . $customer['id'],
        'confirmation' => 'true',
        'callbackUrl' => 'https://example.com/dlr-callback.php',
        'responseType' => 'json'
    ];
    
    $url = 'https://api.panelsms.com/sendMtSms.php?' . http_build_query($params);
    $response = json_decode(file_get_contents($url), true);
    
    // Log transaction for tracking
    logTransaction($customer['id'], $response['response']['transactionId'], 'pending');
    
    sleep(1); // Rate limiting
}

Use Case 5: Receiving DLR Callbacks

<?php
// Handle incoming delivery reports at /dlr-callback.php
header('Content-Type: application/json');

$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    http_response_code(400);
    exit(json_encode(['error' => 'Invalid request']));
}

try {
    // Validate signature if implemented
    $pdo = new PDO('mysql:host=localhost;dbname=sms_db', 'user', 'pass');
    
    // Update message status
    $stmt = $pdo->prepare("
        UPDATE sms_messages 
        SET status = ?, 
            delivered_at = ?, 
            error_code = ?
        WHERE transaction_id = ?
    ");
    
    $stmt->execute([
        $input['status'],
        $input['timestamp'],
        $input['errorCode'] ?? null,
        $input['transactionId']
    ]);
    
    // Send confirmation
    http_response_code(200);
    echo json_encode(['success' => true]);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>

URL Encoding Tips

Special characters must be properly URL encoded:

Character Encoded
Space%20
+%2B
&%26
=%3D
?%3F
#%23
á/é/í/ó/ú%C3%A1, %C3%A9, etc.

Best Practices & Security

Follow these recommendations to ensure reliable message delivery and secure API integration.

Security Recommendations

  • Never expose API keys: Don't include API keys in client-side code or public repositories
  • Use HTTPS only: Always use HTTPS for all API requests
  • Regenerate API keys periodically: Rotate keys every 90 days for enhanced security
  • IP whitelisting: Contact support to whitelist only your sending IP addresses
  • Store credentials securely: Use environment variables or secure configuration files

Best Practices for Reliability

  • Implement retry logic: Retry failed requests with exponential backoff (3 retries recommended)
  • URL encode all parameters: Ensure all text parameters are properly URL encoded
  • Validate phone numbers: Verify phone numbers are in international format before sending
  • Monitor delivery reports: Set up webhook callbacks to track message delivery status
  • Rate limiting: Implement client-side rate limiting to avoid throttling errors
  • Message idempotency: Use transactionId to prevent duplicate messages if retrying

Performance Tips

  • Batch requests wisely: Send multiple messages sequentially with small delays rather than concurrent requests
  • Use asynchronous processing: Process API calls in background jobs for better performance
  • Cache API responses: Cache balance information instead of checking before each send
  • Implement request timeouts: Set 30-second timeout for API requests