# Protect a sensitive action (balance, history, payment): single-use link and PIN

_There is no secure action button or masked input in WhatsApp through /v1: send a single-use, short-lived link and have the PIN typed on your web page, never in the conversation._

Keywords: PIN, PIN code, password, sensitive data, balance, history, statement, confirm a payment, authentication, WhatsApp login, single-use link, magic link, token, TTL, expiry, CTA button, secure button, type a code in WhatsApp, brute force protection, secure

## Scenario

A customer writes "My balance" or "My last transactions". You do not want to show that data in a conversation on the sole strength of their number, and above all you do not want them to type their PIN in WhatsApp.

**What the API does not do:** `/v1` has no interactive action button (only reply buttons and lists, which send back text) and no masked input field. A code typed in the chat stays readable in the phone history, in backups, and by anyone who sees the screen.

**What works:** send a **single-use link** to **your** web page. The customer types their PIN there; your server checks it, then answers on WhatsApp. The PIN never travels through the conversation.

## Conversation

```text
Customer : My balance
Server   : known number (recognised by from) but not yet authenticated
You      : "For your security, open this link and enter your PIN (valid 15 min, single use)"
           https://app.example.com/l/plk_x7k2m9qa
Customer : (opens the page, types the PIN, submits)
Server   : token marked used, session opened for this number
You      : "Thanks Awa, your balance is 45,000 FCFA."
```

## Code

1. Your server builds a **random** token, stores it with the number and an expiry time, then sends the link. Within 24 h of the customer's message, it is free text:

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages/reply" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa"
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages/reply", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa"
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages/reply");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "text" => "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa",
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages/reply",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa",
    },
    timeout=15,
)
print(res.status_code, res.json())
```

1. If the conversation is closed (more than 24 h), send the same link in a [variable-link template](https://console.geskap.com/docs/lien-variable-bouton?lang=en): the "Open" button receives the token in `button_url_param`:

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "template": {
    "name": "ouvrir_espace_securise",
    "language": "fr",
    "variables": ["Awa"],
    "button_url_param": "plk_x7k2m9qa"
  },
  "idempotency_key": "lien-plk_x7k2m9qa"
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "template": {
      "name": "ouvrir_espace_securise",
      "language": "fr",
      "variables": ["Awa"],
      "button_url_param": "plk_x7k2m9qa"
    },
    "idempotency_key": "lien-plk_x7k2m9qa"
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "template" => [
      "name" => "ouvrir_espace_securise",
      "language" => "fr",
      "variables" => ["Awa"],
      "button_url_param" => "plk_x7k2m9qa",
    ],
    "idempotency_key" => "lien-plk_x7k2m9qa",
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "template": {
            "name": "ouvrir_espace_securise",
            "language": "fr",
            "variables": ["Awa"],
            "button_url_param": "plk_x7k2m9qa",
        },
        "idempotency_key": "lien-plk_x7k2m9qa",
    },
    timeout=15,
)
print(res.status_code, res.json())
```

1. On your page, apply the rules below, then answer the customer with `POST /v1/messages/reply`.

```js
// Node.js
// Your server — the PIN is checked on YOUR page, never in WhatsApp.
import crypto from "node:crypto";

export function createLoginLink(phone) {
  const token = "plk_" + crypto.randomBytes(24).toString("base64url"); // unguessable
  const expiresAt = Date.now() + 15 * 60_000;                          // short TTL
  db.linkTokens.insert({ token, phone, expiresAt, usedAt: null });
  return `https://app.example.com/l/${token}`;
}

