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.
- Installation of composer on Linux / Unix / macOS. More information at getcomposer.org .
- Composer installation on Windows. More information at getcomposer.org .
The LabsMobile PHP library can be installed in two ways:
- From the command line, while inside the project directory
composer require labsmobile/sms-php
- Creating a file composer.json. In this file, you must include:
"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(
.
To send SMS messages, follow these steps:
- Initialize the
LabsMobileModelTextMessage
class with the mandatory parameters (the destination numbers and the message text). - Include parameter options such as programming, simulated mode, etc.
- Finally call the
sendSMS()
function to perform the actual sending. - Finally, it is recommended to review the outcome of the request.
- Expand all
PARAMETERS
All possible parameters for sending SMS messages are described below.
numbers string | array mandatory
Telephone numbers of the recipients to whom the message is sent. The numbers must comply with the international format E.164 and separated by commas (",") if more than one destination number is included.
Example:
LabsMobileModelModelTextMessage("34609362742", $message)
.message string mandatory
Text of the message to be sent. When sending standard SMS only GSM 3.38 7bit alphabet characters are valid. You can also send Concatenated SMS and Unicode SMS with the corresponding parameters.
Example:
LabsMobileModelTextMessage(
.$numbers, "Hello world, this is my first message"). scheduled YYYY-MM-DD HH:MM:SS
Scheduling of sending for the day and time indicated. If this field is not specified, the message will be sent immediately. Format:
YYYYYY-MM-DD HH:MM:SS
.Important: The value of this field must be expressed in GMT time zone.
Example:
setScheduled("2024-04-12 10:00:00")
.tpoa string
SMS message sender field. It can have a numeric value (maximum length 16 digits) or an alphanumeric value (maximum length 11 characters).
Sender assignment and customization is only available in some countries and operators. Otherwise, the sender will be a static numeric value (shortcode or longcode).
Example:
setTpoa("MyBrand")
.subid string
Request identifier. Maximum length of 20 characters.
If no value is included in the
subid
parameter, the platform will assign a unique 13-character identifier that will be displayed in the request result.Example:
setSubid("5aa3ea802828ce5")
.label string
Free information field to identify and assign attributes. Maximum length of 255 characters.
Possible uses: user, application, grouping or campaign, etc.
Example:
setLabel("A05-Jan-2024")
.test 0 | 1
Activation of simulated send mode for testing and monitoring.
If a value
1
is assigned to this parameter, the messages will not be sent to the recipients and no credit will be deducted. Messages sent in simulated mode will be available in the History and other tools.Example:
setTest(1)
.ackurl url
Url to which delivery confirmation and error notifications of sent messages will be sent.
A default URL can be set in the Account API Settings and in that case it is not necessary to include this parameter.
Example:
setAckurl("https://clientserver.com/receive_ack")
.clickurl url
Url to which the event notifications will be sent when clicking on the links in the sent messages.
A default URL can be set in the Account API Settings and in that case it is not necessary to include this parameter.
Example:
setClickurl("https://clientserver.com/receive_click")
.shortlink 0 | 1
Activation of automatic link replacement.
If its value is
1
all Urls in the message will be replaced with a short link (format:labsmo.bi/XXXXXXXXX
or custom domain).You can enable this feature permanently for all messages in the Account Preferences and in that case you do not need to include this parameter.
Example:
setShortlink(1)
.long 0 | 1
Activation of the SMS Concatenated in this request.
If this field has value
1
the message can contain more than 160 characters. Learn more about How to calculate the price of an SMS.Example:
setLong(1)
.ucs2 0 | 1
Activation of the SMS Unicode in this request.
If this field has value
1
the message can contain any character, symbol or emoji. The capacity is reduced to 70 characters and concatenated and unicode SMS can be sent. Learn more about How to calculate the price of an SMS.Example:
setUcs2(1)
.crt email
Sending a SMS Certificate in this request.
An e-mail with the certification PDF document will be sent to the address containing this parameter.
Example:
setCrt("info@client.es")
.crt_name string
Name of the entity or company sending the certified SMS. Only effective if sent together with the
crt
parameter.Example:
setCrt_name("My Company SL")
.crt_id string
Fiscal identifier of the entity or company sending the certified SMS. Only effective if sent together with the
crt
parameter.Example:
setCrt_id("ESB65213332")
.nofilter 0 | 1
If this field has value
1
the duplicate message filter will not be applied.You can permanently enable or disable this feature for all messages in the Account Preferences and in that case you do not need to include this parameter.
Example:
setNofilter(1)
.RESULT
The result is obtained in
JSON
format with the following elements:code integer
Identifier code indicating whether the request could be processed successfully or if an error occurred. Possible values in the Errors section.
Example:
"code": "0"
.message string
Description indicating whether the request could be processed successfully or if an error occurred. Possible values in the Errors section.
Example:
"message": "Message has been success
.fully sent." subid string
API request identifier.
Example:
"subid": "661568648080e47"
.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:code integer
Identifier code indicating whether the request could be processed successfully or if an error occurred. Possible values in the Errors section.
Example:
"code": "0"
.message string
Description of the error in the request. If the request has been processed correctly this field does not appear.
Example:
"message": "Unauthorized"
.credits float
Number of credits available in the account balance.
Example:
"credits": "1023.10"
.
<?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();
{"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
.
PARAMETERS
subid string mandatory
Identifier of the scheduled sending request. If this parameter has
*
as value it will affect all pending scheduled sendings on the account.Example:
scheduledSendings(
."5aa3ea8e5cdb6", $cmd) cmd string mandatory
Command to execute. Possible values:
cancel
send
, to delete or execute at that moment the selected programmed sendings.Example:
scheduledSendings(
.$subid, "send") RESULT
The result is obtained in
JSON
format with the following elements:code integer
Identifier code indicating whether the request could be processed successfully or if an error occurred. Possible values in the Errors section.
Example:
"code": "0"
.message string
Description indicating whether the request could be processed successfully or if an error occurred. Possible values in the Errors section.
Example:
"message": "Scheduled messages success
.fully cancelled."
<?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();
{ "code": 0, "message": "Scheduled messages successfully sent." }
{ "code": 0, "message": "Scheduled messages successfully cancelled." }
{ "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
.
PARAMETERS
countries array
List of countries for which you want to obtain the updated rate in credits and other details. Format: ISO codes of the countries. If this field is not sent or is null, information for all countries is returned.
Example:
getpricesCountry(array("ES", "FR",
."US", "MX")) - Expand all
RESULT
The result is obtained in
JSON
format with the following elements: isocode float
ISO code that identifies the country.
Example:
"isocode": "FR"
.prefix float
Telephone prefix of the country.
Example:
"prefix": "33"
.name float
Descriptive name of the country in English.
Example:
"name": "France"
.credits float
Number of credits available in the account balance.
Example:
"credits": 0.89
.code integer
Identifier code indicating the error occurred. Possible values in the Errors section. If the request has been processed correctly this field does not appear.
Example:
"code": "401"
.message string
Description of the error in the request. If the request has been processed correctly this field does not appear.
Example:
"message": "Unauthorized"
.
<?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();
{ "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
.
PARAMETERS
numbers string | list mandatory
Mobile numbers to be included in the HLR application. Numbers must be included in E.164 international format with the country code and without "+" or "00". May contain a single number or a list of numbers separated by commas with a maximum of 100 numbers.
Example:
LabsMobileModelHlrRequest(
.array( "573058156414", "528130939475" , "51918213400")) - Expand all
RESULT
The result of any HLR request is obtained in
JSON
format with the values detailed below: result string
Successful or unsuccessful result of the request. Values:
ok
ko
numbers array
Result information by number included in the request. The format and data obtained are detailed in RESULT BY NUMBER.
error string
Description in case of error. No value in case the request is successful. Values:
requiredfields
internalerror
numberslimit
nocredits
invalidauth
invalidauth
.count integer
Number of requests processed.
credits float
Number of credits that have been consumed by all HLR request checks.
- Expand all
RESULT BY NUMBER
msisdn string
Mobile number in international format E.164 without "+" or "00".
status string
Indicates the availability of the number.
Values of the state of a numberactive
Recently available and active. absent
Valid but without recent network connection. not_active
Incorrect or no active subscription. not_mobile
The format does not correspond to a mobile number. unknown
Incorrect status or no information. Usually indicates a temporary issue. format string
Indicates whether this is a number with a valid format. Values:
valid
error
error
.type string
Phone number type. Values:
mobile
fixed
fixedormobile
tollfree
premium
shared
voip
personal
pager
uan
voicemail
unknown
unknown
.country_name string
Name of the country to which the number belongs.
country_code string
Telephone prefix of the country to which the number belongs.
country_iso string
ISO code of the country to which the number belongs.
network string
Name of the operator's current network. In case the status is different from
active
the network corresponding to the prefix or format of the number is returned.mcc string
MCC code (Mobile Country Code) of the country according to the E.212 ITU-T encoding.
mnc string
MNC code (Mobile Network Code) of network or mobile operator according to E.212 ITU-T encoding. In case the status is different from
active
the network code corresponding to the prefix or number format is returned.
<?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();
{ "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 Code | Description |
---|---|
200 OK | Request processed correctly. |
400 Bad Request | Error in the request parameters. The error is detailed and specified in the code returned in JSON format. |
401 Unauthorized | Error in credentials or authentication method. |
402 Payment Required | Error due to lack of credits in the account. |
403 Forbidden | Request blocked by the IP filter or for violating any platform usage policy. |
500 Internal Server Error | Temporary error or incidence in the service |
This is the complete list of response codes in JSON format:
JSON Code | Description |
---|---|
0 | Message has been successfully sent |
10 | Missing XML data in request |
11 | Badly formed XML in request |
20 | The message element must be present in the request |
21 | The message element cannot be empty |
23 | There are no recipients |
24 | Too many recipients |
27 | This message contained one or more invalid character(s) |
28 | Subid is exceeding maximum length |
30 | There was an error while sending the message |
35 | The account has no enough credit for this sending |
39 | The value of the scheduled field is not a valid datetime format |
41 | Scheduled messages cannot be send in test mode |
51 | Compulsary fields not defined. |
52 | Scheduled messages not found. |
Support resources
We recommend that you consult and take into account the following support resources in your integration: