Cookie

Cookie consent

We use some essential cookies to make this website work. We'd like to set additional cookies to help us measure your experience when you view and interact with the website.

Cookie policy

Sample code for OTP verification

This page provides sample code to help you set up Postcoder one-time password (OTP) verification.

Copy any example below and then insert your own API key to make it work. Sign up to get an API key.

Send an OTP using Python, PHP or C#

These examples show how to make a request to the otp/send endpoint to send an OTP via SMS.

OTP verification: Enable access on your API key using the Features page or by contacting us.
from urllib.parse import quote
import requests
import json

# Request parameters
api_key = "PCW45-12345-12345-1234X"
to_mobile = "07500123456"
from_name = "Example.com"
message = "Hello from [from]. Your security code is [otp]. It will expire in [expiry] minutes. Do not share this code."
otp_length = 6
expiry = 5

# Prepare request and encode user-entered parameters with %xx encoding
request_url = f"https://ws.postcoder.com/pcw/{api_key}/otp/send"

request_body = {
    "to": f"{quote(to_mobile, safe='')}",
    "from": f"{quote(from_name, safe='')}",
    "message": f"{quote(message, safe='')}",
    "otplength": otp_length,
    "expiry": expiry
}

# Make request to send OTP via SMS
response = requests.post(request_url, json=request_body)

# Get ID to use with the otp/verify endpoint
if response.status_code == 200:
    json = response.json()
    print(json["id"])
else:
    print(f"Request error: {response.content.decode()}")
// Request parameters
$api_key = "PCW45-12345-12345-1234X";
$to = "07500123456";
$from = "Example.com";
$message = "Hello from [from]. Your security code is [otp]. It will expire in [expiry] minutes. Do not share this code.";
$otp_length = 6;
$expiry = 5;

// Prepare request and encode user-entered parameters with %xx encoding
$request_url = "https://ws.postcoder.com/pcw/$api_key/otp/send";

$data = array("to" => $to, "from" => $from, "message" => $message, "otplength" => $otp_length, "expiry" => $expiry);

$context = stream_context_create([
  "http" => [
    "header"  => "Content-type: application/x-www-form-urlencoded\r\n",
    "method"  => "POST",
    "content" => http_build_query($data),
    "ignore_errors" => true
  ]
]);

// Make request to send OTP via SMS
$result = file_get_contents($request_url, false, $context);

// Get ID to use with the otp/verify endpoint
$status_line = $http_response_header[0];
preg_match("{HTTP\/\S*\s(\d{3})}", $status_line, $match);
$status_code = $match[1];

if ($status_code == 200) {
    $json = json_decode($result);
    echo($json->id);
} else {
    echo("Request error");
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static async Task Main()
	{
		// Request parameters
		string apiKey = "PCW45-12345-12345-1234X";
		string to = "07500123456";
		string from = "Example.com";
		string message = "Hello from [from]. Your security code is [otp]. It will expire in [expiry] minutes. Do not share this code.";
		int otpLength = 6;
		int expiry = 5;

		// Prepare request and encode user-entered parameters with %xx encoding
		string requestUrl = $"https://ws.postcoder.com/pcw/{apiKey}/otp/send";
		
		var content = new Dictionary<string, string>
		{
			{ "to", to },
			{ "from", from },
			{ "message", message },
			{ "otplength", otpLength },
			{ "expiry", expiry }
		};
		var encodedContent = new FormUrlEncodedContent(content);

		using (HttpClient client = new HttpClient())
		{
			// Make request to send OTP via SMS
			var response = await client.PostAsync(requestUrl, encodedContent);
			var responseContent = await response.Content.ReadAsStringAsync();

			// Get ID to use with the otp/verify endpoint
			if (response.IsSuccessStatusCode)
			{
				JObject responseJson = JObject.Parse(responseContent);
				Console.WriteLine(responseJson["id"]);
			}
			else
			{
				Console.WriteLine($"Request error: {responseContent}");
			}
		}
	}
}

Verify an OTP using Python, PHP or C#

These examples show how to make a request to the otp/verify endpoint to verify an OTP.

OTP verification: Enable access on your API key using the Features page or by contacting us.
from urllib.parse import quote
import requests
import json

# Request parameters; ID is provided by the otp/send endpoint
api_key = "PCW45-12345-12345-1234X"
id = "OTP45-12345-12345-1234X"
otp = "532132"

# Prepare request and encode user-entered parameters with %xx encoding
request_url = f"https://ws.postcoder.com/pcw/{api_key}/otp/verify"

request_body = {
    "id": f"{quote(id, safe='')}",
    "otp": f"{quote(otp, safe='')}"
}

# Send request
response = requests.post(request_url, json=request_body)

# Process response
if response.status_code == 200:
    json = response.json()
    print(json["valid"])
else:
    print(f"Request error: {response.content.decode()}")
// Request parameters; ID is provided by the otp/send endpoint
$api_key = "PCW45-12345-12345-1234X";
$id = "OTP45-12345-12345-1234X";
$otp = "532132";

// Prepare request and encode user-entered parameters with %xx encoding
$request_url = "https://ws.postcoder.com/pcw/$api_key/otp/verify";

$data = array("id" => $id, "otp" => $otp);

$context = stream_context_create([
  "http" => [
    "header"  => "Content-type: application/x-www-form-urlencoded\r\n",
    "method"  => "POST",
    "content" => http_build_query($data),
    "ignore_errors" => true
  ]
]);

// Send request
$result = file_get_contents($request_url, false, $context);

// Process response
$status_line = $http_response_header[0];
preg_match("{HTTP\/\S*\s(\d{3})}", $status_line, $match);
$status_code = $match[1];

if ($status_code == 200) {
    $json = json_decode($result);
    echo($json->valid);
} else {
    echo("Request error");
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json.Linq;
					
public class Program
{
	public static async Task Main()
	{
		// Request parameters; ID is provided by the otp/send endpoint
		string apiKey = "PCW45-12345-12345-1234X";
		string id = "OTP45-12345-12345-1234X";
		string otp = "532132";

		// Prepare request and encode user-entered parameters with %xx encoding
		string requestUrl = $"https://ws.postcoder.com/pcw/{apiKey}/otp/verify";
		
		var content = new Dictionary<string, string>
		{
			{ "id", id },
			{ "otp", otp }
		};
		var encodedContent = new FormUrlEncodedContent(content);

		using (HttpClient client = new HttpClient())
		{
			// Send request
			var response = await client.PostAsync(requestUrl, encodedContent);
			var responseContent = await response.Content.ReadAsStringAsync();

			// Process response
			if (response.IsSuccessStatusCode)
			{
				JObject responseJson = JObject.Parse(responseContent);
				Console.WriteLine(responseJson["valid"]);
			}
			else
			{
				Console.WriteLine($"Request error: {responseContent}");
			}
		}
	}
}