export function submitPin(token, pin) {
  const link = db.linkTokens.get(token);
  if (!link || link.usedAt || link.expiresAt < Date.now()) return { status: 410 }; // expired or used
  if (tooManyAttempts(link.phone)) return { status: 429 };                          // e.g. 5 per 10 min
  if (!pinMatches(pin, db.customers.byPhone(link.phone).pinHash)) {
    recordFailure(link.phone);
    return { status: 401 };
  }
  db.linkTokens.update(token, { usedAt: Date.now() });                              // single use
  sendBalanceOnWhatsApp(link.phone);                                                // POST /v1/messages/reply
  return { status: 200 };
}
```

## Rules your page must apply

| Rule | Why |
|---|---|
| Long random token, never the number or a guessable identifier | a guessed link grants access |
| Short lifetime (15 min in the example) | a link left in the history expires |
| Single use: marked used as soon as the PIN is right | a forwarded link is useless |
| Limited attempts (5 in 10 min in the example), then refuse | stops PIN guessing |
| PIN stored hashed, never in clear | a database leak does not reveal the codes |
| WhatsApp answer only **after** server-side validation | the chat shows nothing before authentication |

> **Pitfall:** do not confuse the number with proof. `from` says which phone is writing ([Recognise a customer by their number](https://console.geskap.com/docs/reconnaitre-client-par-numero?lang=en)), not who holds it. The PIN on your page is what proves the person.

> **Pitfall:** `button_url_param` only takes the **end** of the link (200 characters, no spaces) and cannot change the domain. The token goes there; the domain stays that of your page approved by Meta.

> **Pitfall:** never send the PIN, a card code or a password **inside** a message, even a template. If you need a one-time code delivered over WhatsApp, read [Send a verification code (OTP)](https://console.geskap.com/docs/code-otp?lang=en) first.

This flow is the one in the CamaireTech WhatsApp demo (single-use link, PIN typed on the web page, limited attempts). That demo sends straight to Meta: it proves the conversation logic, not the `/v1` call.

_Proof — verified in the API source: api_schemas.py, public_api.py, templates.py ; applied by the WhatsApp demo: auth, config, engine._

---

# Protéger une action sensible (solde, historique, paiement) : lien unique et PIN

_Il n'y a pas de bouton d'action sécurisée ni de saisie masquée dans WhatsApp via /v1 : envoyez un lien à usage unique et de courte durée, et faites saisir le PIN sur votre page web, jamais dans la conversation._

Mots-clés: PIN, code PIN, mot de passe, données sensibles, solde, historique, relevé, confirmer un paiement, authentification, connexion WhatsApp, lien à usage unique, lien magique, magic link, token, TTL, expiration, bouton CTA, bouton sécurisé, saisir un code dans WhatsApp, anti brute force, sécuriser

## Scénario

Un client écrit « Mon solde » ou « Mes dernières opérations ». Vous ne voulez pas afficher ces données dans une conversation sur la seule foi de son numéro, et surtout vous ne voulez pas qu'il tape son PIN dans WhatsApp.

**Ce que l'API ne fait pas :** `/v1` n'a ni bouton d'action interactif (seulement des boutons de réponse et des listes, qui renvoient un texte) ni champ de saisie masqué. Un code tapé dans le chat reste lisible dans l'historique du téléphone, des sauvegardes et chez les contacts qui voient l'écran.

**Ce qui marche :** envoyer un **lien unique** vers **votre** page web. Le client y saisit son PIN ; votre serveur vérifie, puis lui répond sur WhatsApp. Le PIN ne transite jamais par la conversation.

## Conversation

```text
Client  : Mon solde
Serveur : numéro connu (reconnu par from) mais pas encore authentifié
Vous    : « Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) »
          https://app.example.com/l/plk_x7k2m9qa
Client  : (ouvre la page, saisit son PIN, valide)
Serveur : jeton marqué utilisé, session ouverte pour ce numéro
Vous    : « Merci Awa, votre solde est de 45 000 FCFA. »
```

## Code

1. Votre serveur fabrique un jeton **aléatoire**, l'enregistre avec le numéro et une heure d'expiration, puis envoie le lien. Dans les 24 h qui suivent le message du client, c'est du texte libre :

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages/reply" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa"
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages/reply", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa"
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages/reply");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "text" => "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa",
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages/reply",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "text": "Pour votre sécurité, ouvrez ce lien et saisissez votre PIN (valable 15 min, un seul usage) : https://app.example.com/l/plk_x7k2m9qa",
    },
    timeout=15,
)
print(res.status_code, res.json())
```

