Sample code for bank validation
This page provides sample code to help you set up Postcoder bank validation.
Copy any example below and then insert your own API key to make it work. Sign up to get an API key.
Bank validation using JavaScript
This example uses the bank endpoint to check a UK sort code and account number, and get details about the bank and branch. It can be customised using the config settings at the end of the HTML.
Bank validation: Enable access on your API key using the Features page or by contacting us.
class PostcoderBank{
constructor(config) {
this.config = config
this.init()
}
init() {
this.endpoint = 'https://ws.postcoder.com/pcw/' + this.config.apikey + '/bank/'
this.sortcode_input = document.querySelector(this.config.sortcode)
this.accountnumber_input = document.querySelector(this.config.accountnumber)
this.submit_btn = document.querySelector(this.config.submitbtn)
// add click event listener to the submit button, to call the search function
this.submit_btn.addEventListener('click', this.search)
// add a result container to the page, delete when not required.
this.resultcontainer = document.createElement('pre')
this.submit_btn.closest('form').appendChild(this.resultcontainer)
}
search = event => {
event.preventDefault()
if(this.sortcode_input.value && this.accountnumber_input.value){
let self = this
let sortcode = this.sortcode_input.value
let accountnumber = this.accountnumber_input.value
fetch(this.endpoint, {
method: 'post',
headers: {
"Content-Type": "application/json",
},
body: `{"sortcode":"${sortcode}","accountnumber":"${accountnumber}"}`
}).then( response => {
if (!response.ok) {
throw response
}
return response.json()
}).then(data => {
self.processResult(data)
}).catch( err => {
if(typeof err.text === 'function'){
err.text().then( errorMessage => {
console.log('Postcoder request error ' + err.status + ' : ' + errorMessage)
})
}else{
console.log(err)
}
})
}
}
processResult = result =>{
// show result on page, delete when not required.
this.resultcontainer.innerHTML = "Result: \n\n" + JSON.stringify( result, null, 4 )
}
}
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="postcoder.css" >
<script src="postcoder_bank.js"></script>
</head>
<body>
<form>
<label for="txt_sortcode">Sort code</label>
<input type="text" id="txt_sortcode">
<label for="txt_accountnumber">Account number</label>
<input type="text" id="txt_accountnumber">
<button id="btn_submit">Submit</button>
</form>
<script>
new PostcoderBank({
apikey: 'PCW45-12345-12345-1234X',
sortcode: '#txt_sortcode', // query selector of the sortcode input field
accountnumber: '#txt_accountnumber', // query selector of the accountnumber input field
submitbtn: '#btn_submit', // query selector of the submit button
})
</script>
</body>
</html>
input, select {
display: block;
box-sizing: border-box;
width: 100%;
padding: 10px;
height: 40px;
margin-bottom: 0.5em;
border-width: 1px;
border-style: solid;
border-color: lightgray;
}
.search_wrap {
overflow: hidden;
}
.search_wrap div {
font-size: 0.75em;
}
button {
padding: 8px;
margin-left: 0.5em;
float: right;
font-family: sans-serif;
}
label {
display: block;
margin-top: 1.25em;
margin-bottom: 0.25em;
}
select {
position: relative;
z-index: 1;
padding-right: 40px;
}
.isvalid:after {
content: '\2713';
color: green;
}
.notvalid:after {
content: '\2717';
color: red;
}
#successindicator {
float: right;
margin-left: 0.5em;
display: flex;
justify-content: center;
align-content: center;
flex-direction: column;
height: 40px;
}
#json_result_container {
margin: 5em 0 0;
background-color: #eee;
color: #333;
/* border: solid lightgrey 1px; */
padding: 1em;
overflow: auto;
}
#autocomplete_wrap{
position: relative;
}
#suggestion_list{
position: absolute;
background-color: #fff;
outline: -webkit-focus-ring-color auto 1px;
list-style-type: none;
margin: 0;
padding: 0;
max-height: 400px;
overflow-y: auto;
}
#suggestion_list li{
cursor: pointer;
padding: 10px 5px;
}
#suggestion_list li.header{
border-bottom: 2px solid #ddd;
}
#suggestion_list li:hover, #suggestion_list li.selected{
background-color: #ddd;
}
#suggestion_list li span.location{
font-size: 0.75em;
color: #666;
}
.arrow {
border: solid black;
border-width: 0 3px 3px 0;
display: inline-block;
padding: 3px;
}
.left {
margin-left: 3px;
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
.address{
height: 140px;
margin: 8px;
}
.map {
height: 300px;
width: 100%;
}
body {
font-family: sans-serif;
padding: 0;
margin: 0;
}
Bank validation using Python, PHP or C#
These examples show how to make a request to the bank endpoint to check a UK sort code and account number, and get details about the bank and branch.
Bank validation: 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"
sort_code = "100000"
account_number = "31510604"
# Prepare request and encode user-entered parameters with %xx encoding
request_url = f"https://ws.postcoder.com/pcw/{api_key}/bank"
request_body = {
"sortcode": f"{quote(sort_code, safe='')}",
"accountnumber": f"{quote(account_number, safe='')}",
}
# Send request
response = requests.post(request_url, json=request_body)
# Process response
if response.status_code == 200:
json = response.json()
print(json["valid"], json["bankname"], json["branchname"])
else:
print(f"Request error: {response.content.decode()}")
// Request parameters
$api_key = "PCW45-12345-12345-1234X";
$sort_code = "100000";
$account_number = "31510604";
// Prepare request and encode user-entered parameters with %xx encoding
$request_url = "https://ws.postcoder.com/pcw/$api_key/bank";
$data = array("sortcode" => $sort_code, "accountnumber" => $account_number);
$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<br>$json->bankname<br>$json->branchname");
} 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 sortCode = "100000";
string accountNumber = "31510604";
// Prepare request and encode user-entered parameters with %xx encoding
string requestUrl = $"https://ws.postcoder.com/pcw/{apiKey}/bank";
var content = new Dictionary<string, string>
{
{ "sortcode", sortCode },
{ "accountnumber", accountNumber }
};
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"]}, {responseJson["bankname"]}, {responseJson["branchname"]}");
}
else
{
Console.WriteLine($"Request error: {responseContent}");
}
}
}
}