Part 3 of Behind the Tap, a series on how contactless payments work. Part 2 showed how a phone pays by pretending to be a card.

Count the places your card is saved. The wallet on your phone, maybe your watch, a streaming service, a ride-hailing app, the online shop you order from every month. Where those are tokenised, and more of them are every year, none of them holds your card number. Each holds its own token: a different 16-digit number with its own rules about where it can be used.

So one card can have a handful of numbers alive at the same time. The bank issued one of them. The rest were created later by the card network, on request, and each one will be suspended, updated and finally retired on its own schedule.

This post follows one token through that life: who is allowed to ask for it, how it gets issued, what is checked every time it's used, and what happens to it when your phone goes missing or your card is renewed.

Who is allowed to ask

Not just anyone. A token is requested by a Token Requestor: a wallet such as Apple Pay or Google Pay, a merchant that stores cards, a payment gateway, or the bank's own app. Before it can ask for a single token, a requestor has to register with the network's Token Service Provider, the part of the network that creates tokens and runs the vault that maps them back to card numbers. Registration is a vetting process, with due diligence on who the requestor is and what it intends to do with tokens.

What comes out of it is a Token Requestor ID, 11 digits long. The first three identify the Token Service Provider, the other eight the requestor. A requestor that does several different things gets several IDs, because the ID doesn't only name the company. It names the company and the job. "This wallet, paying contactless from a phone" is a different ID from "this wallet, paying inside apps".

At registration the two sides also agree the rules every token under that ID will carry, and where those tokens will be kept: in a secure element, in a phone's ordinary storage (as with the HCE wallets from part 2), on a merchant's servers, and so on.

Asking for one

When you add a card to your phone, the wallet sends a token request. It carries the requestor's ID, your card number and expiry date, where the token will live, and evidence that it's really you adding the card.

That evidence is the part that matters. EMV calls it ID&V, identification and verification, and it can come in several forms:

  • a basic account check by the bank: the CVV matches, or a zero-amount authorisation goes through
  • a one-time code or a login, where you prove who you are directly
  • a risk assessment from data the requestor already holds: how old your account is, the device, its location, the IP address
  • the bank vouching for you, because you started the request inside its own mobile banking app, where you're already signed in

The Token Service Provider records the outcome in a two-digit Token Assurance Method. A few values show how it reads: 00 means nobody checked, 10 means the bank verified the account, 12 means the bank ran a two-factor check, and 14 means the bank asserted it was you.

Two things about this field are easy to miss. First, a token can be issued at 00. Nothing in the design forces an unchecked request to be refused; that's left to the network's rules and the bank. Second, the value doesn't stay in the vault. It can travel with each payment to the bank, next to the real card number. So every time the token is used, the bank can see how well it was vetted on the day it was created.

That ties straight back to part 2, where I said that adding the card to a wallet is the weak moment. This is the field that lets a bank do something about it.

What the token gets