1. Si la conversation est fermée (plus de 24 h), envoyez le même lien dans un [template à lien variable](https://console.geskap.com/docs/lien-variable-bouton) : le bouton « Ouvrir » reçoit le jeton dans `button_url_param` :

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "template": {
    "name": "ouvrir_espace_securise",
    "language": "fr",
    "variables": ["Awa"],
    "button_url_param": "plk_x7k2m9qa"
  },
  "idempotency_key": "lien-plk_x7k2m9qa"
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "template": {
      "name": "ouvrir_espace_securise",
      "language": "fr",
      "variables": ["Awa"],
      "button_url_param": "plk_x7k2m9qa"
    },
    "idempotency_key": "lien-plk_x7k2m9qa"
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "template" => [
      "name" => "ouvrir_espace_securise",
      "language" => "fr",
      "variables" => ["Awa"],
      "button_url_param" => "plk_x7k2m9qa",
    ],
    "idempotency_key" => "lien-plk_x7k2m9qa",
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "template": {
            "name": "ouvrir_espace_securise",
            "language": "fr",
            "variables": ["Awa"],
            "button_url_param": "plk_x7k2m9qa",
        },
        "idempotency_key": "lien-plk_x7k2m9qa",
    },
    timeout=15,
)
print(res.status_code, res.json())
```

1. Sur votre page, appliquez les règles ci-dessous, puis répondez au client par `POST /v1/messages/reply`.

```js
// Node.js
// Your server — the PIN is checked on YOUR page, never in WhatsApp.
import crypto from "node:crypto";

export function createLoginLink(phone) {
  const token = "plk_" + crypto.randomBytes(24).toString("base64url"); // unguessable
  const expiresAt = Date.now() + 15 * 60_000;                          // short TTL
  db.linkTokens.insert({ token, phone, expiresAt, usedAt: null });
  return `https://app.example.com/l/${token}`;
}

export function submitPin(token, pin) {
  const link = db.linkTokens.get(token);
  if (!link || link.usedAt || link.expiresAt < Date.now()) return { status: 410 }; // expired or used
  if (tooManyAttempts(link.phone)) return { status: 429 };                          // e.g. 5 per 10 min
  if (!pinMatches(pin, db.customers.byPhone(link.phone).pinHash)) {
    recordFailure(link.phone);
    return { status: 401 };
  }
  db.linkTokens.update(token, { usedAt: Date.now() });                              // single use
  sendBalanceOnWhatsApp(link.phone);                                                // POST /v1/messages/reply
  return { status: 200 };
}
```

## Les règles que votre page doit appliquer

| Règle | Pourquoi |
|---|---|
| Jeton aléatoire long, jamais le numéro ni un identifiant devinable | un lien deviné donne accès |
| Durée de vie courte (15 min dans l'exemple) | un lien oublié dans l'historique expire |
| Usage unique : marqué utilisé dès que le PIN est correct | un lien transféré ne sert plus |
| Nombre d'essais limité (5 en 10 min dans l'exemple), puis refus | bloque la devinette de PIN |
| PIN stocké haché, jamais en clair | une fuite de base ne révèle pas les codes |
| Réponse WhatsApp uniquement **après** la validation côté serveur | le chat ne montre rien avant l'authentification |

> **Piège :** ne confondez pas le numéro et la preuve. `from` dit quel téléphone écrit ([Reconnaître un client à son numéro](https://console.geskap.com/docs/reconnaitre-client-par-numero)), pas qui le tient. Le PIN sur votre page est ce qui prouve la personne.

> **Piège :** `button_url_param` n'accepte que la **fin** du lien (200 caractères, sans espace) et ne peut pas changer de domaine. Le jeton va là ; le domaine reste celui de votre page approuvée par Meta.

> **Piège :** n'envoyez jamais le PIN, un code de carte ou un mot de passe **dans** un message, même en template. Si vous avez besoin d'un code à usage unique envoyé par WhatsApp, lisez d'abord [Envoyer un code de vérification (OTP)](https://console.geskap.com/docs/code-otp).

Ce parcours est celui de la démonstration WhatsApp de CamaireTech (lien à usage unique, PIN saisi sur la page web, essais limités). Cette démonstration envoie directement à Meta : elle prouve la logique de conversation, pas l'appel `/v1`.

_Preuve — vérifié dans le code de l'API : api_schemas.py, public_api.py, templates.py ; appliqué par la démo WhatsApp : auth, config, engine._

Support: WhatsApp +237 6 56 09 88 31 · All recipes: https://wa-api.geskap.com/llms.txt
