Skip to main content

Incoming SMS Messages

Retrieve incoming SMS messages sent to your dedicated phone numbers or short codes.

Overview

The incoming SMS API allows you to retrieve messages sent by users to your phone numbers. This is useful for:

  • 📨 Two-way SMS communication
  • 🎫 Keyword-based campaigns (e.g., "TEXT STOP to unsubscribe")
  • 🗳️ Polls and surveys
  • 💬 Customer support via SMS
  • ✅ Opt-in/opt-out management
Prerequisites

You need a dedicated phone number or short code to receive incoming messages. Contact LightSMS support to set this up.


Get Incoming Messages

Retrieve incoming messages for a specific date or date range.

Endpoint:

GET https://www.lightsms.com/external/get/incoming.php

Required Parameters:

ParameterTypeDescription
loginstringYour LightSMS login
signaturestringMD5 signature
timestampintegerUTC timestamp (valid for 10 seconds)

Date Parameters (choose one):

ParameterTypeDescription
datestringSingle date in format YYYY-MM-DD
OR
from + tostringDate range in format YYYY-MM-DD HH:MM:SS

Optional Parameters:

ParameterTypeDescription
returnstringResponse format: json or xml
tip

If you specify both date and from/to parameters, the date parameter takes priority.


Request by Single Date

Get all incoming messages for a specific day.

Example Request:

curl "https://www.lightsms.com/external/get/incoming.php?login=YourLogin&signature=generated_signature&timestamp=1732809600&return=json&date=2025-01-15"

Response (JSON):

{
"5597": {
"date": "2025-01-15 14:23:45",
"sender": "37061234567",
"phone": "5163251632",
"prefix": "51632",
"text": "STOP"
},
"5598": {
"date": "2025-01-15 15:10:22",
"sender": "37062345678",
"phone": "5163251632",
"prefix": "51632",
"text": "INFO"
}
}

Response (XML):

<?xml version="1.0" encoding="utf-8"?>
<response>
<sms
id_sms="5597"
date="2025-01-15 14:23:45"
sender="37061234567"
phone="5163251632"
prefix="51632"
text="STOP"
/>
<sms
id_sms="5598"
date="2025-01-15 15:10:22"
sender="37062345678"
phone="5163251632"
prefix="51632"
text="INFO"
/>
</response>

Request by Date Range

Get incoming messages for a specific time period.

Example Request:

curl "https://www.lightsms.com/external/get/incoming.php?login=YourLogin&signature=generated_signature&timestamp=1732809600&return=json&from=2025-01-15%2000:00:00&to=2025-01-15%2023:59:59"
URL Encoding

Remember to URL-encode the date/time parameters. Space becomes %20, colon : becomes %3A.


Response Fields

FieldTypeDescription
id_smsstringUnique message ID (JSON key or attribute)
datestringDate and time message was received
senderstringPhone number that sent the message
phonestringYour phone number that received it
prefixstringShort code or prefix
textstringMessage content

Code Examples

PHP - Process Incoming Messages

<?php
function getIncomingMessages($login, $apiKey, $date) {
// Get timestamp
$timestamp = trim(file_get_contents('https://www.lightsms.com/external/get/timestamp.php'));

// Prepare parameters
$params = [
'login' => $login,
'date' => $date,
'timestamp' => $timestamp,
'return' => 'json'
];

// Create signature
ksort($params);
$signature = md5(implode($params) . $apiKey);
$params['signature'] = $signature;

// Make request
$url = 'https://www.lightsms.com/external/get/incoming.php?' . http_build_query($params);
$response = file_get_contents($url);

return json_decode($response, true);
}

function processIncomingMessages($login, $apiKey, $date) {
$messages = getIncomingMessages($login, $apiKey, $date);

if (empty($messages)) {
echo "No incoming messages for $date\n";
return;
}

echo "Processing " . count($messages) . " incoming messages:\n\n";

foreach ($messages as $id => $message) {
$sender = $message['sender'];
$text = strtoupper(trim($message['text']));
$receivedAt = $message['date'];

echo "[$receivedAt] From $sender: {$message['text']}\n";

// Handle keywords
if ($text === 'STOP') {
echo " → Adding $sender to blacklist\n";
addToBlacklist($login, $apiKey, $sender);
} elseif ($text === 'START') {
echo " → Removing $sender from blacklist\n";
removeFromBlacklist($login, $apiKey, $sender);
} elseif ($text === 'HELP') {
echo " → Sending help information to $sender\n";
sendHelpMessage($login, $apiKey, $sender);
} else {
echo " → Forwarding to customer support\n";
forwardToSupport($sender, $message['text']);
}

echo "\n";
}
}

