"""Check Share Code API client for Python: right to work, right to rent, immigration status, driving licence and SIA licence checks (https://checksharecode.co.uk/docs/clients). One file, standard library only, Python 3.9+. Copy it into your project: curl -O https://checksharecode.co.uk/clients/checksharecode.py import os from checksharecode import CheckShareCode csc = CheckShareCode(os.environ["CHECKSHARECODE_API_KEY"]) result = csc.right_to_work( share_code="AB1CD2EF3", date_of_birth="1990-01-01", company_name="Acme Ltd" ) What it does for you: sends the key, waits out BUSY and retries TIMEOUT and INTERNAL (never a driving licence check whose code may have been used), sends Northern Ireland licence numbers to their own endpoint, polls asynchronous checks, and verifies webhooks. Keys starting rtw_test_ get the sandbox's fixed answers, free; rtw_live_ keys run real checks. Answers are the API's JSON as dicts; every field is described at https://checksharecode.co.uk/openapi.json. """ from __future__ import annotations import base64 import hashlib import hmac import json import re import time import urllib.error import urllib.parse import urllib.request import uuid from typing import Any, Dict, Mapping, Optional CLIENT_VERSION = "2026-11-23" PATHS = { "right_to_work": "/v1/check/right-to-work", "right_to_rent": "/v1/check/right-to-rent", "immigration_status": "/v1/check/immigration-status", "driving_licence": "/v1/check/driving-licence", "sia_licence": "/v1/check/sia-licence", } NI_LICENCE_PATH = "/v1/check/driving-licence-ni" RETRYABLE = {"BUSY", "TIMEOUT", "INTERNAL", "RATE_LIMITED"} # The longest Retry-After worth waiting for in a request; longer ones are raised. MAX_WAIT_S = 30 class CheckShareCodeError(Exception): """Any refusal from the API. Switch on `code` (INVALID_INPUT, NOT_FOUND, SHARE_CODE_UNUSABLE, CHECK_CODE_UNUSABLE, QUOTA_EXCEEDED...): https://checksharecode.co.uk/docs/api/check#errors. `check_code_used` (driving licence errors): False means send the same code again; True or "unknown", ask the driver for a new one. `error` is the whole error dict, with upgrade_url, claim_url and the like when present. Quote `request_id` when you contact us. """ def __init__( self, status: int, error: Dict[str, Any], retry_after: Optional[int] = None, request_id: Optional[str] = None, ): super().__init__(f"{error.get('code')}: {error.get('message')}") self.status = status self.code: str = error.get("code", "UNEXPECTED_RESPONSE") self.message: str = error.get("message", "") self.check_code_used = error.get("check_code_used") self.retry_after = retry_after self.request_id = request_id self.error = error def is_retryable(err: CheckShareCodeError, check: str) -> bool: """Whether the same request may be sent again. BUSY, TIMEOUT, INTERNAL and RATE_LIMITED may, except a driving licence check whose code DVLA or DVA may have seen: a code works once.""" if err.code not in RETRYABLE: return False if check == "driving_licence": return err.check_code_used is False or err.check_code_used is None return True def _path_for(check: str, body: Mapping[str, Any]) -> str: if check not in PATHS: raise ValueError(f"unknown check {check!r}: one of {', '.join(PATHS)}") if check != "driving_licence": return PATHS[check] # Northern Ireland numbers are 8 digits; GB ones always have a letter in their last 8. number = re.sub(r"\s", "", str(body.get("licence_number", ""))) return NI_LICENCE_PATH if re.fullmatch(r"\d{8}", number) else PATHS["driving_licence"] class CheckShareCode: """The client. `timeout` is per request in seconds (a live check usually takes 15 to 40); `max_attempts` is tries per check, the first included (1 turns retries off).""" def __init__( self, api_key: Optional[str], base_url: str = "https://api.checksharecode.co.uk", timeout: float = 60, max_attempts: int = 3, ): if not api_key: raise ValueError( "CheckShareCode: no API key (get one at https://checksharecode.co.uk/signup)" ) self._api_key = api_key self.base_url = base_url.rstrip("/") self.timeout = timeout self.max_attempts = max(1, max_attempts) @property def mode(self) -> str: """"test" for a sandbox key (rtw_test_), "live" for a live one (rtw_live_).""" return "test" if self._api_key.startswith("rtw_test_") else "live" def right_to_work(self, *, share_code: str, date_of_birth: str, company_name: str) -> dict: return self.check( "right_to_work", {"share_code": share_code, "date_of_birth": date_of_birth, "company_name": company_name}, ) def right_to_rent( self, *, share_code: str, date_of_birth: str, checker_name: str, checker_type: str ) -> dict: """`checker_type` is "landlord" or "agent".""" return self.check( "right_to_rent", { "share_code": share_code, "date_of_birth": date_of_birth, "checker_name": checker_name, "checker_type": checker_type, }, ) def immigration_status( self, *, share_code: str, date_of_birth: str, company_name: str, job_title: str, purpose: str, other_purpose: Optional[str] = None, ) -> dict: """`purpose` is one of driving_licence, student_loan, education_or_training, health_insurance_card, personal_finance, homelessness_or_council_housing, travel or other (then give `other_purpose`).""" body = { "share_code": share_code, "date_of_birth": date_of_birth, "company_name": company_name, "job_title": job_title, "purpose": purpose, } if other_purpose is not None: body["other_purpose"] = other_purpose return self.check("immigration_status", body) def driving_licence(self, *, licence_number: str, check_code: str) -> dict: """A GB licence number (16 characters, or the last 8) or a Northern Ireland one (8 digits). A check code works once: on CHECK_CODE_UNUSABLE, or an error whose `check_code_used` is True or "unknown", ask the driver for a new code.""" return self.check( "driving_licence", {"licence_number": licence_number, "check_code": check_code} ) def sia_licence(self, *, licence_number: str) -> dict: """The 16 digits on a Security Industry Authority licence. A licence not on the register is a NOT_FOUND error.""" return self.check("sia_licence", {"licence_number": licence_number}) def check(self, check: str, body: Mapping[str, Any]) -> dict: """Runs a check and waits for its answer, retrying what may be retried.""" path = _path_for(check, body) return self._with_retries(check, lambda: self._request("POST", path, dict(body))) def start_check( self, check: str, body: Mapping[str, Any], *, callback_url: Optional[str] = None, client_reference: Optional[str] = None, idempotency_key: Optional[str] = None, ) -> dict: """Queues a check and answers at once (202). Get the result from `wait_for_check`, `get_check`, or your webhook. `callback_url` is where to post the result (https); `client_reference` your own id, never applicant data. Sending the same `idempotency_key` again returns the first check (one is made for you if absent).""" path = _path_for(check, body) + "/async" payload = dict(body) if callback_url is not None: payload["callback_url"] = callback_url if client_reference is not None: payload["client_reference"] = client_reference headers = {"idempotency-key": idempotency_key or str(uuid.uuid4())} return self._with_retries(check, lambda: self._request("POST", path, payload, headers)) def get_check(self, check_id: str) -> dict: """An asynchronous check, by its id (chk_...).""" quoted = urllib.parse.quote(check_id, safe="") return self._request("GET", f"{PATHS['right_to_work']}/async/{quoted}") def wait_for_check(self, check_id: str, interval: float = 3, timeout: float = 600) -> dict: """Polls until the check has succeeded or failed, and returns it.""" deadline = time.monotonic() + timeout while True: job = self.get_check(check_id) if job["status"] in ("succeeded", "failed"): return job if time.monotonic() + interval > deadline: raise TimeoutError(f"CheckShareCode: check {check_id} still {job['status']}") time.sleep(interval) def _with_retries(self, check: str, send): attempt = 1 while True: try: return send() except CheckShareCodeError as err: if attempt >= self.max_attempts or not is_retryable(err, check): raise wait = err.retry_after if err.retry_after is not None else 2 * attempt if wait > MAX_WAIT_S: raise time.sleep(wait) attempt += 1 def _request( self, method: str, path: str, body: Optional[dict] = None, headers: Optional[Dict[str, str]] = None, ) -> dict: data = None if body is None else json.dumps(body).encode() request = urllib.request.Request(self.base_url + path, data=data, method=method) request.add_header("Authorization", f"Bearer {self._api_key}") request.add_header("Accept", "application/json") request.add_header("User-Agent", f"checksharecode-python/{CLIENT_VERSION}") if data is not None: request.add_header("Content-Type", "application/json") for name, value in (headers or {}).items(): request.add_header(name, value) try: with urllib.request.urlopen(request, timeout=self.timeout) as res: text = res.read().decode() return json.loads(text) if text else {} except urllib.error.HTTPError as res: text = res.read().decode(errors="replace") try: error = json.loads(text)["error"] except (ValueError, KeyError, TypeError): # Not our JSON (a proxy's page): never retried, since it can't say whether a # driving licence code was used. error = { "code": "UNEXPECTED_RESPONSE", "message": f"HTTP {res.code}: {text[:200]}", } retry_after = res.headers.get("Retry-After") raise CheckShareCodeError( res.code, error, int(retry_after) if retry_after and retry_after.isdigit() else None, res.headers.get("X-Request-Id"), ) from None class WebhookVerificationError(Exception): pass def verify_webhook( secret: str, headers: Mapping[str, str], body: Any, tolerance_seconds: int = 300, now: Optional[float] = None, ) -> dict: """Checks a webhook's Standard Webhooks signature with your whsec_ secret (on /app/webhooks, one for live and one for sandbox) and returns the event as a dict. Pass the raw body (bytes or str) exactly as it arrived: re-serialising the JSON breaks the signature. Raises WebhookVerificationError for a bad signature or a timestamp over 5 minutes out, so a captured request can't be replayed. Answer 2xx within 10 seconds; the same event can arrive more than once (dedupe on the webhook-id header).""" lower = {k.lower(): v for k, v in headers.items()} msg_id = lower.get("webhook-id") timestamp = lower.get("webhook-timestamp") signatures = lower.get("webhook-signature") if not msg_id or not timestamp or not signatures: raise WebhookVerificationError("missing webhook headers") try: sent = int(timestamp) except ValueError: raise WebhookVerificationError("timestamp too old or too new") from None if abs((time.time() if now is None else now) - sent) > tolerance_seconds: raise WebhookVerificationError("timestamp too old or too new") raw = body.encode() if isinstance(body, str) else bytes(body) key = base64.b64decode(secret[len("whsec_"):] if secret.startswith("whsec_") else secret) signed = msg_id.encode() + b"." + timestamp.encode() + b"." + raw expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode() for part in signatures.split(" "): version, _, mac = part.partition(",") if version == "v1" and hmac.compare_digest(mac, expected): return json.loads(raw) raise WebhookVerificationError("no valid signature")