JavaScript SMS API

Table of Contents

Enter the SMSAPI JavaScript library! Sending SMS with JS is simpler than you think. In this programmer’s guide, you’ll find both sample code fragments and a discussion of how to do things and how to tackle errors you may encounter.

I dealt with other SMS APIs libraries like JavaPHP, Python and C#, and I’ve even shown what to do with the incoming message. But this time, I’ll concentrate on the outbound messages sent via JavaScript Library. Lock and load! First off – a public service announcement: in January 2021, we released version 2.0.0 of the JavaScript library.

What’s changed? Quite a lot, as it introduces TypeScript support. It is a lesser-known “superstructure” for JavaScript (professionally, its superset), made by Microsoft. It means that any JavaScript code is also correct in TypeScript. The essential difference is that static typing has been added to the fully dynamic JS. Additionally, TypeScript is the first to support the important async/await mechanism. But all in good time.

Before you start sending SMS messages

You need to take a few steps of preparation before you deliver your first SMS. These will involve creating and configuring an account on our website or logging into yours. Either way, get access to the Customer Portal.

Free tests

Test our open SMS API and JavaScript library free of charge. Create a trial business account.

Selected features of the SMSAPI web portal

  • bulk SMS sending;
  • text message scheduling;
  • HLR lookup;
  • MMS messages;
  • 2Way SMS;
  • authentication credentials (2FA SMS);
  • OAuth2 tokens for connecting to the API;
  • SMS sender names (SMS branding);
  • URL shortener;
  • contact lists;
  • recipient groups;
  • SMS opt-out system;
  • invoicing information;
  • payments for SMS campaigns.

As you can see, the SMSAPI gateway and its Customer Portal itself gives you decent possibilities. Find the complete guide to setting up the SMSAPI account. Other texts and video guides on the blog showcase individual features of the panel – check out the Tutorials tab. Now let’s focus on the code.

We have divided each Library into modules responsible for individual functions. You can find all of it on the SMSAPI GitHub. Analysing individual files is, of course, the surest way to learn how to handle them. But, if you’d prefer to familiarise yourself while using it a little faster and with more fun – read on!

Business uses of SMS texts

  • Sending and receiving SMS from clients
  • SMS notifications and customer service
  • SMS marketing and sales-oriented messaging
  • Two-factor authentication (SMS 2FA)

Sending SMS messages through SMS API JavaScript

The foundation of automatic SMS handling are the HTTP methods. An HTTP client is an application’s core for communicating with the SMS API, which formulates these server queries through HTTP requests with all the necessary parameters. An example of such a solution is the popular Axios, written in JavaScript. It’s a solution our Library uses for making API requests. This way, you don’t have to provide your client. 

Preparing to work with the JavaScript SMS API

Installation

Use node.js package manager of your choice to install the library.

//npm
npm install smsapi

//yarn
yarn add smsapi

//pnpm
pnpm install smsapi

Initialisation

You’ll need to initialise the Library’s functions when working with the code. Nothing could be simpler! All you need to do is create a new instance of SMSAPI – the only parameter you need here is the authorisation token (API key) generated in the Customer Portal.

Initialisation – sample code:

import {SMSAPI} from 'smsapi';
const apiToken = '%SMSAPI_ACCESS_TOKEN%';
const smsapi = new SMSAPI(apiToken);

And that’s all! Axios does all the client configuration. A piece of advice: do not store your API key directly in your code – use non-public environment variables instead.

JavaScript: sending a single SMS

What’s the simplest way to send text messages and SMS notifications from a web app or JS application? Use the module with the fairly obvious name sms.

Code sample:

import {SMSAPI, MessageResponse} from 'smsapi'; // MessageResponse not used

const smsapi = new SMSAPI('[token]');

const receiver = '+44111222333';

const message = 'Hello world!';
smsapi.sms.sendSms(receiver, message);

The sendSms method is asynchronous, so it returns the Promise object known from JavaScript. This, in turn, is an envelope for the MessageResponse object. You need to wait for a response to be able to use the returned data. Now comes the async/await mechanism. Once sending is complete, the function below will display a status:

async function SendAndDisplayStatus(receiver, message) {
const response = await smsapi.sms.sendSms(receiver, message);
const response: MessageResponse = await smsapi.sms.sendSms(receiver, message); // Or like this, if you use MessageResponse

console.log(response.list[0].status);
}

The individual elements of the returned the response object are similar to the JSON response described in the API Documentation. You can log response for debugging purposes. It is possible to send SMS to multiple phone numbers at once, which leads us to the element called list. Its fields include:

  • status – one of the message delivery statuses;
  • id – a unique identifier in the SMSAPI system.
  • points – sending cost, or the number of points deducted from the SMSAPI account;
  • number – recipient phone number;
  • dateSent – send date.

You can see then that thanks to the SMS API library, the minimum SMS handling in JavaScript takes up two a mere two lines of code: creating the main SMSAPI object and ordering the HTTP client to send SMS messages:

const smsapi = new SMSAPI('%SMSAPI_ACCESS_TOKEN%');
smsapi.sms.sendSms('+44111222333', 'Hello world!');

Send messages to multiple recipients – JavaScript methods

Let’s move on. Since you intend to use software code to automate SMS sending to the customers’ phone numbers, you likely need more capabilities. Delivering identical messages to multiple recipients at once? Nothing could be simpler! All you need to do is to add a list of recipients instead of a single number to the same function.

async function SendMultipleAndDisplayStatuses(receivers, message) {	
const response = await smsapi.sms.sendSms(receivers, message);	
 	
for (const respList of response.list) {	
 console.log(respList.status);	
}	
}
	
SendMultipleAndDisplayStatuses(	
['+44111222333', '+44444555666'],	
'Hello receivers!'	
);

You’ll quickly spot the ability to join recipients into groups in the Customer Portal. Our Library in JavaScript allows you to use them. When a whole group is to receive the same content, you just need to use the following code:

async function SendToGroupAndDisplayStatuses(group, message) {	
const response = await smsapi.sms.sendSmsToGroup(group, message);
	
for (const respList of response.list) {	
 console.log(respList.status);	
}	
}
	
SendToGroupAndDisplayStatuses('group_name', 'Hello group!');

If the group the argument is a list, everything will execute correctly. The program will simply attempt to send SMS to all recipients from multiple groups.

Additional SMS options: customisation and scheduling

A message is better received if one feels treated like an individual. Such a minor thing, like addressing someone by their first name, can be the first step towards successful SMS marketing.

Customising messages means adding a more personal touch to individual messages. And you don’t have to manually type in every text separately. You can create content templates in the right section of your Customer Panel. Such as this one:

PackageSentTemplate: „Hi [%name%], your order has been sent!”

The [%name%] element will be replaced with relevant content if you have created a recipient database. It’s a simple way to ensure that every person receives a message addressed directly to them. Naturally, more field types are available – we’ve described them all in the Documentation.

Code snippet: using the SMS message template

async function NotifyPackageSent(receiver) {	
const details = {	
template: 'PackageSentTemplate'	
};
	
await smsapi.sms.sendSms(receiver, "", details);	
}

As you can see, I’ve skipped the message content, as it is included in the template. The details variable is of the SmsDetails type. It contains a number of additional data, which can be added to the messages to be sent. For example, character coding, date sent, the maximum number of message parts, the template used and custom parameters. You can find a more detailed description in the Documentation chapter on sending single messages. 

Scheduling a text message in JS

Next comes messaging scheduling: the  date field from the SmsDetails object allows you to schedule messages to be sent in the future. It is a standard JavaScript object of the Date type, so you can use the following command:

async function ScheduleSms(receiver, message, futureDate) {
const details = {
date: futureDate	
};
	
await smsapi.sms.sendSms(receiver, message, details);	
}

This unassuming function will allow you to schedule SMS campaigns! Just in case, you can find in the sms module, a function you can use to cancel the scheduled sending of an SMS. This is its signature:

async removeScheduledSms(smsId: string | string[]):
Promise<ScheduledSmsResponse>

The parameter it accepts is the unique identifier that you learn when it is sent. It is returned by the sendSms and sendSmsToGroup methods – see above.

SMS sender name

It is a short text displayed instead of the sender’s phone number. It allows the recipient to know who’s texting them immediately. It can be your brand name, for example. In SMS marketing, it’s the first opportunity to make a good impression on your customer.

To keep things safe and sound, our employee manually approves each new sender ID during our business hours. You can set sender names in the Customer Portal, and select one of them as the default name.

From the code perspective, they are handled by the sendernames module. It contains several useful methods for searching, creating and deleting sender names. The function below, for example, shows how you can overtly ensure that the text message will be sent with your default SMS sender ID.

async function sendSmsWithDefaultSenderName(receiver, message) {
const senderNamesList = await smsapi.sendernames.get();
	
for (let elem of senderNamesList.collection) {
if (elem.isDefault) {
await smsapi.sms.sendSms(receiver, message, {from: elem.sender});	
break;	
}	
}	
}

SMS sending errors

To protect your program from unpleasant surprises, you should include error handling in the code. The Axios (HTTP client) mentioned above returns an error code and message in the event of a sending failure. In such a situation, the SMS API library code will throw an exception with an error object of the MessageError type, which contains these two values.

You can find a detailed description of the API request error codes in the Documentation. Here are some of the most frequently encountered ones:

  • 11 – text message is too long or special characters are present while the nounicode parameter is used;
  • 12 – message part limit exceeded;
  • 13 – no correct recipient numbers;
  • 14 – incorrect sender name;
  • 26 – message subject is too long;
  • 101 – incorrect authorisation data (incorrect token);
  • 103 – insufficient points on the account to send the message.

Other SMS API modules for JavaScript

As I’ve mentioned in the beginning, the library code is divided into modules. Above we’ve learned about sms and sendernames – those most important for sending SMS. Some of the other modules are:

  • templates – used to handle content and data templates.
  • contacts – for creating and editing contacts. Contains minor modules for managing contact groups and custom fields for individual contacts.
  • mms – you can use it to send MMS messages in the SMIL format. 
  • profile – allows you to check your account details in SMSAPI, such as the number of available points, user details, and payment type.

If you want to learn more about other aspects of the JavaScript library for sending SMS, I refer you to the GitHub repository, and specifically to the files and unit tests. Find them in the individual subfolders, always under the name index.spec.ts. The tests are also examples of how to use the individual methods – it’s the simplest way to master them. Good luck!