// Configuration
$login = 'YourLogin';
$apiKey = 'your_api_key_here';
$date = date('Y-m-d'); // Today

processIncomingMessages($login, $apiKey, $date);
?>

Python - Keyword-Based Processing

import requests
import hashlib
from urllib.parse import urlencode
from datetime import datetime

def get_incoming_messages(login, api_key, date):
# Get timestamp
timestamp_response = requests.get('https://www.lightsms.com/external/get/timestamp.php')
timestamp = timestamp_response.text.strip()

# Prepare parameters
params = {
'login': login,
'date': date,
'timestamp': timestamp,
'return': 'json'
}

# Create signature
sorted_params = sorted(params.items())
param_string = ''.join([str(value) for key, value in sorted_params])
signature = hashlib.md5((param_string + api_key).encode()).hexdigest()
params['signature'] = signature

# Make request
url = f'https://www.lightsms.com/external/get/incoming.php?{urlencode(params)}'
response = requests.get(url)

return response.json() if response.text else {}

class IncomingSMSHandler:
def __init__(self, login, api_key):
self.login = login
self.api_key = api_key
self.keywords = {
'STOP': self.handle_stop,
'START': self.handle_start,
'HELP': self.handle_help,
'INFO': self.handle_info
}

def handle_stop(self, sender, message):
"""Handle unsubscribe request."""
print(f" ✋ Unsubscribe request from {sender}")
# Add to blacklist
# send_confirmation(sender, "You have been unsubscribed.")

def handle_start(self, sender, message):
"""Handle subscribe request."""
print(f" ✅ Subscribe request from {sender}")
# Remove from blacklist
# send_confirmation(sender, "You have been subscribed.")

def handle_help(self, sender, message):
"""Send help information."""
print(f" ❓ Help request from {sender}")
help_text = "Send STOP to unsubscribe, START to subscribe, INFO for details."
# send_sms(sender, help_text)

def handle_info(self, sender, message):
"""Send information."""
print(f" ℹ️ Info request from {sender}")
# send_info_message(sender)

def process_messages(self, date):
messages = get_incoming_messages(self.login, self.api_key, date)

if not messages:
print(f"No incoming messages for {date}")
return

print(f"Processing {len(messages)} incoming messages:\n")

for msg_id, message in messages.items():
sender = message['sender']
text = message['text'].strip().upper()
received_at = message['date']

print(f"[{received_at}] From {sender}: {message['text']}")

# Check for keywords
if text in self.keywords:
self.keywords[text](sender, message)
else:
print(f" 💬 Forwarding to customer support")
# forward_to_support(sender, message['text'])

print()

# Configuration
LOGIN = 'YourLogin'
API_KEY = 'your_api_key_here'

# Process today's incoming messages
handler = IncomingSMSHandler(LOGIN, API_KEY)
today = datetime.now().strftime('%Y-%m-%d')
handler.process_messages(today)

JavaScript - Auto-Reply System

const crypto = require('crypto');
const axios = require('axios');

async function getIncomingMessages(login, apiKey, date) {
// Get timestamp
const timestampResponse = await axios.get('https://www.lightsms.com/external/get/timestamp.php');
const timestamp = timestampResponse.data.trim();

// Prepare parameters
const params = {
login: login,
date: date,
timestamp: timestamp,
return: 'json'
};

// Create signature
const sortedKeys = Object.keys(params).sort();
const paramString = sortedKeys.map(key => params[key]).join('');
const signature = crypto.createHash('md5').update(paramString + apiKey).digest('hex');
params.signature = signature;

// Make request
const queryString = new URLSearchParams(params).toString();
const url = `https://www.lightsms.com/external/get/incoming.php?${queryString}`;
const response = await axios.get(url);

return response.data || {};
}

