EN

API OTP

La API OTP está diseñada para técnicos y clientes que quieran envíar códigos OTP a través del canal SMS.

Los códigos OTP (One Time Password) son códigos de un sólo uso utilizados en procesos de verificación o autenticación 2fa (Two Factor Authentication).

Para iniciar una integración con la API OTP son imprescindibles los siguientes requisitos:

  • Una cuenta de LabsMobile asociada con un nombre de usuario (correo electrónico de registro). Crea una cuenta aquí.
  • Token API utilizado como contraseña y generado desde la sección Configuración API de tu cuenta.
  • URL del endpoint de la API OTP y los valores de los parámetros para realizar las peticiones.

Colección Postman API OTP
Descargar

La API OTP de LabsMobile utiliza parámetros HTTP GET y una URL base común para todas las peticiones: https://api.labsmobile.com/otp/

También es posible realizar envíos de código OTP por SMS con nuestra API http/POST eligiendo todos los aspectos como reintentos, validaciones, formato del OTP, etc.


Autenticación

El método de autenticación utilizado en cualquier petición de la API OTP es Basic Auth HTTP.

Este tipo de autenticación consta de unas credenciales username:tokenapi que se incluyen en el encabezado de la petición HTTP codificado en base64().

Ejemplo de valor de encabezado de autenticación:
Authorization: Basic 9yewaXic21vYmlsZqS5jmSk04enFTbUU=

Recomendación Se pueden generar tokens API desde la Configuración API de la cuenta. Recomendamos cambiar el token frecuentemente y utilizar diferentes tokens para cada uso, conexión o integración.


Enviar código OTP

Creación de un código OTP para un número y entorno determinados.

Esta petición genera un código OTP nuevo para un número móvil y un entorno indicados. Se enviará un SMS al número con el texto donde aparece el código OTP.

Los códigos OTP y procesos de validación se enmarcan en un entorno para identificar el proyecto, aplicación o versión a la que pertenece.

Importante Al enviar un código OTP se anularán todos los códigos anteriores pendientes de validar para este número y entorno y se generará un nuevo código. En el caso de que se quiera reenviar un código OTP para el mismo proceso de validación se debe utilizar la función Reenviar código OTP.

ENDPOINT

GET https://api.labsmobile.com/otp/sendCode

  • Ampliar todo

    PARÁMETROS

    Los parámetros o datos se envían en variables http/GET en la propia URL de la petición. A continuación se describen los valores y funcionalidad de todos los parámetros:

  • RESULTADO

    El resultado se obtiene en el cuerpo (body) de la respuesta HTTP y puede contener los siguientes valores:

    Valores de estado
    0Petición incorrecta o con error en el envío o procesado del código OTP.
    1Petición de creación y envío de código OTP exitosa.
