# One Time Password (OTP)

### Endpoint <a href="#endpoint" id="endpoint"></a>

<mark style="color:$success;">**`GET`**</mark> `https://api.textcus.com/api/v2/otp`

#### Headers <a href="#headers" id="headers"></a>

`Authorization: Bearer API_KEY`

### **Request Parameters** <a href="#request-parameters" id="request-parameters"></a>

Below is a list of parameters when issuing an HTTP Request.

<table><thead><tr><th width="226">Parameters</th><th width="160">Type</th><th>Description</th></tr></thead><tbody><tr><td><code>expiry</code></td><td>Required</td><td>This is your OTP from TextCus: %otp_code%. The code will expire in %expiry% minutes.</td></tr><tr><td><code>length</code></td><td>Required</td><td>This parameter specifies the number of characters or digits in the generated code.</td></tr><tr><td><code>message</code></td><td>Required</td><td>Enter your message content here. One message page equals 160 characters — for example, a 200-character message will count as 2 pages. Be sure to include the <strong>%otp_code%</strong> placeholder where the generated code should appear in the message.</td></tr><tr><td><code>medium</code></td><td>Required</td><td>Enum: "<code>sms</code>" or "<code>email</code>"</td></tr><tr><td><code>phone_number</code></td><td>Required</td><td>The phone number of the contact.</td></tr><tr><td><code>sender_id</code></td><td>Required</td><td>A Sender ID is the name or number that appears as the sender of an SMS message. This field must not exceed 11 characters, including spaces — exceeding this limit may cause your messages to fail.</td></tr><tr><td><code>type</code></td><td>Required</td><td>Enum: "<code>numeric</code>" or "<code>alphanumeric</code>"</td></tr></tbody></table>

## Sample Requests <a href="#sample-requests" id="sample-requests"></a>

{% tabs %}
{% tab title="PHP" %}

```php
<?php

$data = [
  'expiry' => 10, // Otp expiry in minutes e.g, 10
  'length' => 6, // Length of otp code
  'medium' => "sms", //sms or email
  'phone_number' => "23324xxxxxxx", // In international format
  'sender_id' => "TextCus", // Maximum 11 Characters
  'message' => "Your TextCus Otp: %otp_code%",
  'type' => "numeric" // numeric or alphanumeric
];

$url = 'https://api.textcus.com/api/v2/otp';

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer API_KEY',  // Replace 'API_KEY' with your actual API key
    'Content-Type: application/json' 
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>

```

{% endtab %}

{% tab title="NodeJs" %}

```javascript
const axios = require('axios');

const data = {
  expiry: 10, // Otp expiry in minutes e.g, 10
  length: 6, // Length of otp code
  medium: "sms", //sms or email
  phone_number: "23324xxxxxxx", // In international format
  sender_id: "TextCus", // Maximum 11 Characters
  message: "Your TextCus Otp: %otp_code%",
  type: "numeric" //numeric or alphanumeric
};

const url = 'https://api.textcus.com/api/v2/otp';

axios({
  method: 'get',
  url: url,
  data: data,
  headers: {
    'Authorization': 'Bearer API_KEY',  // Replace 'API_KEY' with your actual API Key
    'Content-Type': 'application/json'
  },
  timeout: 30000  // Set timeout to 30 seconds
})
  .then(response => {
    console.log(response.data);  // Handle successful response
  })
  .catch(error => {
    console.error('Error:', error.response ? error.response.data : error.message);  // Handle errors
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

url = 'https://api.textcus.com/api/v2/otp'

data = {
  'expiry': 10, # Otp expiry in minutes e.g, 10
  'length': 6, # Length of otp code
  'medium': "sms", #sms or email
  'phone_number': "23324xxxxxxx", # In international format
  'sender_id': "TextCus", # Maximum 11 Characters
  'message': "Your TextCus Otp: %otp_code%",
  'type': "numeric" # numeric or alphanumeric
}

headers = {
    'Authorization': 'Bearer API_KEY',  # Replace 'API_KEY' with your actual API Key
    'Content-Type': 'application/json'
}

try:
    response = requests.post(url, data=json.dumps(data), headers=headers, timeout=30)
    
    if response.status_code == 200:
        print(response.json())  # Handle successful response
    else:
        print(f"Failed to send message. Status code: {response.status_code}")
        print(response.text)  # Print the error message from the response

except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

```

{% endtab %}

{% tab title="Dart" %}