class AutoReplySystem {
constructor(login, apiKey) {
this.login = login;
this.apiKey = apiKey;

// Define auto-reply rules
this.rules = [
{
pattern: /^STOP$/i,
action: 'unsubscribe',
reply: 'You have been unsubscribed. Send START to re-subscribe.'
},
{
pattern: /^START$/i,
action: 'subscribe',
reply: 'You have been subscribed to our updates!'
},
{
pattern: /^HELP$/i,
action: 'help',
reply: 'Commands: STOP (unsubscribe), START (subscribe), BALANCE (check balance), HELP (this message)'
},
{
pattern: /^BALANCE$/i,
action: 'balance',
reply: 'Your current balance is: [balance]. Visit myaccount.com for details.'
}
];
}

async processMessage(message) {
const sender = message.sender;
const text = message.text.trim();

console.log(`Processing: "${text}" from ${sender}`);

// Check against rules
for (const rule of this.rules) {
if (rule.pattern.test(text)) {
console.log(` ✅ Matched rule: ${rule.action}`);
console.log(` 📤 Auto-reply: ${rule.reply}`);

// Send auto-reply
// await this.sendSMS(sender, rule.reply);

// Perform action
await this.performAction(rule.action, sender);

return true;
}
}

// No rule matched - forward to support
console.log(` 💬 No rule matched, forwarding to support`);
// await this.forwardToSupport(sender, text);

return false;
}

async performAction(action, sender) {
switch(action) {
case 'unsubscribe':
console.log(` Adding ${sender} to blacklist`);
// await addToBlacklist(sender);
break;

case 'subscribe':
console.log(` Removing ${sender} from blacklist`);
// await removeFromBlacklist(sender);
break;

case 'balance':
console.log(` Fetching balance for ${sender}`);
// const balance = await getCustomerBalance(sender);
break;

case 'help':
console.log(` Sending help information`);
break;
}
}

async processAllMessages(date) {
const messages = await getIncomingMessages(this.login, this.apiKey, date);

if (Object.keys(messages).length === 0) {
console.log(`No incoming messages for ${date}`);
return;
}

console.log(`Processing ${Object.keys(messages).length} messages:\n`);

for (const [id, message] of Object.entries(messages)) {
await this.processMessage(message);
console.log();
}
}
}

// Configuration
const LOGIN = 'YourLogin';
const API_KEY = 'your_api_key_here';

(async () => {
const autoReply = new AutoReplySystem(LOGIN, API_KEY);

// Process today's messages
const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
await autoReply.processAllMessages(today);
})();

Common Use Cases

1. Opt-Out Management

function handleOptOut($login, $apiKey, $date) {
$messages = getIncomingMessages($login, $apiKey, $date);

foreach ($messages as $message) {
$text = strtoupper(trim($message['text']));

if ($text === 'STOP' || $text === 'UNSUBSCRIBE') {
$sender = $message['sender'];

// Add to blacklist
addToBlacklist($login, $apiKey, $sender);

// Send confirmation
sendSMS($login, $apiKey, $sender, 'You have been unsubscribed.');

// Log for compliance
logOptOut($sender, date('Y-m-d H:i:s'));
}
}
}

2. Customer Support Ticketing

def create_support_tickets(login, api_key, date):
"""Create support tickets from incoming messages."""
messages = get_incoming_messages(login, api_key, date)

for msg_id, message in messages.items():
# Skip keyword responses
if message['text'].upper() in ['STOP', 'START', 'HELP']:
continue

# Create ticket
ticket = {
'id': msg_id,
'customer_phone': message['sender'],
'message': message['text'],
'received_at': message['date'],
'status': 'open'
}

# Save to database
# save_ticket(ticket)

# Send acknowledgment
# send_sms(message['sender'], "We received your message. Ticket #" + msg_id)

print(f"Created ticket #{msg_id} from {message['sender']}")

3. Poll/Survey Responses

async function processPollResponses(login, apiKey, date, pollId) {
const messages = await getIncomingMessages(login, apiKey, date);
const responses = {};

for (const [id, message] of Object.entries(messages)) {
const answer = message.text.trim().toUpperCase();

// Count responses (A, B, C, D, etc.)
if (/^[A-D]$/.test(answer)) {
responses[answer] = (responses[answer] || 0) + 1;
console.log(`Response from ${message.sender}: ${answer}`);
}
}

console.log('\nPoll Results:');
for (const [option, count] of Object.entries(responses)) {
console.log(` Option ${option}: ${count} votes`);
}

return responses;
}

Error Handling

Error 30: No Date Specified

Problem: Neither date nor from/to parameters provided

Solution: Include date parameter in format YYYY-MM-DD


Next Steps


Need Help?

For questions about incoming SMS: