ES

Node.js library for SMS sending

The SMS API Node.js Library is designed for technicians and customers who want to connect their applications to LabsMobile's SMS messaging platform.

The functionalities of this library are:

  • The sending of SMS messages individually or massively in real time.
  • Scheduled sending of SMS messages.
  • Sending SMS Unicode, SMS Concatenated messages and SMS Certified messages.
  • Consulting the balance of credits in an account
  • Price query per country
  • Consult HLR of status and availability of a mobile number

This documentation explains in detail the process of integration and automation of these functionalities.

Requirements

  • A compatible version of Node.js. This library is compatible with Node.js v16.19.0 and higher versions.
  • Install npm compatible with the installed Node.js version.
  • Install this library labsmobile-sms via npm.
  • A LabsMobile account associated with a username (registration email). Create an account here.
  • API token used as password and generated from the API Settings section of your account.
  • Validation of this documentation. More information in the HTTP/POST SMS API documentation.

To be taken into account

For more details on the Node.js library, see the official repository on Github.


Authentication

The authentication method used is Auth Basic HTTP through credentials (username of the account and a tokenapi) included in the configuration and initialization of the library.

Before calling any function of this library it is necessary to initialize the credentials as shown in the code examples.

Recommendation You can generate API tokens from the API Settings of the account. We recommend changing the token frequently and using different tokens for each use, connection or integration.


Configuration and filters

The following are important configuration variables and security aspects in an integration with the SMS http/GET API:

  • IP address from which messages will be sent. If this option is enabled, only requests from the list of IP addresses entered will be accepted. This functionality is optional, by default messages will be accepted from any IP.
  • Default sender (default LABSMOBILE). Only some operators allow dynamic, alphanumeric-valued mapping of the sender field.
  • Daily message limit, by default 100,000 sms/day.
  • Message limit per batch, default 10,000 sms/request.
  • Country filter, so that only messages from a list of countries are processed.
  • Anti-duplication filter, to avoid sending identical messages to the same recipient.

All these parameters can be activated and modified in the API Settings and Account Preferences.

Important A maximum of 10 requests per second is established. Misuse, abuse or a higher volume of requests will result in a temporary or permanent blocking of the account and/or IP address.

Recommendation We recommend activating the Automatic Top-Ups so that there are always credits available in the account and the SMS sending service is not interrupted.


Installation of composer and LabsMobile SMS library

To install npm it is necessary to follow the instructions according to the operating system.

The LabsMobile PHP library can be installed in two ways:

  • Use the following command line command, inside the project directory
Command line installation
npm i labsmobile-sms
              
  • Create a file named package.json. In that file, include:
Installation from package.json file
"dependencies": {
	"labsmobile-sms": "1.0.1"
}
                

It is essential to import the necessary classes from the labsmobile-sms namespace. These classes provide the functions and classes to interact with the LabsMobile API.

You must indicate the authentication credentials in the username and token variables when initializing the LabsMobileClient class.


Sending SMS messages

Function for basic and multiple sending of SMS messages.

FUNCTION

sendSMS(new LabsMobileModelTextMessage(numbers, message)).

To send SMS messages, follow these steps:

  1. Initialize the LabsMobileModelTextMessage class with the mandatory parameters (the destination numbers and the message text).
  2. Include parameter options such as programming, simulated mode, etc.
  3. Finally call the sendSMS() function to perform the actual sending.
  4. Finally, it is recommended to review the outcome of the request.
  • Expand all

    PARAMETERS

    All possible parameters for sending SMS messages are described below.

  • RESULT

    The result is obtained in JSON format with the following elements:

Basic sending to a single recipient
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const LabsMobileModelTextMessage = require("labsmobile-sms/src/LabsMobileModelTextMessage");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function sendSmsTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const message = "Your verification code is 123";
   const phone = ["12015550123"];
   const clientLabsMobile = new LabsMobileClient(username, token);
   const bodySms = new LabsMobileModelTextMessage(phone, message);
   bodySms.scheduled = "2024-12-02 09:00:00";
   bodySms.long = 1;
   const response = await clientLabsMobile.sendSms(bodySms);
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

sendSmsTest()
                
Bulk sending to multiple recipients
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const LabsMobileModelTextMessage = require("labsmobile-sms/src/LabsMobileModelTextMessage");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function sendSmsTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const message = "Don't miss our Sale! Use code XXXX123 for 20% off.";
   const phone = ["12015550123","12015550124","12015550125"];
   const clientLabsMobile = new LabsMobileClient(username, token);
   const bodySms = new LabsMobileModelTextMessage(phone, message);
   bodySms.scheduled = "2024-12-02 09:00:00";
   bodySms.ucs2 = 1;
   bodySms.long = 1;
   const response = await clientLabsMobile.sendSms(bodySms);
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

sendSmsTest()
                
Positive result
{
  "subid": "65f33a88ceb3d",
  "code": "0",
  "message": "Message has been successfully sent."
}
  
Wrong result
{
  "subid": "65f7f7041385d",
  "code": "35",
  "message": "The account has no enough credit for this sending"
}
  

Balance inquiry

Function to obtain the balance of credits available in an account.

FUNCTION

getCredit().

This function has no parameters and returns the following result.

  • RESULT

    The result of any request is obtained in JSON format with the following elements:

Account balance inquiry
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function getCreditTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const clientLabsMobile = new LabsMobileClient(username, token);
   const response = await clientLabsMobile.getCredit();
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

getCreditTest()
                
Result
{"code":0,"credits":"10"}

  

Scheduled sending management

Function to cancel or send programmed messages.

To specify the parameters, the class LabsMobileModelScheduledSendings() must be initialized with the following parameters and then call the scheduledSendings() function.

FUNCTION

scheduledSendings(new LabsMobileModelScheduledSendings(subid, cmd)).

  • PARAMETERS

  • RESULT

    The result is obtained in JSON format with the following elements:

Manage scheduled sendings
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const LabsMobileModelScheduledSendings = require("labsmobile-sms/src/LabsMobileModelScheduledSendings");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function scheduledSendingsTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const subid = "mysubid";
   const cmd = "XXXXXX"; // send or cancel
   const clientLabsMobile = new LabsMobileClient(username, token);
   const scheduledSendings = new LabsMobileModelScheduledSendings(subid, cmd);
   const response = await clientLabsMobile.scheduledSendings(
     scheduledSendings
   );
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

scheduledSendingsTest()
                
Positive result send
{
  "code": 0,
  "message": "Scheduled messages successfully sent."
}
  
Positive result canceled
{
    "code": 0,
    "message": "Scheduled messages successfully cancelled."
}
  
Wrong result
{
    "code": 52,
    "message": "Scheduled messages not found."
}
  

Price inquiry

Function to consult the prices of a standard SMS in credits of each country.

To indicate the parameters, the LabsMobileModelCountryPrice() class must be initialized with the following parameters and then call the getpricesCountry() function.

FUNCTION

getpricesCountry(new LabsMobileModelCountryPrice(countries)).

  • PARAMETERS

  • Expand all

    RESULT

    The result is obtained in JSON format with the following elements:

Check prices by country
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const LabsMobileModelCountryPrice = require("labsmobile-sms/src/LabsMobileModelCountryPrice");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function getpricesCountryTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const countries = ["CO", "ES"];
   const clientLabsMobile = new LabsMobileClient(username, token);
   const countriesPrice = new LabsMobileModelCountryPrice(countries);
   const response = await clientLabsMobile.getpricesCountry(countriesPrice);
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

getpricesCountryTest()
                
Positive result
{
    "CO": {
        "isocode": "CO",
        "prefix": "57",
        "name": "Colombia",
        "credits": 0.043
    },
    "ES": {
        "isocode": "ES",
        "prefix": "34",
        "name": "Spain",
        "credits": 1
    }
}
  

HLR Lookup query

Function to check the status and availability of one or more mobile numbers.

To indicate the parameters, the LabsMobileModelHlrRequest() class must be initialized with the numbers to query and then call the hlrRequest() function.

FUNCTION

hlrRequest(new LabsMobileModelHlrRequest(numbers)).

  • PARAMETERS

  • Expand all

    RESULT

    The result of any HLR request is obtained in JSON format with the values detailed below:

  • Expand all

    RESULT BY NUMBER

Cell phone status query
const LabsMobileClient = require("labsmobile-sms/src/LabsMobileClient");
const LabsMobileModelHlrRequest = require("labsmobile-sms/src/LabsMobileModelHlrRequest");
const ParametersException = require("labsmobile-sms/src/Exception/ParametersException");
const RestException = require("labsmobile-sms/src/Exception/RestException");

async function hlrRequestTest() {
 try {
   const username = "myusername";
   const token = "mytoken";
   const numbers = [];
   const clientLabsMobile = new LabsMobileClient(username, token);
   const hlr = new LabsMobileModelHlrRequest(numbers);
   const response = await clientLabsMobile.hlrRequest(hlr);
   console.log(response);
 } catch (error) {
   if (error instanceof ParametersException) {
     console.log(error.message);
   } else if (error instanceof RestException) {
     console.log(`Error: ${error.status} - ${error.message}`);
   } else {
     throw new Error("Error: " + error);
   }
 }
}

hlrRequestTest()
                
Positive result
{
  "result":"ok",
  "error":"",
  "numbers":[
    {
      "msisdn":"573051155514",
      "status":"active",
      "country_name":"Colombia",
      "country_code":"57",
      "country_iso":"CO",
      "network":"Colombia Movil SA(TIGO)",
      "mcc":"732",
      "mnc":"103",
      "format":"valid",
      "type":"mobile"
    }],
    "count":1,
    "credits":0.1
  }
  

Errors

The HTTP error codes that may be returned by a request are described below.

HTTP codes
HTTP CodeDescription
200 OKRequest processed correctly.
400 Bad RequestError in the request parameters. The error is detailed and specified in the code returned in JSON format.
401 UnauthorizedError in credentials or authentication method.
402 Payment RequiredError due to lack of credits in the account.
403 ForbiddenRequest blocked by the IP filter or for violating any platform usage policy.
500 Internal Server ErrorTemporary error or incidence in the service

This is the complete list of response codes in JSON format:

Result codes in the response JSON
JSON CodeDescription
0Message has been successfully sent
10Missing XML data in request
11Badly formed XML in request
20The message element must be present in the request
21The message element cannot be empty
23There are no recipients
24Too many recipients
27This message contained one or more invalid character(s)
28Subid is exceeding maximum length
30There was an error while sending the message
35The account has no enough credit for this sending
39The value of the scheduled field is not a valid datetime format
41Scheduled messages cannot be send in test mode
51Compulsary fields not defined.
52Scheduled messages not found.