```dart
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  String url = 'https://api.textcus.com/api/v2/otp';

  Map<String, dynamic> data = {
    'expiry': 10, // Otp expiry in minutes e.g, 10
    'length': 6, // Length of otp code
    'medium': "sms", //sms or email
    'phone_number': "23324xxxxxxx", // In international format
    'sender_id': "TextCus", // Maximum 11 Characters
    'message': "Your TextCus Otp: %otp_code%",
    'type': "numeric" // numeric or alphanumeric
  };

  try {
    final response = await http.get(
      Uri.parse(url),
      headers: {
        'Authorization': 'Bearer API_KEY', // Replace 'API_KEY' with your actual API Key
        'Content-Type': 'application/json',
      },
      body: jsonEncode(data), // Convert the data map to a JSON string
    );

    if (response.statusCode == 200) {
      print(response.body); // Handle successful response
    } else {
      print('Failed to send message. Status code: ${response.statusCode}');
      print(response.body); // Print the error message from the response
    }
  } catch (e) {
    print('Error: $e');
  }
}

```

{% endtab %}

{% tab title="Java" %}

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SendSMS {

    public static void main(String[] args) {
        String url = "https://api.textcus.com/api/v2/otp";

        Map<String, Object> data = new HashMap<>();
        data.put("expiry", 10); // Otp expiry in minutes e.g, 10
        data.put("length", 6); // Length of otp code
        data.put("medium", "sms"); //sms or email
        data.put("type", "numeric"); // numeric or alphanumeric
        data.put("phone_number", "23324xxxxxxx"), // In international format
        data.put("sender_id", "TextCus"); // Maximum 11 Characters
        data.put("message", "Your TextCus Otp: %otp_code%");

        try {
            // Convert the data map to JSON string using Jackson ObjectMapper
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(data);

            // Create an HttpClient
            HttpClient client = HttpClient.newHttpClient();

            // Build the HTTP request
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Authorization", "Bearer API_KEY")  // Replace 'API_KEY' with your actual API Key
                    .header("Content-Type", "application/json")
                    .POST(BodyPublishers.ofString(requestBody, StandardCharsets.UTF_8))
                    .build();

            // Send the request and get the response
            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());

            // Handle response
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.println("Failed to send message. Status code: " + response.statusCode());
                System.out.println("Response: " + response.body());
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

```

{% endtab %}

{% tab title="VB.Net" %}

```vbnet
Imports System.Net.Http
Imports System.Text
Imports Newtonsoft.Json

Module SendSMS
    Sub Main()
        Dim url As String = "https://api.textcus.com/api/v2/otp"

        ' Prepare the data to be sent
        Dim data As New Dictionary(Of String, Object) From {
          {"expiry", 10}, ' Otp expiry in minutes e.g, 10
          {"length", 6}, ' Length of otp code
          {"medium", "sms"}, ' sms or email
          {"phone_number", "23324xxxxxxx"}, ' In international format
          {"sender_id", "TextCus"}, ' Maximum 11 Characters
          {"message", "Your TextCus Otp: %otp_code%"},
          {"type", "numeric"} ' numeric or alphanumeric
        }

        ' Convert data to JSON string
        Dim jsonData As String = JsonConvert.SerializeObject(data)

        ' Create HttpClient
        Using client As New HttpClient()
            client.DefaultRequestHeaders.Add("Authorization", "Bearer API_KEY") ' Replace 'API_KEY' with your actual API key
            client.DefaultRequestHeaders.Add("Content-Type", "application/json")

            ' Create HttpContent from JSON data
            Dim content As New StringContent(jsonData, Encoding.UTF8, "application/json")

            Try
                ' Send the POST request
                Dim response As HttpResponseMessage = client.PostAsync(url, content).Result

                ' Check the status code
                If response.IsSuccessStatusCode Then
                    ' Read the response content
                    Dim responseBody As String = response.Content.ReadAsStringAsync().Result
                    Console.WriteLine("Response: " & responseBody)
                Else
                    Console.WriteLine("Failed to send message. Status code: " & response.StatusCode)
                    Console.WriteLine("Response: " & response.Content.ReadAsStringAsync().Result)
                End If

            Catch ex As Exception
                Console.WriteLine("Error: " & ex.Message)
            End Try
        End Using
    End Sub
End Module

```

{% endtab %}
{% endtabs %}

## Sample Response <a href="#sample-response" id="sample-response"></a>

{% tabs %}
{% tab title="Success" %}

```json
{
    "status": 200,
    "message": "Otp sent successfully"
}
```

{% endtab %}

{% tab title="Errors" %}

```json
{
    "status": 401,
    "error": "Authentication invalid"
}, 

{
    "status": 401,
    "error": "Unauthorized: Invalid API Key"
}
```

{% endtab %}
{% endtabs %}
