Crear un código de verificación
Inicia un proceso de verificación creando un nuevo código de verificación con una estrategia de enrutamiento especificada.
Authorizations
Sección titulada «Authorizations »Request Body required
Sección titulada «Request Body required »Payload de escritura de código de verificación. Crea una nueva solicitud de código de verificación con una estrategia de enrutamiento de varios pasos.
object
Número de teléfono del destinatario en formato internacional (ej. +491701234567).
Código de verificación personalizado. Si no se proporciona, se genera automáticamente un código numérico aleatorio basado en code_length.
Longitud del código de verificación generado automáticamente. Se utiliza solo cuando no se proporciona code. Predeterminado: 4.
Idioma para la plantilla de mensaje predeterminada. Determina el idioma del texto SMS/Voz generado automáticamente cuando no se proporciona una template personalizada. No aplica para el canal telegram — Telegram siempre envía un mensaje del sistema en el idioma de la aplicación Telegram del usuario.
Datos personalizados que se almacenarán con el código de verificación y se devolverán en los eventos de webhook. Útil para correlacionar las solicitudes de verificación con sus sistemas internos.
Si es true, el código de verificación se eliminará del almacenamiento después de haberse enviado al destinatario. Predeterminado: false.
Lista ordenada de canales de entrega. Cada paso define un canal para intentar. Si un canal falla o expira, se intenta el siguiente paso. Se requiere al menos un paso. El canal sms solo puede ser el último paso. No se permiten canales duplicados.
object
Canal de entrega para este paso.
Tiempo en segundos para esperar una respuesta de este canal antes de recurrir al siguiente paso. Solo aplicable para el canal de telegram. Si no se establece, se utiliza un valor predeterminado del sistema.
Identificador del remitente para canales SMS y Voice. Para SMS, este es el número de teléfono o ID alfanumérico del remitente que se muestra en el dispositivo del destinatario. Validado con los IDs de remitente permitidos de su cuenta.
Plantilla de mensaje personalizada para canales sms o voice. Use {{code}} como marcador de posición para el código de verificación. Si no se proporciona, se utiliza una plantilla traducida predeterminada basada en el campo lang. Para el canal voice, el texto se envuelve automáticamente en etiquetas SSML <speak>. Ignorado para el canal telegram.
Examples
Verify code with multi-channel routing
Create a verification code with a 3-step routing strategy: Telegram, Voice, and SMS.
{ "phone": "+491701234567", "code": "1234", "is_code_deleted": false, "payload": "yours payload here", "lang": "EN", "routing_strategy": [ { "channel": "telegram", "timeout_sec": 30 }, { "channel": "voice", "sender_id": "LOX24", "template": "Your code is {{code}}" }, { "channel": "sms", "sender_id": "LOX24", "template": "Your code is {{code}}" } ]}Verify code via Telegram
Send a verification code through a Telegram bot. The code will be delivered as a Telegram message to the user’s chat.
{ "phone": "+491701234567", "lang": "EN", "routing_strategy": [ { "channel": "telegram", "timeout_sec": 60 } ]}Verify code via Voice call
Deliver a verification code through an automated voice call. The code is read aloud to the recipient using a text-to-speech template.
{ "phone": "+491701234567", "code_length": 6, "lang": "EN", "routing_strategy": [ { "channel": "voice", "sender_id": "LOX24", "template": "Your verification code is {{code}}" } ]}Responses
Sección titulada « Responses »Verify code created and delivery process started
Respuesta de lectura del código de verificación. Contiene los detalles completos de la solicitud del código de verificación, incluyendo el estado actual, el historial de entrega y la información de costos.
object
Identificador único (UUID) de la solicitud del código de verificación.
ID del usuario que creó la solicitud del código de verificación.
Número de teléfono del destinatario en formato internacional.
El valor del código de verificación. Si se estableció is_code_deleted y la tarea se completó, el código estará ausente.
Longitud del código de verificación.
Idioma utilizado para la plantilla del mensaje.
Lista ordenada de canales de entrega que se configuraron para esta solicitud.
object
Tipo de canal de entrega.
Tiempo de espera en segundos antes de recurrir al siguiente paso. Solo aplicable para el canal de telegram.
Identificador del remitente utilizado para este canal.
Plantilla de mensaje personalizada utilizada para este canal.
Estado actual del código de verificación: 0 = Nuevo, 5 = En progreso, 10 = Éxito, 20 = Fallido, 100 = Error.
El canal que entregó exitosamente el código de verificación. Null si aún no se ha entregado o si la entrega falló.
Costo total de la solicitud de verificación en céntimos de euro. Null hasta que se complete el procesamiento.
Código de moneda para el costo.
Datos de payload personalizados de la solicitud original.
Marca de tiempo Unix de cuándo se creó el código de verificación.
Marca de tiempo Unix de la última actualización.
Historial de procesamiento para cada intento de canal. Una entrada por paso de enrutamiento.
object
UUID de la entrada del historial.
Tipo de canal para este intento.
Estado de este intento de canal: 0 = Nuevo, 5 = En progreso, 10 = Éxito, 20 = Fallido, 100 = Error.
Marca de tiempo Unix de cuándo se procesó este paso.
ID del mensaje del proveedor externo.
Si el código de verificación ha sido eliminado del almacenamiento después de ser enviado al destinatario.
Examples
Verify code response with multi-channel routing
Successful response after creating a verification code with a 3-step routing strategy. Telegram and voice channels failed, SMS succeeded.
{ "id": "d7ad7539-fb8f-4dbb-a7f7-7c40babec969", "user_id": 12345, "phone": "+491701234567", "routing_strategy": [ { "channel": "telegram", "timeout_sec": 30 }, { "channel": "voice", "sender_id": "LOX24", "template": "Your code is {{code}}" }, { "channel": "sms", "sender_id": "LOX24", "template": "Your code is {{code}}" } ], "status": 10, "delivered_channel": "sms", "cost": 120, "currency": "EUR", "code": "1234", "code_length": 4, "payload": "yours payload here", "lang": "EN", "created_at": 1779903448, "updated_at": 1779903510, "history": [ { "id": "bccaff09-59f2-11f1-a685-7c10c91d54a1", "channel": "telegram", "status": 20, "processed_at": 1779903478, "external_id": "tg_msg_001" }, { "id": "bccaff09-59f2-11f1-a685-7c10c91d54a2", "channel": "voice", "status": 20, "processed_at": 1779903490, "external_id": "voice_msg_002" }, { "id": "bccaff09-59f2-11f1-a685-7c10c91d54a3", "channel": "sms", "status": 10, "processed_at": 1779903510, "external_id": "sms_msg_003" } ], "is_code_deleted": false}Entrada no valida
El ID de cliente o la clave API no están activos o no son válidos.
No hay fondos suficientes en su cuenta.
La cuenta no está activada. Espere o póngase en contacto con el servicio de asistencia.
La solicitud estaba bien formada pero no se pudo procesar debido a errores semánticos
La dirección IP fue bloqueada temporalmente, ya que durante poco tiempo se enviaron muchas solicitudes con credenciales no válidas. Espere y pruebe más tarde.
Code Samples
#!/usr/bin/env bashcurl -X POST https://api.lox24.eu/verify_codes \ -H 'Content-Type: application/json' \ -H 'X-LOX24-AUTH-TOKEN: 1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx' \ -d '{ "phone": "+491701234567", "code": "1234", "is_code_deleted": false, "payload": "yours payload here", "lang": "EN", "routing_strategy": [ { "channel": "telegram", "timeout_sec": 30 }, { "channel": "voice", "sender_id": "LOX24", "template": "Your code is {{code}}" }, { "channel": "sms", "sender_id": "LOX24", "template": "Your code is {{code}}" } ] }'using Newtonsoft.Json;using System;using System.IO;using System.Net;using System.Text;
namespace Lox24.Api{ class VerifyCodesClient { static void Main() { string key = "1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx"; string url = "https://api.lox24.eu/verify_codes";
var data = new { phone = "+491701234567", code = "1234", is_code_deleted = false, payload = "yours payload here", lang = "EN", routing_strategy = new[] { new { channel = "telegram", timeout_sec = 30 }, new { channel = "voice", sender_id = "LOX24", template = "Your code is {{code}}" }, new { channel = "sms", sender_id = "LOX24", template = "Your code is {{code}}" } } };
string postdata = JsonConvert.SerializeObject(data);
Console.WriteLine("Post data: {0}", postdata);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ReadWriteTimeout = 100000; httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Accept = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.Headers.Add("X-LOX24-AUTH-TOKEN", key); httpWebRequest.Credentials = CredentialCache.DefaultNetworkCredentials;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(postdata); streamWriter.Flush(); streamWriter.Close(); } try { using (HttpWebResponse resp = (HttpWebResponse)httpWebRequest.GetResponse()) {
if(resp.StatusCode == HttpStatusCode.Created) { Console.WriteLine("Success:{0} {1}", (int)resp.StatusCode, "verify code resource created"); } else { Console.WriteLine("Error: wrong response code {0} on create verify code", (int)resp.StatusCode); }
Stream respStream = resp.GetResponseStream(); using (StreamReader sr = new StreamReader(respStream, Encoding.UTF8)) { string responseText = sr.ReadToEnd(); Console.WriteLine("responseText : {0}", responseText); } }
} catch (System.Net.WebException ex) { var webResponse = ex.Response as System.Net.HttpWebResponse; Console.WriteLine("Error:{0}", webResponse.StatusCode);
switch (webResponse.StatusCode) { case HttpStatusCode.BadRequest: Console.WriteLine("Error:400 Invalid input"); break; case HttpStatusCode.Unauthorized: Console.WriteLine("Error:401 Client ID or API key isn't active or invalid!"); break; case HttpStatusCode.PaymentRequired: Console.WriteLine("Error:402 There are not enough funds on your account!"); break; case HttpStatusCode.Forbidden: Console.WriteLine("Error:403 Account isn't activated. Please wait or contact to support!"); break; case (HttpStatusCode)422: Console.WriteLine("Error:422 Unprocessable entity"); break; case HttpStatusCode.InternalServerError: case HttpStatusCode.BadGateway: case HttpStatusCode.ServiceUnavailable: case HttpStatusCode.GatewayTimeout: Console.WriteLine("System error! Please contact to LOX24 support!"); break; } } } }}package main
import ( "bytes" "encoding/json" "fmt" "io" "log" "net/http")
func main() {
const Method = "POST" const URL = "https://api.lox24.eu/verify_codes" const Token = "1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx"
routingStrategy := []map[string]interface{}{ {"channel": "telegram", "timeout_sec": 30}, {"channel": "voice", "sender_id": "LOX24", "template": "Your code is {{code}}"}, {"channel": "sms", "sender_id": "LOX24", "template": "Your code is {{code}}"}, }
payload := map[string]interface{}{ "phone": "+491701234567", "code": "1234", "is_code_deleted": false, "payload": "yours payload here", "lang": "EN", "routing_strategy": routingStrategy, }
jsonPayload, _ := json.Marshal(payload)
client := &http.Client{}
req, err := http.NewRequest(Method, URL, bytes.NewBuffer(jsonPayload)) if err != nil { log.Fatal(err) }
req.Header.Add("X-LOX24-AUTH-TOKEN", Token) req.Header.Add("Content-Type", "application/json")
res, err := client.Do(req) if err != nil { log.Fatal(err) }
defer res.Body.Close()
body, err := io.ReadAll(res.Body) if err != nil { log.Fatal(err) }
switch res.StatusCode { case 201: fmt.Println(string(body)) case 400: fmt.Println("Error: code = 400 - Invalid input") case 401: fmt.Println("Error: code = 401 - Client ID or API key isn't active or invalid!") case 402: fmt.Println("Error: code = 402 - There are not enough funds on your account!") case 403: fmt.Println("Error: code = 403 - Account isn't activated. Please wait or contact to support!") case 422: fmt.Println("Error: code = 422 - Unprocessable entity") default: fmt.Printf("Error: code = %d\n", res.StatusCode) }}package eu.lox24.doc.verify_codes;
import org.json.JSONArray;import org.json.JSONObject;
import java.io.IOException;import java.net.HttpURLConnection;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.time.Duration;
public class PostVerifyCodesCollection {
public static void main(String[] args) {
var key = "1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx"; var url = "https://api.lox24.eu/verify_codes";
var routingStrategy = new JSONArray(); routingStrategy.put(new JSONObject().put("channel", "telegram").put("timeout_sec", 30)); routingStrategy.put(new JSONObject().put("channel", "voice").put("sender_id", "LOX24").put("template", "Your code is {{code}}")); routingStrategy.put(new JSONObject().put("channel", "sms").put("sender_id", "LOX24").put("template", "Your code is {{code}}"));
var json = new JSONObject(); json.put("phone", "+491701234567"); json.put("code", "1234"); json.put("is_code_deleted", false); json.put("payload", "yours payload here"); json.put("lang", "EN"); json.put("routing_strategy", routingStrategy);
var postData = json.toString();
System.out.println("Post data: " + postData);
var httpRequest = HttpRequest.newBuilder(URI.create(url)) .timeout(Duration.ofMillis(100000)) .setHeader("Content-Type", "application/json; charset=utf-8") .setHeader("Accept", "application/json") .setHeader("X-LOX24-AUTH-TOKEN", key) .POST(HttpRequest.BodyPublishers.ofString(postData)) .build();
var client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .build();
try { var httpResponse = client.send(httpRequest, HttpResponse.BodyHandlers.ofString());
if (httpResponse.statusCode() == HttpURLConnection.HTTP_CREATED) { System.out.println("Success:" + httpResponse.statusCode() + " " + "verify code resource created"); System.out.println("Response text : \n" + httpResponse.body());
} else {
System.out.println("Error: wrong response code " + httpResponse.statusCode() + " on create verify code");
switch (httpResponse.statusCode()) {
case HttpURLConnection.HTTP_BAD_REQUEST: System.out.println("Error:400 Invalid input"); break; case HttpURLConnection.HTTP_UNAUTHORIZED: System.out.println("Error:401 Client ID or API key isn't active or invalid!"); break; case HttpURLConnection.HTTP_PAYMENT_REQUIRED: System.out.println("Error:402 There are not enough funds on your account!"); break; case HttpURLConnection.HTTP_FORBIDDEN: System.out.println("Error:403 Account isn't activated. Please wait or contact to support!"); break; case 422: System.out.println("Error:422 Unprocessable entity"); break; case HttpURLConnection.HTTP_INTERNAL_ERROR: case HttpURLConnection.HTTP_BAD_GATEWAY: case HttpURLConnection.HTTP_UNAVAILABLE: case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: System.out.println("System error! Please contact to LOX24 support!"); break; }
}
} catch (IOException | InterruptedException e) { e.printStackTrace(); } }}/* * Post verify code */const token = "1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx";
var postObj = { phone: '+491701234567', code: '1234', is_code_deleted: false, payload: 'yours payload here', lang: 'EN', routing_strategy: [ { channel: 'telegram', timeout_sec: 30 }, { channel: 'voice', sender_id: 'LOX24', template: 'Your code is {{code}}' }, { channel: 'sms', sender_id: 'LOX24', template: 'Your code is {{code}}' } ]};
var postdata = JSON.stringify(postObj);
const https = require('https');const options = { hostname: 'api.lox24.eu', path: '/verify_codes', method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Content-Length': postdata.length, 'X-LOX24-AUTH-TOKEN': token }}
const req = https.request(options, res => { if (res.statusCode == 201) { console.log("Success: code = 201 - verify code resource created"); res.on('data', d => { process.stdout.write(d) }) } else if (res.statusCode == 400) console.log("Error: code = 400 - Invalid input"); else if (res.statusCode == 401) console.log("Error: code = 401 - Client ID or API key isn't active or invalid!"); else if (res.statusCode == 402) console.log("Error: code = 402 - There are not enough funds on your account!"); else if (res.statusCode == 403) console.log("Error: code = 403 - Account isn't activated. Please wait or contact to support!"); else if (res.statusCode == 422) console.log("Error: code = 422 - Unprocessable entity");})
req.on('error', error => { console.error(error)})req.write(postdata);req.end();<?php
$uri = 'https://api.lox24.eu/verify_codes';
$token = '1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx';
$body = [ 'phone' => '+491701234567', 'code' => '1234', 'is_code_deleted' => false, 'payload' => 'yours payload here', 'lang' => 'EN', 'routing_strategy' => [ [ 'channel' => 'telegram', 'timeout_sec' => 30, ], [ 'channel' => 'voice', 'sender_id' => 'LOX24', 'template' => 'Your code is {{code}}', ], [ 'channel' => 'sms', 'sender_id' => 'LOX24', 'template' => 'Your code is {{code}}', ], ],];
if(!$body = json_encode($body)) { die('JSON encoding error!');}
$curl = curl_init();
curl_setopt_array($curl, [ CURLOPT_POST => true, CURLOPT_URL => $uri, CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => [ "X-LOX24-AUTH-TOKEN: {$token}", 'Accept: application/json', 'Content-Type: application/json', ], CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 20, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,]);
$response = curl_exec($curl);$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);curl_close($curl);
$data = json_decode($response, JSON_OBJECT_AS_ARRAY);
if(201 === $code) { echo 'Success: response data = ' . var_export($data, true);} else { echo "Error: code = {$code}, data = " . var_export($data, true);}import jsonimport requests
token = "1234567:e3f3a759b6677959b6ebfcxxxxxxxxxx"
url = 'https://api.lox24.eu/verify_codes'
data = { 'phone': "+491701234567", 'code': "1234", 'is_code_deleted': False, 'payload': "yours payload here", 'lang': "EN", 'routing_strategy': [ { 'channel': "telegram", 'timeout_sec': 30 }, { 'channel': "voice", 'sender_id': "LOX24", 'template': "Your code is {{code}}" }, { 'channel': "sms", 'sender_id': "LOX24", 'template': "Your code is {{code}}" } ]}
headers = { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-LOX24-AUTH-TOKEN': token,}
print("Post data : ", json.dumps(data, indent=4))
try: res = requests.post(url, headers=headers, json=data, timeout=100) if res.status_code != 201: print("Error: Wrong response code on create verify code") res.raise_for_status() else: print(f'Success: code = {res.status_code} - verify code resource created') print("Response: ", json.dumps(res.json(), indent=4))
except requests.HTTPError: if res.status_code == 400: print("Error:400 Invalid input") elif res.status_code == 401: print("Error: code = 401 - Client ID or API key isn't active or invalid!") elif res.status_code == 402: print("Error:402 There are not enough funds on your account!") elif res.status_code == 403: print("Error: code = 403 - Account isn't activated. Please wait or contact to support!") elif res.status_code == 422: print("Error:422 Unprocessable entity") elif res.status_code in (500, 502, 503, 504): print("System error! Please contact to LOX24 support!") else: print(f"Error: code {res.status_code}") print(json.dumps(res.json(), indent=4))