ES

PHP library for sending SMS

The SMS API PHP 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 PHP. This library is compatible with php v5.4 and higher versions.
  • Install Composer. It is recommended to use Composer 2.2.22.
  • Install this library labsmobile/sms-php via composer.
  • 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 about the PHP 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

Important configuration variables and security aspects of any integration are detailed below:

  • 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 Composer it is necessary to follow the instructions depending on the operating system.

The LabsMobile PHP library can be installed in two ways:

  • From the command line, while inside the project directory
Command line installation
composer require labsmobile/sms-php
              
  • Creating a file composer.json. In this file, you must include:
Installation from composer.json file
"require": {
	"labsmobile/sms-php": "1.0.1"
}
                

It is essential to import the necessary classes from the Labsmobile\SmsPhp 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.

Advice We recommend including the auto-load file vendor/autoload.php, which is commonly used in applications that use Composer to manage their dependencies.


Sending SMS messages

Function for basic and multiple sending of SMS messages.

FUNCTION

sendSMSMS(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
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\LabsMobileModelTextMessage;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileSendSms
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function sendSms()
 {
   try {
     $message = 'Your verification code is 123';
     $phone = ['12015550123'];
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $bodySms = new LabsMobileModelTextMessage($phone,$message);
     $bodySms->setScheduled("2024-12-02 09:00:00");
     $bodySms->setLong(1);
     $labsMobileClient = $labsMobileClient->sendSms($bodySms);
     $body = $labsMobileClient->getBody();
     $json = json_decode($body);
     echo 'Status ', $json->code . " " . $json->message;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileSendSms();
$smsSender->sendSms();
                
Bulk sending to multiple recipients
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\LabsMobileModelTextMessage;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileSendSms
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function sendSms()
 {
   try {
     $message = 'Do not miss our Sale! Use code XXXX123 for 20% off.';
     $phone = ['12015550123','12015550124','12015550125'];
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $bodySms = new LabsMobileModelTextMessage($phone,$message);
     $bodySms->setScheduled("2024-12-02 09:00:00");
     $bodySms->setUcs2(1);
     $bodySms->setShortlink(1);
     $bodySms->setTest(1);
     $labsMobileClient = $labsMobileClient->sendSms($bodySms);
     $body = $labsMobileClient->getBody();
     $json = json_decode($body);
     echo 'Status ', $json->code . " " . $json->message;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileSendSms();
$smsSender->sendSms();
                
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:

Balance inquiry
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileGetCredits
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function getCredits()
 {
   try {
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $response = $labsMobileClient->getCredit();
     $body = $response->getBody();
     echo 'Status ', $body;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileGetCredits();
$smsSender->getCredits();
                
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:

Scheduled sending management
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\LabsMobileModelScheduledSendings;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileScheduledSendings
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function scheduledSendings()
 {
   try {
     $subid="XXXXXXXXXX";  //Identificador de la solicitud de envío
     $cmd="XXXX"; //Comando a ejecutar. Los valores posibles son cancely send
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $bodyScheduled = new LabsMobileModelScheduledSendings($subid, $cmd);
     $labsMobileClient = $labsMobileClient->scheduledSendings($bodyScheduled);
     $body = $labsMobileClient->getBody();
     echo 'Status ', $body;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileScheduledSendings();
$smsSender->scheduledSendings();
                
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
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\LabsMobileModelCountryPrice;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileCountryPrice
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function countryPrice()
 {
   try {
     $countries = ["CO","ES"];
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $bodyContries = new LabsMobileModelCountryPrice($countries);
     $labsMobileClient = $labsMobileClient->getpricesCountry($bodyContries);
     $body = $labsMobileClient->getBody();
     echo 'Status ', $body;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileCountryPrice();
$smsSender->countryPrice();
                
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

HLR Query
<?php 
require __DIR__ . '/../vendor/autoload.php';

use Labsmobile\SmsPhp\LabsMobileClient;
use Labsmobile\SmsPhp\LabsMobileModelHlrRequest;
use Labsmobile\SmsPhp\Exception\RestException;

class LabsMobileHlr
{
 public $username = 'myUsername';
 public $token = 'myToken';

 public function hlr()
 {
   try {
     $numbers = [];//[34XXXXXXXX,34XXXXXXXX]
     $labsMobileClient = new LabsMobileClient($this->username, $this->token);
     $bodyHlr = new LabsMobileModelHlrRequest(json_encode($numbers));
     $labsMobileClient = $labsMobileClient->hlrRequest($bodyHlr);
     $body = $labsMobileClient->getBody();
     echo 'Status ', $body;
   } catch (RestException $exception) {
     echo 'Error ', $exception->getStatus() ." ". $exception->getMessage();
   }
 }
}

$smsSender = new LabsMobileHlr();
$smsSender->hlr();
                
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.