ENVIAR OTP
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/sendCode?env=verifApp&sender=MyBRAND&phone_number=12015550123&message=The+code+to+verify+your+username+is%25CODE%25
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
    
    char *env = "verifApp";
    char *sender = "MyBRAND";
    char *phone_number = "12015550123";
    char *message = "The code to verify your username is %CODE%";

    curl = curl_easy_init();
    if(curl) {
        char *encoded_env = curl_easy_escape(curl, env, 0);
        char *encoded_sender = curl_easy_escape(curl, sender, 0);
        char *encoded_phone_number = curl_easy_escape(curl, phone_number, 0);
        char *encoded_message = curl_easy_escape(curl, message, 0);

        char url[1024];
        snprintf(url, sizeof(url),
                 "https://api.labsmobile.com/otp/sendCode?env=%s&sender=%s&phone_number=%s&message=%s",
                 encoded_env, encoded_sender, encoded_phone_number, encoded_message);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_free(encoded_env);
        curl_free(encoded_sender);
        curl_free(encoded_phone_number);
        curl_free(encoded_message);
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/sendCode", Method.Get);

      request.AddQueryParameter("env", "verifApp");
      request.AddQueryParameter("sender", "MyBRAND");
      request.AddQueryParameter("phone_number", "12015550123");
      request.AddQueryParameter("message", "The code to verify your username is %CODE%");

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String env = URLEncoder.encode("verifApp", "UTF-8");
    String sender = URLEncoder.encode("MyBRAND", "UTF-8");
    String phoneNumber = URLEncoder.encode("12015550123", "UTF-8");
    String message = URLEncoder.encode("The code to verify your username is %CODE%", "UTF-8");

    String url = String.format("https://api.labsmobile.com/otp/sendCode?env=%s&sender=%s&phone_number=%s&message=%s",
                                env, sender, phoneNumber, message);

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$env = "verifApp";
$sender = "MyBRAND";
$phone_number = "12015550123";
$message = "The code to verify your username is %CODE%";

$url = 'https://api.labsmobile.com/otp/sendCode?';
            $url .= 'env='.  urlencode($env) .'&';
            $url .= 'sender='.  urlencode($sender) .'&';
            $url .= 'phone_number=' .  urlencode($phone_number) .'&';
            $url .= 'message=' .  urlencode($message);

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64, urllib.parse

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

data = {
    'env':'verifApp',
    'sender': 'MyBRAND',
    'phone_number': '12015550123',
    'message':'The code to verify your username is %CODE%'
}

url = "https://api.labsmobile.com/otp/sendCode?"+urllib.parse.urlencode(data, doseq=True)
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

const env = "verifApp";
const sender = "MyBRAND";
const phone_number = "12015550123";
const message = "The code to verify your username is %CODE%";

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/sendCode?env=${encodeURIComponent(env)}&sender=${encodeURIComponent(sender)}&phone_number=${encodeURIComponent(phone_number)}&message=${encodeURIComponent(message)}`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/sendCode")

data = {
  'env' => 'verifApp',
  'sender' => 'MyBRAND',
  'phone_number' => '12015550123',
  'message' => 'The code to verify your username is %CODE%'
}

url.query = URI.encode_www_form(data)
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            

Reenviar código OTP

Reenvío de un código OTP para un número y entorno determinados.

Es importante realizar la llamada a esta función para enviar siempre el mismo código OTP para un mismo proceso de validación.

Importante Si no existe un código generado para el número y entorno enviados se creará un nuevo código OTP de igual forma que hace lo hace la función Enviar código OTP.

ENDPOINT

GET https://api.labsmobile.com/otp/resendCode

  • Ampliar todo

    PARÁMETROS

    Los parámetros o datos se envían en variables http/GET en la propia URL de la petición. A continuación se describen los valores y funcionalidad de todos los parámetros:

  • RESULTADO

    El resultado se obtiene en el cuerpo (body) de la respuesta HTTP y puede contener los siguientes valores:

    Valores de estado
    0Petición incorrecta o con error en el envío o procesado del código OTP.
    1Petición de creación y envío de código OTP exitosa.
REENVIAR OTP
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/resendCode?env=verifApp&sender=MyBRAND&phone_number=12015550123&message=The+code+to+verify+your+username+is%25CODE%25
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
    
    char *env = "verifApp";
    char *sender = "MyBRAND";
    char *phone_number = "12015550123";
    char *message = "The code to verify your username is %CODE%";

    curl = curl_easy_init();
    if(curl) {
        char *encoded_env = curl_easy_escape(curl, env, 0);
        char *encoded_sender = curl_easy_escape(curl, sender, 0);
        char *encoded_phone_number = curl_easy_escape(curl, phone_number, 0);
        char *encoded_message = curl_easy_escape(curl, message, 0);

        char url[1024];
        snprintf(url, sizeof(url),
                 "https://api.labsmobile.com/otp/resendCode?env=%s&sender=%s&phone_number=%s&message=%s",
                 encoded_env, encoded_sender, encoded_phone_number, encoded_message);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_free(encoded_env);
        curl_free(encoded_sender);
        curl_free(encoded_phone_number);
        curl_free(encoded_message);
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/resendCode", Method.Get);

      request.AddQueryParameter("env", "verifApp");
      request.AddQueryParameter("sender", "MyBRAND");
      request.AddQueryParameter("phone_number", "12015550123");
      request.AddQueryParameter("message", "The code to verify your username is %CODE%");

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String env = URLEncoder.encode("verifApp", "UTF-8");
    String sender = URLEncoder.encode("MyBRAND", "UTF-8");
    String phoneNumber = URLEncoder.encode("12015550123", "UTF-8");
    String message = URLEncoder.encode("The code to verify your username is %CODE%", "UTF-8");

    String url = String.format("https://api.labsmobile.com/otp/resendCode?env=%s&sender=%s&phone_number=%s&message=%s",
                                env, sender, phoneNumber, message);

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$env = "verifApp";
$sender = "MyBRAND";
$phone_number = "12015550123";
$message = "The code to verify your username is %CODE%";

$url = 'https://api.labsmobile.com/otp/resendCode?';
            $url .= 'env='.  urlencode($env) .'&';
            $url .= 'sender='.  urlencode($sender) .'&';
            $url .= 'phone_number=' .  urlencode($phone_number) .'&';
            $url .= 'message=' .  urlencode($message);

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64, urllib.parse

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

data = {
    'env':'verifApp',
    'sender': 'MyBRAND',
    'phone_number': '12015550123',
    'message':'The code to verify your username is %CODE%'
}

url = "https://api.labsmobile.com/otp/resendCode?"+urllib.parse.urlencode(data, doseq=True)
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

const env = "verifApp";
const sender = "MyBRAND";
const phone_number = "12015550123";
const message = "The code to verify your username is %CODE%";

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/resendCode?env=${encodeURIComponent(env)}&sender=${encodeURIComponent(sender)}&phone_number=${encodeURIComponent(phone_number)}&message=${encodeURIComponent(message)}`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/resendCode")

data = {
  'env' => 'verifApp',
  'sender' => 'MyBRAND',
  'phone_number' => '12015550123',
  'message' => 'The code to verify your username is %CODE%'
}

url.query = URI.encode_www_form(data)
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            

Validar código OTP

Validar el código OTP correspondiente a un número y entorno concreto.

ENDPOINT

GET https://api.labsmobile.com/otp/validateCode

  • PARÁMETROS

  • RESULTADO

    El resultado se obtiene en el cuerpo (body) de la respuesta HTTP y puede contener los siguientes valores:

    Valores de estado
    0Código OTP inexistente o incorrecto para este número.
    1Código OTP correcto y validado.
Validar OTP
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/validateCode?env=verifApp&phone_number=12015550123&code=381102
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
    
    char *env = "verifApp";
    char *phone_number = "12015550123";
    char *code = "652871";

    curl = curl_easy_init();
    if(curl) {
        char *encoded_env = curl_easy_escape(curl, env, 0);
        char *encoded_phone_number = curl_easy_escape(curl, phone_number, 0);
        char *encoded_code = curl_easy_escape(curl, code, 0);

        char url[1024];
        snprintf(url, sizeof(url),
                 "https://api.labsmobile.com/otp/validateCode?env=%s&phone_number=%s&code=%s",
                 encoded_env, encoded_phone_number, encoded_code);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_free(encoded_env);
        curl_free(encoded_phone_number);
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/validateCode", Method.Get);

      request.AddQueryParameter("env", "verifApp");
      request.AddQueryParameter("phone_number", "12015550123");
      request.AddQueryParameter("code", "652871");

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String env = URLEncoder.encode("verifApp", "UTF-8");
    String phoneNumber = URLEncoder.encode("12015550123", "UTF-8");
    String code = URLEncoder.encode("652871", "UTF-8");


    String url = String.format("https://api.labsmobile.com/otp/validateCode?env=%s&phone_number=%s&code=%s",
                                env, phoneNumber, code);

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$env = "verifApp";
$phone_number = "12015550123";
$code = "652871";

$url = 'https://api.labsmobile.com/otp/validateCode?';
            $url .= 'env='.  urlencode($env) .'&';
            $url .= 'phone_number=' .  urlencode($phone_number) .'&';
            $url .= 'code=' .  urlencode($code) .'&';

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64, urllib.parse

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

data = {
    'env':'verifApp',
    'phone_number': '12015550123',
    'code': '652871',

}

url = "https://api.labsmobile.com/otp/validateCode?"+urllib.parse.urlencode(data, doseq=True)
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

const env = "verifApp";
const phone_number = "12015550123";
const code = "652871";

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/validateCode?env=${encodeURIComponent(env)}&phone_number=${encodeURIComponent(phone_number)}&code=${encodeURIComponent(code)}`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/validateCode")

data = {
  'env' => 'verifApp',
  'phone_number' => '12015550123',
  'code' => '652871',
}

url.query = URI.encode_www_form(data)
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            

Comprobar código OTP

Comprobación del estado del código OTP correspondiente a un número y entorno concreto.

ENDPOINT

GET https://api.labsmobile.com/otp/checkCode

  • PARÁMETROS

  • RESULTADO

    El resultado se obtiene en el cuerpo (body) de la respuesta HTTP y puede contener los siguientes valores:

    Valores de estado
    0Código OTP inexistente para este número y entorno o pendiente de validación.
    1Código OTP validado correctamente.
Comprobar OTP
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/checkCode?env=verifApp&phone_number=12015550123
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
    
    char *env = "verifApp";
    char *phone_number = "12015550123";

    curl = curl_easy_init();
    if(curl) {
        char *encoded_env = curl_easy_escape(curl, env, 0);
        char *encoded_phone_number = curl_easy_escape(curl, phone_number, 0);

        char url[1024];
        snprintf(url, sizeof(url),
                 "https://api.labsmobile.com/otp/checkCode?env=%s&phone_number=%s",
                 encoded_env, encoded_phone_number);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_free(encoded_env);
        curl_free(encoded_phone_number);
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/checkCode", Method.Get);

      request.AddQueryParameter("env", "verifApp");
      request.AddQueryParameter("phone_number", "12015550123");

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String env = URLEncoder.encode("verifApp", "UTF-8");
    String phoneNumber = URLEncoder.encode("12015550123", "UTF-8");

    String url = String.format("https://api.labsmobile.com/otp/checkCode?env=%s&phone_number=%s",
                                env, phoneNumber);

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$env = "verifApp";
$phone_number = "12015550123";

$url = 'https://api.labsmobile.com/otp/checkCode?';
            $url .= 'env='.  urlencode($env) .'&';
            $url .= 'phone_number=' .  urlencode($phone_number) .'&';

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64, urllib.parse

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

data = {
    'env':'verifApp',
    'phone_number': '12015550123',
}

url = "https://api.labsmobile.com/otp/checkCode?"+urllib.parse.urlencode(data, doseq=True)
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

const env = "verifApp";
const phone_number = "12015550123";

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/checkCode?env=${encodeURIComponent(env)}&phone_number=${encodeURIComponent(phone_number)}`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/checkCode")

data = {
  'env' => 'verifApp',
  'phone_number' => '12015550123',
}

url.query = URI.encode_www_form(data)
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            

Listar entornos

Consulta de todos los entornos creados por una cuenta.

ENDPOINT

GET https://api.labsmobile.com/otp/getEnvList

Esta función no tiene parámetros y genera un resultado en formato JSON con la lista de entornos.

Lista entornos
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/getEnvList
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
  
    curl = curl_easy_init();
    if(curl) {

        char url[1024];
        snprintf(url, sizeof(url),"https://api.labsmobile.com/otp/getEnvList");

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/getEnvList", Method.Get);

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String url = String.format("https://api.labsmobile.com/otp/getEnvList");

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$url = 'https://api.labsmobile.com/otp/getEnvList';

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

url = "https://api.labsmobile.com/otp/getEnvList"
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/getEnvList`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/getEnvList")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            
Resultado
{"verifApp", "verifApp2", "envEx"}
                  

Listar códigos OTP

Consulta de códigos OTP de un entorno o asociados a un número.

ENDPOINT

GET https://api.labsmobile.com/otp/getEnv

  • PARÁMETROS

    Los parámetros env y msidn son filtros para obtener los códigos OTP enviados. Son filtros opcionales y si no se envía ningún parámetro se obtendrán como resultados todos los códigos OTP de la cuenta.

  • RESULTADO

    El resultado se obtiene en formato JSON con la lista de códigos con los siguientes elementos:

Comprobar OTP
curl --user myUsername:myToken -X GET  \
https://api.labsmobile.com/otp/getEnv?env=verifApp&phone_number=12015550123
              
#include <stdio.h> 
#include <curl/curl.h> 

int main(void) {
    CURL *curl;
    CURLcode res;
    
    char *env = "verifApp";
    char *phone_number = "12015550123";

    curl = curl_easy_init();
    if(curl) {
        char *encoded_env = curl_easy_escape(curl, env, 0);
        char *encoded_phone_number = curl_easy_escape(curl, phone_number, 0);

        char url[1024];
        snprintf(url, sizeof(url),
                 "https://api.labsmobile.com/otp/getEnv?env=%s&phone_number=%s",
                 encoded_env, encoded_phone_number);

        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
        curl_easy_setopt(curl, CURLOPT_HTTPAUTH, (long)CURLAUTH_BASIC);
        curl_easy_setopt(curl, CURLOPT_USERNAME, "myUsername");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "myToken");

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_free(encoded_env);
        curl_free(encoded_phone_number);
        curl_easy_cleanup(curl);
    }

    return 0;
}
            
using System;
using RestSharp;

namespace SendOtp
{
  class Program
  {
    static void MainSend(string[] args)
    {
      var client = new RestClient("https://api.labsmobile.com");
      var request = new RestRequest("/otp/getEnv", Method.Get);

      request.AddQueryParameter("env", "verifApp");
      request.AddQueryParameter("phone_number", "12015550123");

      request.AddHeader("Cache-Control", "no-cache");
      request.AddHeader("Authorization", "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("myUsername" + ":" + "myToken")));

      RestResponse response = client.Execute(request);
      if (response.ErrorException != null)
      {
        Console.WriteLine("Error: " + response.ErrorException.Message);
      }
      else
      {
        Console.WriteLine("Response content: " + response.Content);
      }
    }
  }
}

            
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class App {
  public static void main(String[] args) throws UnirestException, UnsupportedEncodingException {

    String env = URLEncoder.encode("verifApp", "UTF-8");
    String phoneNumber = URLEncoder.encode("12015550123", "UTF-8");

    String url = String.format("https://api.labsmobile.com/otp/getEnv?env=%s&phone_number=%s",
                                env, phoneNumber);

    Unirest.setTimeouts(0, 0);

    HttpResponse<String> response = Unirest.get(url)
        .basicAuth("myUsername", "myToken")
        .header("Cache-Control", "no-cache")
        .asString();

    System.out.println("Response content: " + response.getBody());
  }
}

            
<?php 
$auth_basic = base64_encode("myUsrname:myToken");

$curl = curl_init();

$env = "verifApp";
$phone_number = "12015550123";

$url = 'https://api.labsmobile.com/otp/getEnv?';
            $url .= 'env='.  urlencode($env) .'&';
            $url .= 'phone_number=' .  urlencode($phone_number) .'&';

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic '.$auth_basic
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

            
import requests, base64, urllib.parse

userToken = "myUsername:myToken"
credentials = (base64.b64encode(userToken.encode()).decode())

data = {
    'env':'verifApp',
    'phone_number': '12015550123',
}

url = "https://api.labsmobile.com/otp/getEnv?"+urllib.parse.urlencode(data, doseq=True)
payload = {}
headers = {
  'Authorization': 'Basic %s' % credentials,
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)


            
const axios = require('axios');

const env = "verifApp";
const phone_number = "12015550123";

let config = {
  method: 'get',
  maxBodyLength: Infinity,
  url: `https://api.labsmobile.com/otp/getEnv?env=${encodeURIComponent(env)}&phone_number=${encodeURIComponent(phone_number)}`,
  headers: { 
    'Authorization': 'Basic ' + Buffer.from("myUsername:myToken").toString('base64')
  },
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
            
require "uri"
require 'base64'
require "net/http"

url = URI("https://api.labsmobile.com/otp/getEnv")

data = {
  'env' => 'verifApp',
  'phone_number' => '12015550123',
}

url.query = URI.encode_www_form(data)
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Basic " + Base64.strict_encode64("myUsername:myToken")

response = https.request(request)
puts response.read_body

            
Resultado positivo
[
  {"34609033271", "1", "2016-01-03 12:32:08", "2016-01-03 12:34:40"},
  {"34699293203", "2", "2016-01-05 12:32:10", "2016-01-06 23:22:52"}
]
                  

Errores

A continuación se describen los códigos de error HTTP que puede devolver una petición a la API OTP.

códigos HTTP de respuesta
200OKOperación procesada correctamente.
400Bad RequestError en alguno de los parámetros.
401UnauthorizedError en las credenciales proporcionadas.
403ForbiddenPetición bloqueada por filtros de seguridad o mal uso.
404Not FoundPetición o comando no existente.
500Internal Server ErrorError interno o desconocido.