If the request is accepted, the Token Service Provider creates four things.

  • The token. A number from a token BIN range. It's the same length as a card number, passes the same check-digit test and routes like one, so terminals, acquirers and switches handle it unchanged. The range is what tells the network to send it to the vault.
  • Its own expiry date, separate from the card's.
  • Its rules. EMV calls them Token Domain Restriction Controls: which ways the token may arrive (contactless only, for a phone), which merchant may use it (for a shop's card on file), and whether every payment must carry a fresh cryptogram.
  • A PAR, the Payment Account Reference.

The PAR is worth a closer look. It's 29 characters: four that identify the organisation controlling the card's BIN, and 25 generated so they can't be turned back into the card number. Your card and every one of its tokens share the same PAR. That lets a transit operator see that the tap from your phone and the tap from your plastic card belong to the same traveller, so it can cap your fares, without ever seeing your card number. It's deliberately limited: it can't be used to route a payment, or as an identifier for you as a person.

The life of one payment token as a line with seven stops: requested by a wallet with Token Requestor ID 40100000001; issued by the Token Service Provider with token 4900โ€ฆ0011, expiry 11/30, a PAR, contactless-only rules and assurance 14; first tap with entry mode 07 and a fresh cryptogram; suspended when the phone is reported lost; activated when it is found; card renewed with a new expiry 08/31 while the token keeps working; unlinked when the account closes. Below: checked on every payment โ€” in the vault, active, token expiry, entry mode, merchant, cryptogram used once โ€” then swapped for the card number.

What happens on every payment

When a payment arrives with a token in it, the network sends it to the vault before anything reaches your bank. The vault works down a short list:

  1. Is this a token we issued?
  2. Is it active?
  3. Does the expiry date match the token's (not the card's)?
  4. Did it arrive the way its rules allow? A phone token that turns up typed into a website, with entry mode 01 instead of 07 for contactless, fails here.
  5. If it belongs to one merchant, is this that merchant?
  6. If it needs a cryptogram, is the cryptogram right, and has it never been seen before?

Only then is the token swapped for your card number and expiry, and the request goes on to your bank with extras such as the assurance method and the PAR. The bank makes its usual decision on the real card. On the way back the card number is swapped for the token again, so the merchant never sees it. What the merchant does get back is the last four digits of the real card, which is how a receipt can still tell you which card paid.

The cryptogram check is what makes a stolen token close to worthless. A cryptogram is good for one payment. Record a tap and replay it, and the sixth check fails.

A token's life

After that, the token changes state as things happen around it. The events are few, and the wallet, the bank or the Token Service Provider can each start them:

  • Suspend. You report your phone lost. The token stops working at once. Your plastic card and its other tokens carry on as before.
  • Activate. You find the phone. The same token works again, with the same rules. Nothing has to be added again.
  • Update. The bank renews your card with a new expiry date and tells the vault. Every token on that card keeps working without you doing anything. This is why subscriptions now often survive a card renewal: the merchant was holding a token, and the token didn't change.
  • Unlink. The account is closed, the card number is no longer valid, fraud is found, or a merchant stops keeping your card on file. The link between token and card is cut, and every payment with that token is declined from then on.

The assurance method can change during the token's life as well. A token issued after a weak check can be upgraded later, once the cardholder passes a stronger one.

What I'd watch as an issuer

This is where the work lands on a bank, and where I think it's most often underestimated.

Lifecycle events have to flow out of your card system. The vault only knows what it's told. Renew a card and forget to send the new expiry, and the tokens on that card start failing quietly, often weeks later, when a subscription bounces or a tap is declined and nobody connects it to the reissue. Every card event that matters (renewal, replacement, block, closure) needs a matching message to each Token Service Provider holding tokens for that card.

Use the assurance method in your authorisation rules. A token issued at 00 and one issued at 14 look identical in a payment apart from that one field. Treating them the same throws away the best fraud signal tokenisation gives you.

Your customers will ask about tokens you never issued. "Why is my card on a phone I've never owned?" is a token question. Your support team needs to see which tokens exist on a card and which requestor holds each one, and to suspend a single token without blocking the card.

For the technical reader

The fields, as they're defined:

  • Token Requestor ID: 11 digits. Positions 1โ€“3 are the Token Service Provider's code, 4โ€“11 the requestor's. EMV tag 9F19 when a card or device carries it.
  • Token Assurance Method: 2 digits. 00 not performed; 01โ€“03 checks by someone other than the issuer (one-factor, two-factor, risk-based); 10โ€“14 checks by the issuer (account verification, one-factor, two-factor, risk-based, issuer-asserted); 20โ€“89 defined by each token programme.
  • Token Location: 2 digits. 01 a merchant's card-on-file store, 02 a secure element, 03 device storage such as HCE, 04 a trusted execution environment, 05 remote hardware storage, 06 shared storage such as a multi-merchant wallet, 07 temporary storage such as guest checkout.
  • PAR: 29 uppercase letters and digits, a 4-character BIN Controller Identifier then 25 characters. EMV tag 9F24; field 56 in 1987 ISO 8583. Blank or all zeros when there isn't one.
  • Last four digits of the PAN: EMV tag 9F25.

