Just create a file named Gateway.cs in your project and paste the following code into it. You also need to add Newtonsoft.Json NuGet package to your project.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Gateway_Sample_Application.Properties;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace SMS
{
static class API
{
private static readonly string Server = "https://teleos.in/sms-login";
private static readonly string Key = "YOUR_API_KEY";
public enum Option
{
USE_SPECIFIED = 0,
USE_ALL_DEVICES = 1,
USE_ALL_SIMS = 2
}
/// <summary>
/// Send single message to specific mobile number.
/// </summary>
/// <param name="number">The mobile number where you want to send message.</param>
/// <param name="message">The message you want to send.</param>
/// <param name="device">The ID of a device you want to use to send this message.</param>
/// <param name="schedule">Set it to timestamp when you want to send this message.</param>
/// <param name="isMMS">Set it to true if you want to send MMS message instead of SMS.</param>
/// <param name="attachments">Comma separated list of image links you want to attach to the message. Only works for MMS messages.</param>
/// <exception>If there is an error while sending a message.</exception>
/// <returns>The dictionary containing information about the message.</returns>
public static Dictionary<string, object> SendSingleMessage(string number, string message, string device = "0",
long? schedule = null, bool isMMS = false, string attachments = null)
{
var values = new Dictionary<string, object>
{
{"number", number},
{"message", message},
{"schedule", schedule},
{"key", Key},
{"devices", device},
{"type", isMMS ? "mms" : "sms"},
{"attachments", attachments}
};
return GetMessages(GetResponse($"{Server}/services/send.php", values)["messages"])[0];
}
/// <summary>
/// Send multiple messages to different mobile numbers.
/// </summary>
/// <param name="messages">The array containing numbers and messages.</param>
/// <param name="option">Set this to USE_SPECIFIED if you want to use devices and SIMs specified in devices argument.
/// Set this to USE_ALL_DEVICES if you want to use all available devices and their default SIM to send messages.
/// Set this to USE_ALL_SIMS if you want to use all available devices and all their SIMs to send messages.</param>
/// <param name="devices">The array of ID of devices you want to use to send these messages.</param>
/// <param name="schedule">Set it to timestamp when you want to send this message.</param>
/// <param name="useRandomDevice">Set it to true if you want to send messages using only one random device from selected devices.</param>
/// <exception>If there is an error while sending messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] SendMessages(List<Dictionary<string, string>> messages,
Option option = Option.USE_SPECIFIED, string[] devices = null, long? schedule = null,
bool useRandomDevice = false)
{
var values = new Dictionary<string, object>
{
{"messages", JsonConvert.SerializeObject(messages)},
{"schedule", schedule},
{"key", Key},
{"devices", devices},
{"option", (int) option},
{"useRandomDevice", useRandomDevice}
};
return GetMessages(GetResponse($"{Server}/services/send.php", values)["messages"]);
}
/// <summary>
/// Send a message to contacts in specified contacts list.
/// </summary>
/// <param name="listID">The ID of the contacts list where you want to send this message.</param>
/// <param name="message">The message you want to send.</param>
/// <param name="option">Set this to USE_SPECIFIED if you want to use devices and SIMs specified in devices argument.
/// Set this to USE_ALL_DEVICES if you want to use all available devices and their default SIM to send messages.
/// Set this to USE_ALL_SIMS if you want to use all available devices and all their SIMs to send messages.</param>
/// <param name="devices">The array of ID of devices you want to use to send these messages.</param>
/// <param name="schedule">Set it to timestamp when you want to send this message.</param>
/// <param name="isMMS">Set it to true if you want to send MMS message instead of SMS.</param>
/// <param name="attachments">Comma separated list of image links you want to attach to the message. Only works for MMS messages.</param>
/// <exception>If there is an error while sending messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] SendMessageToContactsList(int listID, string message,
Option option = Option.USE_SPECIFIED, string[] devices = null, long? schedule = null, bool isMMS = false,
string attachments = null)
{
var values = new Dictionary<string, object>
{
{"listID", listID},
{"message", message},
{"schedule", schedule},
{"key", Key},
{"devices", devices},
{"option", (int) option},
{"type", isMMS ? "mms" : "sms"},
{"attachments", attachments}
};
return GetMessages(GetResponse($"{Server}/services/send.php", values)["messages"]);
}
/// <summary>
/// Get a message using the ID.
/// </summary>
/// <param name="id">The ID of a message you want to retrieve.</param>
/// <exception>If there is an error while getting a message.</exception>
/// <returns>The dictionary containing information about the message.</returns>
public static Dictionary<string, object> GetMessageByID(int id)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"id", id}
};
return GetMessages(GetResponse($"{Server}/services/read-messages.php", values)["messages"])[0];
}
/// <summary>
/// Get messages using the Group ID.
/// </summary>
/// <param name="groupID">The group ID of messages you want to retrieve.</param>
/// <exception>If there is an error while getting messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] GetMessagesByGroupID(string groupID)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"groupId", groupID}
};
return GetMessages(GetResponse($"{Server}/services/read-messages.php", values)["messages"]);
}
/// <summary>
/// Get messages using the status.
/// </summary>
/// <param name="status">The status of messages you want to retrieve.</param>
/// <param name="startTimestamp">Search for messages sent or received after this time.</param>
/// <param name="endTimestamp">Search for messages sent or received before this time.</param>
/// <exception>If there is an error while getting messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] GetMessagesByStatus(string status, long? startTimestamp = null,
long? endTimestamp = null)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"status", status},
{"startTimestamp", startTimestamp},
{"endTimestamp", endTimestamp}
};
return GetMessages(GetResponse($"{Server}/services/read-messages.php", values)["messages"]);
}
/// <summary>
/// Resend a message using the ID.
/// </summary>
/// <param name="id">The ID of a message you want to resend.</param>
/// <exception>If there is an error while resending a message.</exception>
/// <returns>The dictionary containing information about the message.</returns>
public static Dictionary<string, object> ResendMessageByID(int id)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"id", id}
};
return GetMessages(GetResponse($"{Server}/services/resend.php", values)["messages"])[0];
}
/// <summary>
/// Resend messages using the Group ID.
/// </summary>
/// <param name="groupID">The group ID of messages you want to resend.</param>
/// <param name="status">The status of messages you want to resend.</param>
/// <exception>If there is an error while resending messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] ResendMessagesByGroupID(string groupID, string status = null)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"groupId", groupID},
{"status", status}
};
return GetMessages(GetResponse($"{Server}/services/resend.php", values)["messages"]);
}
/// <summary>
/// Resend messages using the status.
/// </summary>
/// <param name="status">The status of messages you want to resend.</param>
/// <param name="startTimestamp">Resend messages sent or received after this time.</param>
/// <param name="endTimestamp">Resend messages sent or received before this time.</param>
/// <exception>If there is an error while resending messages.</exception>
/// <returns>The array containing messages.</returns>
public static Dictionary<string, object>[] ResendMessagesByStatus(string status, long? startTimestamp = null,
long? endTimestamp = null)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"status", status},
{"startTimestamp", startTimestamp},
{"endTimestamp", endTimestamp}
};
return GetMessages(GetResponse($"{Server}/services/resend.php", values)["messages"]);
}
/// <summary>
/// Add a new contact to contacts list.
/// </summary>
/// <param name="listID">The ID of the contacts list where you want to add this contact.</param>
/// <param name="number">The mobile number of the contact.</param>
/// <param name="name">The name of the contact.</param>
/// <param name="resubscribe">Set it to true if you want to resubscribe this contact if it already exists.</param>
/// <returns>A dictionary containing details about a newly added contact.</returns>
public static Dictionary<string, object> AddContact(int listID, string number, string name = null,
bool resubscribe = false)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"listID", listID},
{"number", number},
{"name", name},
{"resubscribe", resubscribe ? '1' : '0'},
};
JObject jObject = (JObject) GetResponse($"{Server}/services/manage-contacts.php", values)["contact"];
return jObject.ToObject<Dictionary<string, object>>();
}
/// <summary>
/// Unsubscribe a contact from the contacts list.
/// </summary>
/// <param name="listID">The ID of the contacts list from which you want to unsubscribe this contact.</param>
/// <param name="number">The mobile number of the contact.</param>
/// <returns>A dictionary containing details about the unsubscribed contact.</returns>
public static Dictionary<string, object> UnsubscribeContact(int listID, string number)
{
var values = new Dictionary<string, object>
{
{"key", Key},
{"listID", listID},
{"number", number},
{"unsubscribe", '1'}
};
JObject jObject = (JObject) GetResponse($"{Server}/services/manage-contacts.php", values)["contact"];
return jObject.ToObject<Dictionary<string, object>>();
}
/// <summary>
/// Get remaining message credits.
/// </summary>
/// <exception>If there is an error while getting message credits.</exception>
/// <returns>The amount of message credits left.</returns>
public static string GetBalance()
{
var values = new Dictionary<string, object>
{
{"key", Key}
};
JToken credits = GetResponse($"{Server}/services/send.php", values)["credits"];
if (credits.Type != JTokenType.Null)
{
return credits.ToString();
}
return "Unlimited";
}
private static Dictionary<string, object>[] GetMessages(JToken messagesJToken)
{
JArray jArray = (JArray) messagesJToken;
var messages = new Dictionary<string, object>[jArray.Count];
for (var index = 0; index < jArray.Count; index++)
{
messages[index] = jArray[index].ToObject<Dictionary<string, object>>();
}
return messages;
}
private static JToken GetResponse(string url, Dictionary<string, object> postData)
{
var request = (HttpWebRequest) WebRequest.Create(url);
var dataString = CreateDataString(postData);
var data = Encoding.UTF8.GetBytes(dataString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonResponse = streamReader.ReadToEnd();
try
{
JObject jObject = JObject.Parse(jsonResponse);
if ((bool) jObject["success"])
{
return jObject["data"];
}
throw new Exception(jObject["error"]["message"].ToString());
}
catch (JsonReaderException)
{
if (string.IsNullOrEmpty(jsonResponse))
{
throw new InvalidDataException(
"Missing data in request. Please provide all the required information to send messages.");
}
throw new Exception(jsonResponse);
}
}
}
throw new WebException($"HTTP Error : {(int) response.StatusCode} {response.StatusCode}");
}
private static string CreateDataString(Dictionary<string, object> data)
{
StringBuilder dataString = new StringBuilder();
bool first = true;
foreach (var obj in data)
{
if (obj.Value != null)
{
if (first)
{
first = false;
}
else
{
dataString.Append("&" );
}
dataString.Append(HttpUtility.UrlEncode(obj.Key));
dataString.Append("=");
dataString.Append(obj.Value is string[]
? HttpUtility.UrlEncode(JsonConvert.SerializeObject(obj.Value))
: HttpUtility.UrlEncode(obj.Value.ToString()));
}
}
return dataString.ToString();
}
}
}
Send Single Message
try
{
// Send a message using the primary device.
SMS.API.SendSingleMessage("+11234567890", "This is a test of single message.");
// Send a message using the Device ID 1.
Dictionary<string, object> message = SMS.API.SendSingleMessage("+11234567890", "This is a test of single message.", "1");
// Send a MMS message using the Device ID 1.
string attachments = "https://example.com/images/footer-logo.png,https://example.com/downloads/images/section/create-chat-bot.png";
Dictionary<string, object> message = SMS.API.SendSingleMessage("+11234567890", "This is a test of single message.", "1", null, true, attachments);
// Send a message using the SIM in slot 1 of Device ID 1 (Represented as "1|0").
// SIM slot is an index so the index of the first SIM is 0 and the index of the second SIM is 1.
// In this example, 1 represents Device ID and 0 represents SIM slot index.
Dictionary<string, object> message = SMS.API.SendSingleMessage("+11234567890", "This is a test of single message.", "1|0");
// Send scheduled message using the primary device.
long timestamp = (long) DateTime.UtcNow.AddMinutes(2).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Dictionary<string, object> message = SendSingleMessage(textBoxNumber.Text, textBoxMessage.Text, null, timestamp);
MessageBox.Show("Successfully sent a message.");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Send Bulk Messages
List<Dictionary<string, string>> messages = new List<Dictionary<string, string>>();
for (int i = 1; i <= 12; i++)
{
var message = new Dictionary<string, string>
{
{ "number", "+11234567890" },
{ "message", "This is a test #{$i} of C# version. Testing bulk message functionality." }
};
messages.Add(message);
}
try
{
// Send messages using the primary device.
SMS.API.SendMessages(messages);
// Send messages using default SIM of all available devices. Messages will be split between all devices.
SMS.API.SendMessages(messages, SMS.API.Option.USE_ALL_DEVICES);
// Send messages using all SIMs of all available devices. Messages will be split between all SIMs.
SMS.API.SendMessages(messages, SMS.API.Option.USE_ALL_SIMS);
// Send messages using only specified devices. Messages will be split between devices or SIMs you specified.
// If you send 12 messages using this code then 4 messages will be sent by Device ID 1, other 4 by SIM in slot 1 of
// Device ID 2 (Represendted as "2|0") and remaining 4 by SIM in slot 2 of Device ID 2 (Represendted as "2|1").
SMS.API.SendMessages(messages, SMS.API.Option.USE_SPECIFIED, new [] {"1", "2|0", "2|1"});
// Send messages on schedule using the primary device.
long timestamp = (long) DateTime.UtcNow.AddMinutes(2).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Dictionary<string, object>[] messages = SMS.API.SendMessages(messages, Option.USE_SPECIFIED, null, timestamp);
// Send a message to contacts in contacts list with ID of 1.
Dictionary<string, object>[] messages = SMS.API.SendMessageToContactsList(1, "Test", SMS.API.Option.USE_SPECIFIED, new [] {"1"});
// Send a message on schedule to contacts in contacts list with ID of 1.
Dictionary<string, object>[] messages = SMS.API.SendMessageToContactsList(1, "Test #1", Option.USE_SPECIFIED, null, timestamp);
string attachments = "https://example.com/images/footer-logo.png,https://example.com/downloads/images/section/create-chat-bot.png";
List<Dictionary<string, string>> mmsMessages = new List<Dictionary<string, string>>();
for (int i = 1; i <= 12; i++)
{
var message = new Dictionary<string, string>
{
{ "number", "+11234567890" },
{ "message", "This is a test #{$i} of C# version. Testing bulk MMS message functionality." },
{ "type", "mms" },
{ "attachments", attachments }
};
mmsMessages.Add(message);
}
// Send messages using all SIMs of all available devices. Messages will be split between all SIMs.
SMS.API.SendMessages(messages, SMS.API.Option.USE_ALL_SIMS);
MessageBox.Show("Success");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Get remaining message credits
try
{
string credits = SMS.API.GetBalance();
MessageBox.Show($"Message Credits Remaining: {credits}");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Get messages and their current status
try
{
// Get a message using the ID.
Dictionary<string, object> message = SMS.API.GetMessageByID(1);
// Get messages using the Group ID.
Dictionary<string, object>[] messages = SMS.API.GetMessagesByGroupID("fV5LxqyBMEbQrl9*J$5bb4c03e8a07b7.62193871");
// Get messages received in last 24 hours.
long timestamp = (long) DateTime.UtcNow.AddHours(-24).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
messages = GetMessagesByStatus("Received", timestamp);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Resend messages
try
{
// Resend a message using the ID.
Dictionary<string, object> message = SMS.API.ResendMessageByID(1);
// Resend messages using the Group ID and Status.
Dictionary<string, object>[] messages = SMS.API.ResendMessagesByGroupID("LV5LxqyBMEbQrl9*J$5bb4c03e8a07b7.62193871", "Failed");
// Resend pending messages in last 24 hours.
long timestamp = (long) DateTime.UtcNow.AddHours(-24).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
messages = ResendMessagesByStatus("Pending", timestamp);
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Manage Contacts
try {
// Add a new contact to contacts list 1 or resubscribe the contact if it already exists.
Dictionary<string, object> contact = SMS.API.AddContact(1, "+11234567890", "Test C#", true);
// Unsubscribe a contact using the mobile number.
Dictionary<string, object> contact = UnsubscribeContact(1, "+11234567890");
}
catch (Exception exception)
{
MessageBox.Show(exception.Message, "!Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}