# Introduction

Our SMS APIs are designed to integrate seamlessly with your systems and applications and are supported by our dependable bulk SMS gateway. This document is a comprehensive reference for all the features accessible to you through our APIs for sending SMS messages.

## Getting Started <a href="#getting-started" id="getting-started"></a>

{% hint style="info" %}
To send SMS using our APIs, you need to have a TextCus SMS Messaging account.

**Step 1: Create a TextCus SMS Messaging account (if you don't already have one)**

* Visit <https://sms.textcus.com/signup> to create a new SMS account.
* Follow the steps provided to activate your account.
  {% endhint %}

## Overview

Our APIs are designed to integrate seamlessly with your systems and applications. This document is a comprehensive reference for all the features accessible through our APIs for adding and fetching data. It's designed around the primary resources you'll need most frequently and is made with RESTful standards in mind.

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td><p><mark style="color:yellow;"><strong><code>POST</code></strong></mark></p><p>To add new user data to the system, use this request.</p></td><td></td><td></td></tr><tr><td><mark style="color:green;"><strong><code>GET</code></strong></mark></td><td>To add and retrieve user data from the system, use this request.</td><td></td></tr></tbody></table>

## Authentication

**Reference your API Key**

{% hint style="info" %}
**Reference your API Key**

* Log in to your TextCus SMS Messaging account
* Go to API > API Access or visit <https://sms.textcus.com/api-access>
* Copy your API key for future reference
  {% endhint %}

The following format should be used for authorisation headers:

`Authorization: Bearer API_KEY`

{% hint style="info" %}
**Sample Authorization Header**

Authorization: Bearer 92857043717beff382ae75c8dc7514162f04
{% endhint %}

```php
curl -H "Authorization: Bearer API_KEY" \
     https://api.textcus.com/api/v2/user/authenticate
```

## Requests and Response <a href="#authentication-1" id="authentication-1"></a>

The format of the response and request payloads is JSON. Responses will always have `application/json` as their content type. Each response will typically follow this format:

## Response Formats

<table><thead><tr><th width="255">Response</th><th>Data type</th><th>Description</th></tr></thead><tbody><tr><td>status</td><td>number</td><td>The HTTP status code indicating a status operation.</td></tr><tr><td>message</td><td>string</td><td>This gives you detailed explaination on the request sent. The interpretation of the status code.</td></tr><tr><td>data</td><td>object</td><td>An object holding any data that the API returned after receiving the request.</td></tr></tbody></table>

## **Status Codes and Interpretation**

| Status Code | Interpretation                                            |
| ----------- | --------------------------------------------------------- |
| `200`       | Standard for successful request.                          |
| `201`       | Used for requests as a result of creation.                |
| `204`       | Indicates that a request has succeeded or been processed. |
| `400`       | For bad requests.                                         |
| `401`       | For unathorized.                                          |
| `402`       | For payment required.                                     |
| `404`       | For not found.                                            |
| `500`       | For internal server errors.                               |


# Send SMS (v1)

The HTTP API enables you to send SMS quickly. To send an SMS, simply call the following URL with the relevant parameters appended to the URL, as shown below:

{% hint style="info" %}
`https://sms.textcus.com/api/send?destination={recipient}&source={sender}&dlr={0}&type={0}&message={message}`
{% endhint %}

<mark style="color:red;">NB: Please remove the curly bracket in the URL when testing</mark>

<mark style="color:$danger;">**API v1.0 has been discontinued and will no longer be supported. Please use API v2.0.**</mark>

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

<mark style="color:green;">**`GET`**</mark> `https://sms.textcus.com/api/send`

## **Request Parameters**

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>type</code></td><td>Required</td><td>It indicates the type of message.<br>Values for "type" include:<br>0 : Plain text (GSM 3.38 Character encoding)<br>1 : Flash (GSM 3.38 Character encoding)<br>2 : Unicode<br>3 : Reserved<br>5 : Plain text (ISO-8859-1 Character encoding)<br>6 : Unicode Flash<br>7 : Flash (ISO-8859-1 Character encoding)</td></tr><tr><td><code>source</code></td><td>Required</td><td>The source address that should appear in the message.<br>- Max Length of 18 if numeric.<br>- Max Length of 11 if alphanumeric.<br>To prefix the plus sign (+) to the sender’s address when the message is displayed on their mobile phone, please prefix the plus sign to your sender’s address while submitting the message.<br>Note: You need to URL encode the plus sign. The SMSC may enforce additional restrictions on this field.</td></tr><tr><td><code>destination</code></td><td>Required</td><td>Recipient phone number<br>Must be a valid MSIDSN<br>Must be in the international telephone number format (may or may not include a plus [+] sign) symbol. e.g. 233241234567 or +233241234567<br>Multiple mobile numbers need to be separated by a comma (,) (the comma should be URL encoded).</td></tr><tr><td><code>dlr</code></td><td>Required</td><td>Indicates whether the client wants a delivery report for this message.<br>The values for "dlr" include:<br>0 : No delivery report required<br>1 : Delivery report required</td></tr><tr><td><code>message</code></td><td>Required</td><td>The message to be sent. Must be URL encoded.</td></tr><tr><td><code>time</code></td><td>Optional</td><td>To schedule the message to be sent sometime or date in the future<br>Format: YYYY-MM-DD HH:MM:SS or UNIX TIMESTAMP<br>The Scheduled time must be at least 10 minutes ahead of the current time in UTC</td></tr></tbody></table>

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

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

```php
<?php

//defining the parameters
$apiKey = '63f113a2d1d06b27ebd33a4ui63e71902al3'; //Remember to put your account API Key here
$recipient = 23324xxxxxxx; //International format (233) excluding the (+)
$sender = 'TextCus'; //11 Characters maximum
$msg = "Hello, TextCus SMS is the best!";

//encode the message
$message = urlencode($msg);

$url = 'https://sms.textcus.com/api/send?apikey=' . $apiKey . '&destination=' . $recipient . '&source=' . $sender . '&dlr=0&type=0' . '&message=' . $message . '';

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => $url,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>
```

{% endtab %}
{% endtabs %}

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

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

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

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# Send SMS (v2)

Here are different ways you can send SMS and OTP to your users through these endpoints.

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><mark style="color:yellow;"><strong><code>POST</code></strong></mark></td><td>To send SMS data to the system, use this request.</td><td><a href="/pages/VKoxXUuYkMlaEUWxibdi#request-parameters">/pages/VKoxXUuYkMlaEUWxibdi#request-parameters</a></td></tr><tr><td><mark style="color:green;"><strong><code>GET</code></strong></mark></td><td>To retrieve SMS data from the system, use this request.</td><td><a href="/pages/VKoxXUuYkMlaEUWxibdi#request-parameters">/pages/VKoxXUuYkMlaEUWxibdi#request-parameters</a></td></tr></tbody></table>


# Quick Send

The HTTP API enables you to send SMS quickly. To send an SMS, simply call the following URL with the relevant parameters appended to the URL, as shown below:

{% hint style="info" %}
`https://api.textcus.com/api/v2/send?destination={recipient}&source={sender}&dlr={0}&type={0}&message={message}`
{% endhint %}

<mark style="color:red;">NB: Please remove the curly bracket in the URL when testing</mark>

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

<mark style="color:green;">**`GET`**</mark> `https://api.textcus.com/api/v2/send`

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

`Authorization: Bearer API_KEY`

## **Request Parameters**

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>type</code></td><td>Required</td><td>It indicates the type of message.<br>Values for "type" include:<br>0 : Plain text (GSM 3.38 Character encoding)<br>1 : Flash (GSM 3.38 Character encoding)<br>2 : Unicode<br>3 : Reserved<br>5 : Plain text (ISO-8859-1 Character encoding)<br>6 : Unicode Flash<br>7 : Flash (ISO-8859-1 Character encoding)</td></tr><tr><td><code>source</code></td><td>Required</td><td>The source address that should appear in the message.<br>- Max Length of 18 if numeric.<br>- Max Length of 11 if alphanumeric.<br>To prefix the plus sign (+) to the sender’s address when the message is displayed on their mobile phone, please prefix the plus sign to your sender’s address while submitting the message.<br>Note: You need to URL encode the plus sign. The SMSC may enforce additional restrictions on this field.</td></tr><tr><td><code>destination</code></td><td>Required</td><td>Recipient phone number<br>Must be a valid MSIDSN<br>Must be in the international telephone number format (may or may not include a plus [+] sign) symbol. e.g. 233241234567 or +233241234567<br>Multiple mobile numbers need to be separated by a comma (,) (the comma should be URL encoded).</td></tr><tr><td><code>dlr</code></td><td>Required</td><td>Indicates whether the client wants a delivery report for this message.<br>The values for "dlr" include:<br>0 : No delivery report required<br>1 : Delivery report required</td></tr><tr><td><code>message</code></td><td>Required</td><td>The message to be sent. Must be URL encoded.</td></tr><tr><td><code>time</code></td><td>Optional</td><td>To schedule the message to be sent sometime or date in the future<br>Format: YYYY-MM-DD HH:MM:SS or UNIX TIMESTAMP<br>The Scheduled time must be at least 10 minutes ahead of the current time in UTC</td></tr></tbody></table>

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

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

```php
<?php

$data = [
  'destination' => $recipient,
  'source' => $sender,
  'dlr' => 0,
  'type' => 0,
  'message' => $message
];

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

$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 recipient = 'RECIPIENT_NUMBER'; // Replace with the recipient's phone number
const sender = 'SENDER_NAME'; // Replace with the sender name
const message = 'YOUR_MESSAGE'; // Replace with the message to be sent

const data = {
  destination: recipient,
  source: sender,
  dlr: 0,
  type: 0,
  message: message
};

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

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

# Replace with your actual values
recipient = 'RECIPIENT_NUMBER'
sender = 'SENDER_NAME'
message = 'YOUR_MESSAGE'

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

params = {
    'destination': recipient,
    'source': sender,
    'dlr': 0,
    'type': 0,
    'message': message
}

headers = {
    'Authorization': 'Bearer API_KEY'
}

try:
    response = requests.get(url, params=params, headers=headers, timeout=30)

    if response.status_code == 200:
        print(response.json())
    else:
        print(f"Failed to send message. Status code: {response.status_code}")
        print(response.text)

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

{% endtab %}

{% tab title="Dart" %}

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

void main() async {
  String recipient = 'RECIPIENT_NUMBER';
  String sender = 'SENDER_NAME';
  String message = 'YOUR_MESSAGE';

  final uri = Uri.https(
    'api.textcus.com',
    '/api/v2/send',
    {
      'destination': recipient,
      'source': sender,
      'dlr': '0',
      'type': '0',
      'message': message,
    },
  );

  try {
    final response = await http.get(
      uri,
      headers: {
        'Authorization': 'Bearer API_KEY',
      },
    );

    if (response.statusCode == 200) {
      print(response.body);
    } else {
      print('Failed to send message. Status code: ${response.statusCode}');
      print(response.body);
    }
  } 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 recipient = "RECIPIENT_NUMBER"; // Replace with the recipient's phone number
        String sender = "SENDER_NAME"; // Replace with the sender name
        String message = "YOUR_MESSAGE"; // Replace with the message to be sent

        String url = "https://api.textcus.com/api/v2/send";

        Map<String, Object> data = new HashMap<>();
        data.put("destination", recipient);
        data.put("source", sender);
        data.put("dlr", 0);
        data.put("type", 0);
        data.put("message", message);

        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 recipient As String = "RECIPIENT_NUMBER" ' Replace with the recipient's phone number
        Dim sender As String = "SENDER_NAME" ' Replace with the sender name
        Dim message As String = "YOUR_MESSAGE" ' Replace with the message to be sent

        Dim url As String = "https://api.textcus.com/api/v2/send"

        ' Prepare the data to be sent
        Dim data As New Dictionary(Of String, Object) From {
            {"destination", recipient},
            {"source", sender},
            {"dlr", 0},
            {"type", 0},
            {"message", message}
        }

        ' 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": "Message sent successfully"
}
```

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# Send Multiple SMS

To send multiple SMS at a go, you need to implement a way to loop the contact with foreach or you can just append a comma (,) after every contact number.

{% hint style="info" %}
$recipient = '23324XXXXXXX,233020XXXXXXX'; //International format (233) excluding the (+)&#x20;
{% endhint %}

<mark style="color:orange;">NB: Place comma(,) after every number as seen above.</mark>


# Sender IDs

You can add and retrieve sender IDs through this endpoints. Follow the documentation to be able to achieve this.

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><mark style="color:yellow;"><strong><code>POST</code></strong></mark></td><td>To add new sender data to the system, use this request.</td><td><a href="/pages/WY2RKyopOdlYqEnL3pge">/pages/WY2RKyopOdlYqEnL3pge</a></td></tr><tr><td><mark style="color:green;"><strong><code>GET</code></strong></mark></td><td>To retrieve sender data from the system, use this request.</td><td><a href="/pages/E0dlsDwa2TG7Hogewzh8">/pages/E0dlsDwa2TG7Hogewzh8</a></td></tr></tbody></table>


# List Senders

A list of all senders may be obtained using this endpoint. For emphasis on specific results, you can add filters based on sender status, either approved or not approved.

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

<mark style="color:green;">**`GET`**</mark> `https://api.textcus.com/api/v2/senders`

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

`Authorization: Bearer API_KEY`

### **Header Parameters** <a href="#path-parameters" id="path-parameters"></a>

| Parameters                                           | Type     | Description                                                         |
| ---------------------------------------------------- | -------- | ------------------------------------------------------------------- |
| <p>apikey</p><p><em><strong>string</strong></em></p> | Required | Your unique API key is required to retrieve your TextCus Sender IDs |

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

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

```php
<?php
$url = 'https://api.textcus.com/api/v2/senders';

$curl = curl_init();

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: Bearer API_KEY' // Replace 'API_KEY' with your actual API key
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>
```

{% endtab %}

{% tab title="NodeJS" %}

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

const config = {
    method: 'get',
    url: `https://api.textcus.com/api/v2/senders`,
    headers: {
        'Authorization': 'Bearer API_KEY' // Replace 'API_KEY' with your actual API key
    }
};

axios(config).then(function(response) {
    console.log(JSON.stringify(response.data));
}).catch(function(error) {
    console.error(error);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = f'https://api.textcus.com/api/v2/senders'

headers = {
    "Authorization": "Bearer API_KEY" # Replace 'API_KEY' with your actual API key
}

try:
    response = requests.get(url, headers=headers)
    print(response.json())
except requests.exceptions.RequestException as e:
    print(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/senders';

  try {
    final response = await http.get(
      Uri.parse(url),
      headers: {
        'Authorization': 'Bearer API_KEY', // Replace 'API_KEY' with your actual API Key
      },
    );

    if (response.statusCode == 200) {
      // If the server returns an OK response, parse the JSON
      print(response.body);
    } else {
      // If the server did not return a 200 OK response, throw an exception.
      print('Failed to load balance. Status code: ${response.statusCode}');
    }
  } 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.HttpResponse.BodyHandlers;

public class CheckBalance {

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

        try {
            // Create HttpClient
            HttpClient client = HttpClient.newHttpClient();

            // Build the GET request
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Authorization", "Bearer API_KEY")  // Replace 'API_KEY' with your actual API Key
                    .GET()
                    .build();

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

            // Check if the request was successful
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.println("Failed to retrieve balance. 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.Threading.Tasks

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

        Dim response As String = GetApiResponseAsync(url, apiKey).GetAwaiter().GetResult()

        Console.WriteLine(response)
    End Sub

    Async Function GetApiResponseAsync(url As String, apiKey As String) As Task(Of String)
        Using client As New HttpClient()
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " & apiKey) ' Replace 'API_KEY' with your actual API key

            Dim response As HttpResponseMessage = Await client.GetAsync(url)
            If response.IsSuccessStatusCode Then
                Return Await response.Content.ReadAsStringAsync()
            Else
                Return "Error: " & response.StatusCode.ToString()
            End If
        End Using
    End Function
End Module
```

{% endtab %}
{% endtabs %}

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

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

```json
{
    "status": 200,
    "message": "Senders retrieved",
    "data": {
        "sender_name": "TextCus",
    },
    ...
}
```

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# Add Senders

Adding new sender may be obtained using this endpoint. For emphasis on specific results, you can add the following parameters when creating new sender.

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

<mark style="color:yellow;">**`POST`**</mark> `https://api.textcus.com/api/v2/senders/add`

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

`Authorization: Bearer API_KEY`

### **Body Parameters** <a href="#path-parameters" id="path-parameters"></a>

| Parameters                                                 | Type     | Description                                     |
| ---------------------------------------------------------- | -------- | ----------------------------------------------- |
| <p>sender\_name</p><p><em><strong>string</strong></em></p> | Required | Your 11 character sender ID name. eg. `TextCus` |
| <p>description</p><p><em><strong>string</strong></em></p>  | Required | The purpose of the sender ID                    |

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

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

```php
<?php
$data = [
  'sender_name' => "TextCus", // 11 Characters Only
  'description' => "For business SMS to my customers",
];

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

$curl = curl_init();

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 => 'POST',
  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 = {
  sender_name: "TextCus", // 11 Characters Only
  description: "For business SMS to my customers"
};

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

axios.post(url, data, {
  headers: {
    'Authorization': 'Bearer API_KEY',  // Replace 'API_KEY' with your actual API key
    'Content-Type': 'application/json'
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error:', error);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = 'https://api.textcus.com/api/v2/senders/add'
data = {
    'sender_name': 'TextCus',  # 11 Characters Only
    'description': 'For business SMS to my customers'
}
headers = {
    'Authorization': 'Bearer API_KEY',  # Replace 'API_KEY' with your actual API key
    'Content-Type': 'application/json'
}

response = requests.post(url, json=data, headers=headers)
print(response.text)
```

{% endtab %}

{% tab title="Dart" %}

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

void sendSMS() async {
  var url = Uri.parse('https://api.textcus.com/api/v2/senders/add');
  var data = {
    'sender_name': 'TextCus',  // 11 Characters Only
    'description': 'For business SMS to my customers'
  };

  var response = await http.post(
    url,
    headers: {
      'Authorization': 'Bearer API_KEY',  // Replace 'API_KEY' with your actual API key
      'Content-Type': 'application/json',
    },
    body: jsonEncode(data),
  );

  if (response.statusCode == 200) {
    print('Response: ${response.body}');
  } else {
    print('Error: ${response.statusCode}');
  }
}
```

{% endtab %}

{% tab title="Java" %}

```java
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class Main {
    public static void main(String[] args) {
        try {
            String url = "https://api.textcus.com/api/v2/senders/add";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer API_KEY"); // Replace 'API_KEY'
            con.setRequestProperty("Content-Type", "application/json");

            // Request body
            String jsonInputString = "{\"sender_name\": \"TextCus\", \"description\": \"For business SMS to my customers\"}";
            con.setDoOutput(true);
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

{% endtab %}

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

```vbnet
Imports System.Net
Imports System.Text
Imports System.IO

Module Module1
    Sub Main()
        Dim url As String = "https://api.textcus.com/api/v2/senders/add"
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        request.Method = "POST"
        request.ContentType = "application/json"
        request.Headers.Add("Authorization", "Bearer API_KEY") ' Replace 'API_KEY'

        ' JSON data
        Dim postData As String = "{""sender_name"": ""TextCus"", ""description"": ""For business SMS to my customers""}"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        Dim reader As New StreamReader(response.GetResponseStream())
        Dim responseText As String = reader.ReadToEnd()
        Console.WriteLine(responseText)

        reader.Close()
        response.Close()
    End Sub
End Module
```

{% endtab %}
{% endtabs %}

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

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

```json
{
    "status": 200,
    "message": "Sender ID added",
    "data": {
        "sender_name": "TextCus",
        "description": "For business SMS to my customers",
        "status": "no"
    }
}
```

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# Check Sender Status

A sender's status may be obtained using this endpoint for emphasis on specific results on sender status and whitelisting status.

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

<mark style="color:yellow;">**`POST`**</mark> `https://api.textcus.com/api/v2/senders/check-status`

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

`Authorization: Bearer API_KEY`

### **Body Parameters** <a href="#path-parameters" id="path-parameters"></a>

| Parameters                                                 | Type     | Description                                     |
| ---------------------------------------------------------- | -------- | ----------------------------------------------- |
| <p>sender\_name</p><p><em><strong>string</strong></em></p> | Required | Your 11 character sender ID name. eg. `TextCus` |

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

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

```php
<?php
$url = 'https://api.textcus.com/api/v2/senders/check-status';

$data = [
  'sender_name' => "TextCus", // 11 Characters Only
];

$curl = curl_init();

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 => 'POST',
  CURLOPT_POSTFIELDS => $data,
  CURLOPT_HTTPHEADER => array(
    'Authorization: Bearer API_KEY' // Replace 'API_KEY' with your actual API key
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>
```

{% endtab %}

{% tab title="NodeJS" %}

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

const data = {
  sender_name: "TextCus", // 11 Characters Only
};

const url = 'https://api.textcus.com/api/v2/senders/check-status';

axios.post(url, data, {
  headers: {
    'Authorization': 'Bearer API_KEY',  // Replace 'API_KEY' with your actual API key
    'Content-Type': 'application/json'
  }
})
.then(response => {
  console.log(response.data);
})
.catch(error => {
  console.error('Error:', error);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = 'https://api.textcus.com/api/v2/senders/check-status'
data = {
    'sender_name': 'TextCus',  # 11 Characters Only
}
headers = {
    'Authorization': 'Bearer API_KEY',  # Replace 'API_KEY' with your actual API key
    'Content-Type': 'application/json'
}

response = requests.post(url, json=data, headers=headers)
print(response.text)
```

{% endtab %}

{% tab title="Dart" %}

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

void checkSenderStatus() async {
  var url = Uri.parse('https://api.textcus.com/api/v2/senders/check-status');
  var data = {
    'sender_name': 'TextCus',  // 11 Characters Only
  };

  var response = await http.post(
    url,
    headers: {
      'Authorization': 'Bearer API_KEY',  // Replace 'API_KEY' with your actual API key
      'Content-Type': 'application/json',
    },
    body: jsonEncode(data),
  );

  if (response.statusCode == 200) {
    print('Response: ${response.body}');
  } else {
    print('Error: ${response.statusCode}');
  }
}
```

{% 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.HttpResponse.BodyHandlers;

public class CheckSenderStatus {
    public static void main(String[] args) {
        try {
            String url = "https://api.textcus.com/api/v2/senders/check-status";
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer API_KEY"); // Replace 'API_KEY'
            con.setRequestProperty("Content-Type", "application/json");

            // Request body
            String jsonInputString = "{\"sender_name\": \"TextCus\"}";
            con.setDoOutput(true);
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

```

{% endtab %}

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

```vbnet
Imports System.Net
Imports System.Text
Imports System.IO

Module Module1
    Sub Main()
        Dim url As String = "https://api.textcus.com/api/v2/senders/check-status"
        Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
        request.Method = "POST"
        request.ContentType = "application/json"
        request.Headers.Add("Authorization", "Bearer API_KEY") ' Replace 'API_KEY'

        ' JSON data
        Dim postData As String = "{""sender_name"": ""TextCus""}"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

        request.ContentLength = byteArray.Length
        Dim dataStream As Stream = request.GetRequestStream()
        dataStream.Write(byteArray, 0, byteArray.Length)
        dataStream.Close()

        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        Dim reader As New StreamReader(response.GetResponseStream())
        Dim responseText As String = reader.ReadToEnd()
        Console.WriteLine(responseText)

        reader.Close()
        response.Close()
    End Sub
End Module
```

{% endtab %}
{% endtabs %}

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

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

```json
{
    "status": 200,
    "message": "Sender statuses for TextCus retrieved",
    "data": {
        "sender_name": "TextCus",
        "status": "yes",
        "whitelist_status": "yes"
    }
}
```

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# Account Balance

TextCus Balance API allows you to retrieve your total sms, email & wallet balance information from your account. This endpoint can also help you create notifications when your balance is going low.

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

<mark style="color:green;">**`GET`**</mark> `https://api.textcus.com/api/v2/balance`

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

`Authorization: Bearer API_KEY`

### **Header Parameters** <a href="#path-parameters" id="path-parameters"></a>

| Parameters                                           | Type     | Description                                                      |
| ---------------------------------------------------- | -------- | ---------------------------------------------------------------- |
| <p>apikey</p><p><em><strong>string</strong></em></p> | Required | Your unique API key is required to retrieve your TextCus balance |

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

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

```php
<?php
$url = 'https://api.textcus.com/api/v2/balance';

$curl = curl_init();

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: Bearer API_KEY' // Replace 'API_KEY' with your actual API key
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

?>
```

{% endtab %}

{% tab title="NodeJS" %}

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

const config = {
    method: 'get',
    url: `https://api.textcus.com/api/v2/balance`,
    headers: {
        'Authorization': 'Bearer API_KEY' // Replace 'API_KEY' with your actual API key
    }
};

axios(config).then(function(response) {
    console.log(JSON.stringify(response.data));
}).catch(function(error) {
    console.error(error);
});
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

url = f'https://api.textcus.com/api/v2/balance'

headers = {
    "Authorization": "Bearer API_KEY" # Replace 'API_KEY' with your actual API key
}

try:
    response = requests.get(url, headers=headers)
    print(response.json())
except requests.exceptions.RequestException as e:
    print(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/balance';

  try {
    final response = await http.get(
      Uri.parse(url),
      headers: {
        'Authorization': 'Bearer API_KEY', // Replace 'API_KEY' with your actual API Key
      },
    );

    if (response.statusCode == 200) {
      // If the server returns an OK response, parse the JSON
      print(response.body);
    } else {
      // If the server did not return a 200 OK response, throw an exception.
      print('Failed to load balance. Status code: ${response.statusCode}');
    }
  } 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.HttpResponse.BodyHandlers;

public class CheckBalance {

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

        try {
            // Create HttpClient
            HttpClient client = HttpClient.newHttpClient();

            // Build the GET request
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Authorization", "Bearer API_KEY")  // Replace 'API_KEY' with your actual API Key
                    .GET()
                    .build();

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

            // Check if the request was successful
            if (response.statusCode() == 200) {
                System.out.println("Response: " + response.body());
            } else {
                System.out.println("Failed to retrieve balance. 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.Threading.Tasks

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

        Dim response As String = GetApiResponseAsync(url, apiKey).GetAwaiter().GetResult()

        Console.WriteLine(response)
    End Sub

    Async Function GetApiResponseAsync(url As String, apiKey As String) As Task(Of String)
        Using client As New HttpClient()
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " & apiKey) ' Replace 'API_KEY' with your actual API key

            Dim response As HttpResponseMessage = Await client.GetAsync(url)
            If response.IsSuccessStatusCode Then
                Return Await response.Content.ReadAsStringAsync()
            Else
                Return "Error: " & response.StatusCode.ToString()
            End If
        End Using
    End Function
End Module
```

{% endtab %}
{% endtabs %}

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

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

```json
{
    "status": 200,
    "message": "Balance retrieved",
    "data": {
        "sms_rate": 0.028,
        "sms_balance": 71429,
        "email_balance": 2000,
        "wallet_balance": 0.00,
    }
}
```

{% endtab %}

{% tab title="Errors" %}

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

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

{% endtab %}
{% endtabs %}


# One Time Password (OTP)

This endpoint is used for verification process when authenticating a user on your platform.

### 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 %}


# Email SMTP

This endpoint is used for Email SMTP when sending emails to a user on your platform.

Coming Soon


# USSD Integration

Go beyond apps — reach every mobile user offline with our seamless USSD integration.

Coming Soon


# Whatsapp

TextCus is a messaging platform enabling businesses to communicate with customers via WhatsApp Cloud API, including OTPs, notifications, and support.

Coming Soon