The script is a toy Token Service Provider. It registers two requestors (a phone wallet and a shop's card on file), issues tokens, then runs payments and lifecycle events through the vault's checks. This is the heart of it:

Python
def authorise(token, exp, mode, amount, merchant, crypto=None, counter=0):
    t = vault.get(token)
    if t is None:
        return "decline: not a token we know"
    if t["state"] != "active":
        return f"decline: token is {t['state']}"
    if exp != t["exp"]:
        return "decline: wrong token expiry"
    rq = REQUESTORS[t["trid"]]
    if mode not in rq["modes"]:
        return f"decline: entry mode {mode} isn't allowed for this token"
    if "merchant" in rq and merchant != rq["merchant"]:
        return "decline: token belongs to another merchant"
    if rq["cryptogram"]:
        if crypto is None or not hmac.compare_digest(crypto, cryptogram(token, amount, counter)):
            return "decline: token cryptogram missing or wrong"
        if (token, counter) in used:
            return "decline: cryptogram already used"
        used.add((token, counter))
    # De-tokenise: the bank gets the real card number and expiry, plus how the token was vetted.
    return f"to the bank: PAN ..{t['pan'][-4:]} exp {t['pan_exp']}, assurance {t['method']}"
The same in C#
C#
string Authorise(string token, string exp, string mode, int amount, string merchant, string? crypto = null, int counter = 0)
{
    if (!vault.TryGetValue(token, out var t))
        return "decline: not a token we know";
    if (t.State != "active")
        return $"decline: token is {t.State}";
    if (exp != t.Exp)
        return "decline: wrong token expiry";
    var rq = requestors[t.Trid];
    if (!rq.Modes.Contains(mode))
        return $"decline: entry mode {mode} isn't allowed for this token";
    if (rq.Merchant is not null && merchant != rq.Merchant)
        return "decline: token belongs to another merchant";
    if (rq.Cryptogram)
    {
        if (crypto is null || !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(crypto),
                                                                      Encoding.ASCII.GetBytes(Cryptogram(token, amount, counter))))
            return "decline: token cryptogram missing or wrong";
        if (!used.Add((token, counter)))
            return "decline: cryptogram already used";
    }
    // De-tokenise: the bank gets the real card number and expiry, plus how the token was vetted.
    return $"to the bank: PAN ..{t.Pan[^4..]} exp {t.PanExp}, assurance {t.Method}";
}

The full script, at the end of the post, prints:

Output
Asking for tokens
  phone wallet, approved in the bank app:   4900000000000011
  shop card-on-file, CVV checked:           4900000000000029
  fraudster's wallet, no checks, risky:     refused: no ID&V and a high risk score
  same PAR on both tokens:                  True
Paying
  tap with the phone:                       to the bank: PAN ..0010 exp 2808, assurance 14
  same tap replayed:                        decline: cryptogram already used
  phone token typed into a website:         decline: entry mode 01 isn't allowed for this token
  shop token used by its shop:              to the bank: PAN ..0010 exp 2808, assurance 10
  shop token used somewhere else:           decline: token belongs to another merchant
Living with it
  phone lost, token suspended, tap:         decline: token is suspended
  meanwhile the shop token:                 to the bank: PAN ..0010 exp 2808, assurance 10
  phone found, token activated, tap:        to the bank: PAN ..0010 exp 2808, assurance 14
  card renewed, same token, tap:            to the bank: PAN ..0010 exp 3108, assurance 14
  account closed, tokens unlinked, tap:     decline: token is unlinked

