Code examples

Python

Flask app that creates a session and reads the result.

A small Flask app: a signed-in user clicks Verify my identity, goes through KayWhySee, and comes back to a page that shows the result. It uses requests for the API calls.

link Set up

Terminal
python -m venv .venv && source .venv/bin/activate
pip install flask requests
export KAYWHYSEE_API_KEY="kyc_live_..."

link The API client

kaywhysee.py
import os

import requests

BASE_URL = "https://www.kaywhysee.com/api/v1"


class KayWhySeeError(Exception):
    def __init__(self, status, code, message):
        super().__init__(message)
        self.status = status
        self.code = code


def _call(method, path, body=None):
    response = requests.request(
        method,
        BASE_URL + path,
        headers={"Authorization": f"Bearer {os.environ['KAYWHYSEE_API_KEY']}"},
        json=body,
        timeout=10,
    )
    data = response.json()
    if not response.ok:
        error = data.get("error") or {}
        raise KayWhySeeError(response.status_code, error.get("code"), error.get("message"))
    return data


def create_session(reference, redirect_url=None):
    return _call("POST", "/sessions", {"reference": reference, "redirect_url": redirect_url})


def get_session(session_id):
    return _call("GET", f"/sessions/{session_id}")


def cancel_session(session_id):
    return _call("POST", f"/sessions/{session_id}/cancel")

link The app

app.py
from flask import Flask, redirect

from kaywhysee import create_session, get_session

app = Flask(__name__)
sessions = {}  # your database, in real life: user id -> session id


def current_user_id():
    return "user_1042"  # your own sign-in decides who this is


@app.get("/")
def home(): 
    return '<form method="post" action="/verify"><button>Verify my identity</button></form>'


@app.post("/verify")
def verify():
    user_id = current_user_id()
    session = create_session(user_id, "http://localhost:5000/verified")
    sessions[user_id] = session["id"]
    return redirect(session["start_url"], code=303)


@app.get("/verified")
def verified():
    # Arriving here proves nothing: always ask the API.
    session = get_session(sessions[current_user_id()])
    if session["outcome"] == "clear":
        return "You're verified."
    if session["outcome"] == "rejected":
        return "We couldn't verify you."
    return f"Thanks! We're checking your details (status: {session['status']})."

link Run it

Terminal
flask --app app run

Open http://localhost:5000, click the button and finish on your phone.

Was this page helpful?

Authorization

Your secret key stays in this tab: it is sent with this request only and never stored.

Body application/json

Response

Send the request to see the response.