The line I'd point at is "card renewed". The phone sends the same token with the same expiry, 11/30, as before, and the bank now sees the card's new expiry, 08/31. Nobody touched the phone. The HMAC in the script stands in for the network's real token cryptogram, and the card number is a public Visa test card.

What's next

The cryptogram has come up in every part of this series: the card makes one, the phone makes one, and the vault refuses a token without a fresh one. Next in Behind the Tap: what's actually inside the cryptogram from a tap, how the key that makes it is derived for each card and each payment, and why changing a single digit of the amount breaks it.

If you work at an issuer that has gone live with tokens, I'd like to know which part of the lifecycle gave you the most trouble. Tell me in the comments.

The full scripts

Both run with nothing installed beyond Python 3.10 or .NET 10 (python3 token_vault.py, or dotnet run TokenVault.cs), and print the same output.

token_vault.py
Python
"""A toy Token Service Provider: issue tokens, authorise payments with them, and run one through its life.

Roles and fields follow the EMV Payment Tokenisation Technical Framework v2.4:
- Token Requestor ID: 11 digits, positions 1-3 the Token Service Provider's code, 4-11 the requestor's.
- Token Assurance Method: 2 digits, how the cardholder was checked (00 = not checked, 10 = issuer account
  verification such as the CVV, 14 = issuer-asserted, such as approval in the bank's own app).
- Token Location: 01 = a merchant's card-on-file store, 02 = a secure element.
- PAR (Payment Account Reference): 29 characters, a 4-character BIN Controller ID + 25 that can't be reversed.
- POS entry mode: 07 = contactless chip, 01 = typed in (ISO 8583 field 22, positions 1-2).
Everything else is made up: the card number is a public test PAN, the keys and ranges are invented, and the
HMAC stands in for the network's real token cryptogram.
"""
import hashlib
import hmac

TSP_CODE = "401"                  # positions 1-3 of every Token Requestor ID we hand out
TOKEN_RANGE = "490000"            # a token BIN range: looks like a card BIN, routes to the TSP
PAR_KEY = b"demo PAR key"         # the TSP's secret for PAR; PAR must not reveal the PAN
BIN_CONTROLLER = "Q001"           # made-up 4-character BIN Controller Identifier

def luhn_digit(digits: str) -> str:
    total = 0
    for i, d in enumerate(reversed(digits)):       # double every second digit, from the right
        n = int(d) * (2 if i % 2 == 0 else 1)
        total += n - 9 if n > 9 else n
    return str((10 - total % 10) % 10)

def mac(key: bytes, text: str) -> str:
    return hmac.new(key, text.encode(), hashlib.sha256).hexdigest().upper()

# Registered Token Requestors and the Token Domain Restriction Controls agreed with each.
REQUESTORS = {
    TSP_CODE + "00000001": {"name": "phone wallet", "location": "02", "modes": {"07"}, "cryptogram": True},
    TSP_CODE + "00000002": {"name": "shop card-on-file", "location": "01", "modes": {"01"},
                            "cryptogram": False, "merchant": "SHOP-0042"},
}

vault: dict[str, dict] = {}       # token -> its record
used: set[tuple[str, int]] = set()  # (token, counter) pairs already seen, to stop replays

def request_token(trid: str, pan: str, pan_exp: str, idv: str, risk: int) -> str:
    rq = REQUESTORS.get(trid)
    if rq is None:
        return "refused: not a registered Token Requestor"
    if idv == "none" and risk > 80:
        return "refused: no ID&V and a high risk score"
    method = {"none": "00", "cvv": "10", "bank app": "14"}[idv]
    body = TOKEN_RANGE + f"{len(vault) + 1:09d}"
    token = body + luhn_digit(body)
    par = BIN_CONTROLLER + mac(PAR_KEY, pan)[:25]   # the same for every token on this card
    vault[token] = {"pan": pan, "pan_exp": pan_exp, "exp": "3011", "trid": trid, "method": method,
                    "par": par, "state": "active", "key": token.encode()}
    return token

def cryptogram(token: str, amount: int, counter: int) -> str:
    return mac(vault[token]["key"], f"{token}|{amount}|{counter}")[:16]

def authorise(token: str, exp: str, mode: str, amount: int, merchant: str,
              crypto: str | None = None, counter: int = 0) -> str:
    t = vault.get(token)
    if t is None:
        return "decline: not a token we know"
    if t["state"] != "active":
        return f"decline: token is {t['state']}"
    if exp != t["exp"]:
        return "decline: wrong token expiry"
    rq = REQUESTORS[t["trid"]]
    if mode not in rq["modes"]:
        return f"decline: entry mode {mode} isn't allowed for this token"
    if "merchant" in rq and merchant != rq["merchant"]:
        return "decline: token belongs to another merchant"
    if rq["cryptogram"]:
        if crypto is None or not hmac.compare_digest(crypto, cryptogram(token, amount, counter)):
            return "decline: token cryptogram missing or wrong"
        if (token, counter) in used:
            return "decline: cryptogram already used"
        used.add((token, counter))
    # De-tokenise: the bank gets the real card number and expiry, plus how the token was vetted.
    return f"to the bank: PAN ..{t['pan'][-4:]} exp {t['pan_exp']}, assurance {t['method']}"

pan, pan_exp = "4761739001010010", "2808"           # a public Visa test card
wallet, shop = TSP_CODE + "00000001", TSP_CODE + "00000002"

print("Asking for tokens")
phone = request_token(wallet, pan, pan_exp, "bank app", risk=10)
print(f"  phone wallet, approved in the bank app:   {phone}")
on_file = request_token(shop, pan, pan_exp, "cvv", risk=20)
print(f"  shop card-on-file, CVV checked:           {on_file}")
print(f"  fraudster's wallet, no checks, risky:     {request_token(wallet, pan, pan_exp, 'none', risk=95)}")
print(f"  same PAR on both tokens:                  {vault[phone]['par'] == vault[on_file]['par']}")

print("Paying")
c1 = cryptogram(phone, 4_500, counter=1)
print(f"  tap with the phone:                       {authorise(phone, '3011', '07', 4_500, 'CAFE-7', c1, 1)}")
print(f"  same tap replayed:                        {authorise(phone, '3011', '07', 4_500, 'CAFE-7', c1, 1)}")
print(f"  phone token typed into a website:         {authorise(phone, '3011', '01', 4_500, 'WEB-99')}")
print(f"  shop token used by its shop:              {authorise(on_file, '3011', '01', 12_000, 'SHOP-0042')}")
print(f"  shop token used somewhere else:           {authorise(on_file, '3011', '01', 12_000, 'WEB-99')}")

print("Living with it")
vault[phone]["state"] = "suspended"                                      # phone reported lost
print(f"  phone lost, token suspended, tap:         {authorise(phone, '3011', '07', 900, 'CAFE-7', cryptogram(phone, 900, 2), 2)}")
print(f"  meanwhile the shop token:                 {authorise(on_file, '3011', '01', 12_000, 'SHOP-0042')}")
vault[phone]["state"] = "active"                                         # phone found
print(f"  phone found, token activated, tap:        {authorise(phone, '3011', '07', 900, 'CAFE-7', cryptogram(phone, 900, 3), 3)}")
for t in vault.values():                                                 # card renewed: new expiry
    t["pan_exp"] = "3108"
print(f"  card renewed, same token, tap:            {authorise(phone, '3011', '07', 900, 'CAFE-7', cryptogram(phone, 900, 4), 4)}")
for t in vault.values():                                                 # account closed
    t["state"] = "unlinked"
print(f"  account closed, tokens unlinked, tap:     {authorise(phone, '3011', '07', 900, 'CAFE-7', cryptogram(phone, 900, 5), 5)}")
TokenVault.cs
C#
// A toy Token Service Provider: issue tokens, authorise payments with them, and run one through its life.
// (.NET 10: dotnet run TokenVault.cs)
// Roles and fields follow the EMV Payment Tokenisation Technical Framework v2.4:
// - Token Requestor ID: 11 digits, positions 1-3 the Token Service Provider's code, 4-11 the requestor's.
// - Token Assurance Method: 2 digits, how the cardholder was checked (00 = not checked, 10 = issuer account
//   verification such as the CVV, 14 = issuer-asserted, such as approval in the bank's own app).
// - Token Location: 01 = a merchant's card-on-file store, 02 = a secure element.
// - PAR (Payment Account Reference): 29 characters, a 4-character BIN Controller ID + 25 that can't be reversed.
// - POS entry mode: 07 = contactless chip, 01 = typed in (ISO 8583 field 22, positions 1-2).
// Everything else is made up: the card number is a public test PAN, the keys and ranges are invented, and the
// HMAC stands in for the network's real token cryptogram.
using System.Security.Cryptography;
using System.Text;

const string TspCode = "401";               // positions 1-3 of every Token Requestor ID we hand out
const string TokenRange = "490000";         // a token BIN range: looks like a card BIN, routes to the TSP
byte[] parKey = "demo PAR key"u8.ToArray(); // the TSP's secret for PAR; PAR must not reveal the PAN
const string BinController = "Q001";        // made-up 4-character BIN Controller Identifier

// Registered Token Requestors and the Token Domain Restriction Controls agreed with each.
var requestors = new Dictionary<string, Requestor>
{
    [TspCode + "00000001"] = new("phone wallet", "02", ["07"], Cryptogram: true),
    [TspCode + "00000002"] = new("shop card-on-file", "01", ["01"], Cryptogram: false, Merchant: "SHOP-0042"),
};
var vault = new Dictionary<string, TokenRecord>();  // token -> its record
var used = new HashSet<(string, int)>();            // (token, counter) pairs already seen, to stop replays

string Mac(byte[] key, string text) => Convert.ToHexString(HMACSHA256.HashData(key, Encoding.UTF8.GetBytes(text)));

string RequestToken(string trid, string pan, string panExp, string idv, int risk)
{
    if (!requestors.ContainsKey(trid))
        return "refused: not a registered Token Requestor";
    if (idv == "none" && risk > 80)
        return "refused: no ID&V and a high risk score";
    string method = idv switch { "none" => "00", "cvv" => "10", _ => "14" };
    string body = TokenRange + (vault.Count + 1).ToString("D9");
    string token = body + LuhnDigit(body);
    string par = BinController + Mac(parKey, pan)[..25];   // the same for every token on this card
    vault[token] = new TokenRecord { Pan = pan, PanExp = panExp, Exp = "3011", Trid = trid, Method = method,
                                     Par = par, Key = Encoding.UTF8.GetBytes(token) };
    return token;
}

string Cryptogram(string token, int amount, int counter) => Mac(vault[token].Key, $"{token}|{amount}|{counter}")[..16];

string Authorise(string token, string exp, string mode, int amount, string merchant, string? crypto = null, int counter = 0)
{
    if (!vault.TryGetValue(token, out var t))
        return "decline: not a token we know";
    if (t.State != "active")
        return $"decline: token is {t.State}";
    if (exp != t.Exp)
        return "decline: wrong token expiry";
    var rq = requestors[t.Trid];
    if (!rq.Modes.Contains(mode))
        return $"decline: entry mode {mode} isn't allowed for this token";
    if (rq.Merchant is not null && merchant != rq.Merchant)
        return "decline: token belongs to another merchant";
    if (rq.Cryptogram)
    {
        if (crypto is null || !CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(crypto),
                                                                      Encoding.ASCII.GetBytes(Cryptogram(token, amount, counter))))
            return "decline: token cryptogram missing or wrong";
        if (!used.Add((token, counter)))
            return "decline: cryptogram already used";
    }
    // De-tokenise: the bank gets the real card number and expiry, plus how the token was vetted.
    return $"to the bank: PAN ..{t.Pan[^4..]} exp {t.PanExp}, assurance {t.Method}";
}

string pan = "4761739001010010", panExp = "2808";   // a public Visa test card
string wallet = TspCode + "00000001", shop = TspCode + "00000002";

Console.WriteLine("Asking for tokens");
string phone = RequestToken(wallet, pan, panExp, "bank app", risk: 10);
Console.WriteLine($"  phone wallet, approved in the bank app:   {phone}");
string onFile = RequestToken(shop, pan, panExp, "cvv", risk: 20);
Console.WriteLine($"  shop card-on-file, CVV checked:           {onFile}");
Console.WriteLine($"  fraudster's wallet, no checks, risky:     {RequestToken(wallet, pan, panExp, "none", risk: 95)}");
Console.WriteLine($"  same PAR on both tokens:                  {(vault[phone].Par == vault[onFile].Par ? "True" : "False")}");

Console.WriteLine("Paying");
string c1 = Cryptogram(phone, 4_500, 1);
Console.WriteLine($"  tap with the phone:                       {Authorise(phone, "3011", "07", 4_500, "CAFE-7", c1, 1)}");
Console.WriteLine($"  same tap replayed:                        {Authorise(phone, "3011", "07", 4_500, "CAFE-7", c1, 1)}");
Console.WriteLine($"  phone token typed into a website:         {Authorise(phone, "3011", "01", 4_500, "WEB-99")}");
Console.WriteLine($"  shop token used by its shop:              {Authorise(onFile, "3011", "01", 12_000, "SHOP-0042")}");
Console.WriteLine($"  shop token used somewhere else:           {Authorise(onFile, "3011", "01", 12_000, "WEB-99")}");

Console.WriteLine("Living with it");
vault[phone].State = "suspended";                                        // phone reported lost
Console.WriteLine($"  phone lost, token suspended, tap:         {Authorise(phone, "3011", "07", 900, "CAFE-7", Cryptogram(phone, 900, 2), 2)}");
Console.WriteLine($"  meanwhile the shop token:                 {Authorise(onFile, "3011", "01", 12_000, "SHOP-0042")}");
vault[phone].State = "active";                                           // phone found
Console.WriteLine($"  phone found, token activated, tap:        {Authorise(phone, "3011", "07", 900, "CAFE-7", Cryptogram(phone, 900, 3), 3)}");
foreach (var t in vault.Values) t.PanExp = "3108";                       // card renewed: new expiry
Console.WriteLine($"  card renewed, same token, tap:            {Authorise(phone, "3011", "07", 900, "CAFE-7", Cryptogram(phone, 900, 4), 4)}");
foreach (var t in vault.Values) t.State = "unlinked";                    // account closed
Console.WriteLine($"  account closed, tokens unlinked, tap:     {Authorise(phone, "3011", "07", 900, "CAFE-7", Cryptogram(phone, 900, 5), 5)}");

static string LuhnDigit(string digits)
{
    int total = 0;
    for (int i = 0; i < digits.Length; i++)               // double every second digit, from the right
    {
        int n = (digits[^(i + 1)] - '0') * (i % 2 == 0 ? 2 : 1);
        total += n > 9 ? n - 9 : n;
    }
    return ((10 - total % 10) % 10).ToString();
}

record Requestor(string Name, string Location, string[] Modes, bool Cryptogram, string? Merchant = null);

class TokenRecord
{
    public required string Pan, Exp, Trid, Method, Par;
    public required byte[] Key;
    public required string PanExp;
    public string State = "active";
}

Sources: the EMV Payment Tokenisation Specification Technical Framework v2.4, free from emvco.com, and ISO 8583 for the POS entry modes.