Phone Management
Flow Summary
The current phone module has three flows:
Set Phone Flow
Step 1. Send OTPPOST /api/v2/auth/set-phone/otp
Step 2. Verify and savePOST /api/v2/auth/set-phone/verification
Replace Phone Flow
Step 1. Send OTP (current)POST /api/v2/auth/reset-phone/current-phone/otp
Step 2. Verify (current)POST /api/v2/auth/reset-phone/current-phone/verification
Step 3. Send OTP (new)POST /api/v2/auth/reset-phone/new-phone/otp
Step 4. Verify (new)POST /api/v2/auth/reset-phone/new-phone/verification
Client-Verified Phone Change Flow (Backend Only)
POST /api/v2/auth/phone-change/request
Step 2. Attest verification and apply
POST /api/v2/auth/phone-change/verification
All routes below should be treated as protected routes and sent with:
Authorization: Bearer <access_token>
The client-verified flow additionally requires the agent signature headers.
Set Phone (For Users Without A Verified Phone)
Use this when the user registered without a verified phone, or has a stored phone that is still unverified.
1. Send OTP
POST /api/v2/auth/set-phone/otp
Request
{
"phone_code": "65",
"country_code": "SG",
"phone_number": "91234567"
}
Success response
{
"status_code": 200,
"message": "OTP sent successfully",
"data": {
"set_phone_session_id": "9b7f1b4d-7c75-4d14-bec8-0d03b0f809d6",
"expires_at": 300
}
}
Current rules
- If the user already has a stored phone value, the submitted phone must match that stored phone exactly after normalization.
- If the user has no phone yet, the service validates the phone format and checks that the phone number is not already used by another user.
- The OTP session remains valid for 5 minutes.
- The response reuses the phone-reset OTP message key.
2. Verify OTP And Save Phone
POST /api/v2/auth/set-phone/verification
Request
{
"set_phone_session_id": "9b7f1b4d-7c75-4d14-bec8-0d03b0f809d6",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "Phone number updated successfully",
"data": {
"success": true,
"message": "Phone number set and verified successfully."
}
}
Notes
- The OTP session purpose must be
set_phone. - On success, the service updates
phone,phone_code,country_code, and setsis_phone_verified = true. - The OTP session is deleted after a successful verification.
Reset Phone (Replace An Existing Verified Phone)
This is a 4-step flow.
1. Send OTP To Current Phone
POST /api/v2/auth/reset-phone/current-phone/otp
Request
{
"phone_code": "65",
"country_code": "SG",
"phone_number": "91234567"
}
Success response
{
"status_code": 200,
"message": "Phone reset initiated successfully",
"data": {
"current_phone_session_id": "f2b4a8f8-0f5f-4a8d-9b20-8f2a1f4f34c2",
"phone": "6591234567",
"expires_at": 300
}
}
Notes
phone_codeandphone_numberare required.country_codeis optional here.- The submitted current phone must match the logged-in user’s registered phone.
- The service rate-limits this step to once per minute per user. If hit, it returns a failure payload with
retry_after. - The OTP session remains valid for 5 minutes.
2. Verify Current Phone OTP
POST /api/v2/auth/reset-phone/current-phone/verification
Request
{
"current_phone_session_id": "f2b4a8f8-0f5f-4a8d-9b20-8f2a1f4f34c2",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "Current phone verified successfully",
"data": {
"success": true,
"message": "Current phone verified successfully. You can now proceed to change phone number.",
"new_phone_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2"
}
}
Notes
- This consumes the OTP session from step 1.
- The service creates a
new_phone_session_idthat unlocks step 3. - That intermediate reset session remains valid for 10 minutes.
3. Send OTP To New Phone
POST /api/v2/auth/reset-phone/new-phone/otp
Request
{
"phone_code": "65",
"country_code": "SG",
"new_phone_number": "098765432",
"new_phone_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2"
}
Success response
{
"status_code": 200,
"message": "OTP sent successfully",
"data": {
"new_phone_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2",
"expires_at": 300
}
}
Notes
country_codeis required on this step.- The
new_phone_session_idmust come from step 2 and must belong to the current user. - The new phone number is validated and must not already exist.
- The OTP for the new phone uses the same
new_phone_session_idvalue as the OTP session UUID. - Resending is limited to once per minute for the same
new_phone_session_id. When blocked, the response includesretry_after.
4. Verify New Phone OTP And Update
POST /api/v2/auth/reset-phone/new-phone/verification
Request
{
"new_phone_session_id": "12dc8cb8-cdf5-4f1a-b5ec-c0fd7184bfe2",
"otp_code": "123456"
}
Success response
{
"status_code": 200,
"message": "OTP verified successfully",
"data": {
"success": true,
"message": "Phone number updated successfully."
}
}
Notes
- The OTP session purpose must be
reset_phone. - If the user has a
cardholder_id, the service updates the cardholder phone with the payment provider before saving the local phone. - The service updates
phoneandphone_codein the local database, then deletes the OTP session.
Client-Verified Phone Change (Backend To Backend)
Use this flow when your backend already verifies the user's new phone number (for example through your own SMS OTP system) and you want the mobile API to accept that verification instead of running the 4-step reset-phone flow.
Both endpoints are API v2 only. They are not available under /api/v1, and they do not use the key_version / salt / data encrypted envelope.
Trust model
| Factor | Carried in | Proves |
|---|---|---|
| End-user session | Authorization: Bearer <access_token> | Who the user is, and which agent they belong to |
| Agent signature | X-Agent-ID, X-Timestamp, X-Nonce, X-Signature | The call came from that agent's backend and the body was not tampered with |
Both factors are required on every call. The signing agent must be the agent that owns the bearer's user.
- A stolen bearer token alone cannot call these routes.
- A stolen agent secret alone cannot identify or authorize a user.
- The request body never carries a user identifier; the user comes from the bearer session.
- The mobile API trusts your backend's attestation that the new phone was verified. The signature proves origin and integrity of the request; it does not re-verify the phone.
The agent secret must stay on your server. Never ship it to a web frontend or mobile app.
Required headers
| Header | Required | Rule |
|---|---|---|
Authorization | Yes | Bearer <access_token> of the mobile user whose phone is changing. |
Content-Type | Yes | application/json |
X-Agent-ID | Yes | Your agent UUID. Must be the same agent whose secret signs the request. |
X-Timestamp | Yes | Unix time in seconds. Must be within ±60 seconds of server time. |
X-Nonce | Yes | 16–64 characters from [A-Za-z0-9._~-]. Single use per agent for 5 minutes. |
X-Signature | Yes | 64 lowercase hex characters. HMAC-SHA256 as described below. |
Additional request limits:
- Body must be at most 4096 bytes.
- Unknown JSON fields are rejected.
- Trailing content after the JSON object is rejected.
How the signature is generated
The signature covers the route, a timestamp, a nonce, and a hash of the exact bytes of the request body.
- Hash the raw request body:
body_hash = lowercase_hex( SHA-256( exact request body bytes ) )
- Build the canonical string. It has six lines joined with
\nand no trailing newline:
htp.phone-change.v1
POST
<path>
<X-Timestamp>
<X-Nonce>
<body_hash>
<path> is exactly /api/v2/auth/phone-change/request or /api/v2/auth/phone-change/verification (no host, no query string).
- Sign it with the agent secret:
X-Signature = lowercase_hex( HMAC-SHA256( key = agent_secret, message = UTF-8(canonical) ) )
Important details:
- Sign the bytes you send. Serialize the JSON body once, hash that string, and send that same string. If your HTTP client re-serializes the object (re-indents, reorders keys, escapes differently), the server computes a different
body_hashand rejects the call withINVALID_SIGNATURE. - The
htp.phone-change.v1prefix is fixed. It ensures a signature produced for another agent-secret protocol (for example/connect/token) can never be replayed against these routes. - The signature must be lowercase hex. Uppercase hex is rejected.
- Timestamp and nonce are part of the signed string, so a retry must be re-signed with a fresh timestamp and nonce.
The server verifies in this order: bearer → body size → header format → timestamp window → agent lookup → constant-time signature check → nonce registration (SET NX, 5 minutes) → agent/user binding → strict JSON decoding. A nonce is consumed only after the signature is valid, so a bad signature does not burn a nonce.
Signing examples
Each helper below takes the already-serialized body string and returns the value to place in X-Signature. Use the same string as the HTTP request body.
Node.js
const crypto = require("node:crypto");
function signPhoneChange({ agentSecret, path, timestamp, nonce, rawBody }) {
const bodyHash = crypto.createHash("sha256").update(rawBody, "utf8").digest("hex");
const canonical = [
"htp.phone-change.v1",
"POST",
path,
String(timestamp),
nonce,
bodyHash,
].join("\n");
return crypto.createHmac("sha256", agentSecret).update(canonical, "utf8").digest("hex");
}
async function requestPhoneChange({ baseUrl, accessToken, agentId, agentSecret, newPhone, phoneCode, countryCode }) {
const path = "/api/v2/auth/phone-change/request";
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString("hex"); // 32 chars, [0-9a-f]
const rawBody = JSON.stringify({ new_phone: newPhone, phone_code: phoneCode, country_code: countryCode }); // serialize once
const signature = signPhoneChange({ agentSecret, path, timestamp, nonce, rawBody });
const res = await fetch(baseUrl + path, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
"X-Agent-ID": agentId,
"X-Timestamp": String(timestamp),
"X-Nonce": nonce,
"X-Signature": signature,
},
body: rawBody, // send the exact string that was hashed
});
return res.json();
}
PHP
<?php
function signPhoneChange(string $agentSecret, string $path, int $timestamp, string $nonce, string $rawBody): string
{
$bodyHash = hash('sha256', $rawBody);
$canonical = implode("\n", [
'htp.phone-change.v1',
'POST',
$path,
(string) $timestamp,
$nonce,
$bodyHash,
]);
// hash_hmac(algo, data, key)
return hash_hmac('sha256', $canonical, $agentSecret);
}
function requestPhoneChange(string $baseUrl, string $accessToken, string $agentId, string $agentSecret, string $newPhone, string $phoneCode, string $countryCode): array
{
$path = '/api/v2/auth/phone-change/request';
$timestamp = time();
$nonce = bin2hex(random_bytes(16)); // 32 chars, [0-9a-f]
$rawBody = json_encode(['new_phone' => $newPhone, 'phone_code' => $phoneCode, 'country_code' => $countryCode], JSON_UNESCAPED_SLASHES); // serialize once
$signature = signPhoneChange($agentSecret, $path, $timestamp, $nonce, $rawBody);
$ch = curl_init($baseUrl . $path);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $rawBody, // send the exact string that was hashed
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $accessToken,
'X-Agent-ID: ' . $agentId,
'X-Timestamp: ' . $timestamp,
'X-Nonce: ' . $nonce,
'X-Signature: ' . $signature,
],
]);
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
Python
import hashlib
import hmac
import json
import secrets
import time
import requests
def sign_phone_change(agent_secret: str, path: str, timestamp: int, nonce: str, raw_body: bytes) -> str:
body_hash = hashlib.sha256(raw_body).hexdigest()
canonical = "\n".join([
"htp.phone-change.v1",
"POST",
path,
str(timestamp),
nonce,
body_hash,
])
return hmac.new(agent_secret.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256).hexdigest()
def request_phone_change(base_url: str, access_token: str, agent_id: str, agent_secret: str, new_phone: str, phone_code: str, country_code: str) -> dict:
path = "/api/v2/auth/phone-change/request"
timestamp = int(time.time())
nonce = secrets.token_hex(16) # 32 chars, [0-9a-f]
raw_body = json.dumps({"new_phone": new_phone, "phone_code": phone_code, "country_code": country_code}, separators=(",", ":")).encode("utf-8") # serialize once
signature = sign_phone_change(agent_secret, path, timestamp, nonce, raw_body)
res = requests.post(
base_url + path,
data=raw_body, # send the exact bytes that were hashed (do not use json=...)
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token}",
"X-Agent-ID": agent_id,
"X-Timestamp": str(timestamp),
"X-Nonce": nonce,
"X-Signature": signature,
},
)
return res.json()
Self-test vector
Use this vector to verify your signing helper before calling the API. The secret below is a test-only value; it is not a real agent secret.
agent_secret test-agent-secret-0123456789abcdef
path /api/v2/auth/phone-change/request
body {"new_phone":"91234567","phone_code":"65","country_code":"SG"}
X-Timestamp 1789410000
X-Nonce nonce-0123456789abcdef
body_hash 4f9c46337743f704cbbf7673f46494f5ef5ca63b005b36a963ef3022e064559e
X-Signature 1698bc796060faaabe288b591419945b5f7ca19e33e64dd4587db752522a25d1
The same payload with different formatting, { "new_phone": "91234567", "phone_code": "65", "country_code": "SG" }, must produce a different signature (39d0a9635eb5b9ae7247f32fefa24d3c4215fff0e4c306ce759a330741ef7b14). If your helper returns the same value for both bodies, it is hashing a re-serialized object rather than the transmitted bytes.
Response envelope and error codes
Both endpoints use the standard mobile-api envelope. On errors the envelope carries a stable error_code:
{
"trace_id": "…",
"status_code": 409,
"error_code": "PHONE_ALREADY_EXISTS",
"message": "…",
"data": null
}
- On success, the HTTP status equals
status_code(201for/request,200for/verification). - On error, the HTTP transport status is
200. Read the class fromstatus_codeand branch onerror_code. Never branch onmessage; it is localized. - A missing, invalid, or expired bearer is rejected by the shared auth middleware with
status_code10201(invalid) or10200(expired) and noerror_code. Treat both as "re-authenticate the user".
1. Register The Phone Change
POST /api/v2/auth/phone-change/request
Registers the user's intent to move to a new phone and reserves that phone for 5 minutes.
Request
{
"new_phone": "91234567",
"phone_code": "65",
"country_code": "SG"
}
| Field | What to send |
|---|---|
new_phone | National phone number as a string, without the dialing code; for example 91234567. |
phone_code | International dialing code as a string; for example 65. |
country_code | ISO country code; for example SG. |
Send all three fields. The server trims new_phone and removes one leading 0; it trims phone_code and removes one leading +. It stores country_code unchanged. This implementation does not perform phone-format or country-code validation, so validate these values in your backend before registering the change.
Success response
{
"status_code": 201,
"message": "Phone change request created.",
"data": {
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"expires_at": 1789410300
}
}
request_idis an opaque UUID. It conveys no authorization on its own.expires_atis an absolute Unix timestamp in seconds (created_at + 300). This differs from the set-phone and reset-phone responses, whereexpires_atis a relative duration.
Rules
- Only one pending request may exist per user. A new
/requestby the same user supersedes the previous one and releases its reservation. - Only one user may reserve a given normalized
new_phone/phone_codepair at a time. Another user requesting a reserved phone receivesPHONE_CHANGE_IN_PROGRESS. - The cleaned
new_phoneandphone_codepair must not belong to another non-deleted account (PHONE_ALREADY_EXISTS). PHONE_UNCHANGEDis declared in the API error catalog but is not emitted by this implementation. Check for an unchanged number in your backend.
Errors
status_code | error_code | When | Action |
|---|---|---|---|
400 | INVALID_REQUEST | Malformed JSON, unknown field, body over 4 KiB, bad header format | Fix the request |
401 | INVALID_SIGNATURE | Missing signature headers, signature mismatch, unknown agent, timestamp outside ±60 s | Check clock and signing |
401 | REQUEST_REPLAYED | Nonce already used | Use a fresh nonce |
403 | AGENT_USER_MISMATCH | Signing agent does not own the bearer's user | Wrong agent credentials |
403 | USER_OR_AGENT_INACTIVE | User or agent is not active | Stop |
409 | PHONE_ALREADY_EXISTS | Another non-deleted account holds this phone | Ask for a different phone |
409 | PHONE_CHANGE_IN_PROGRESS | Another user holds a live reservation on this phone | Retry after up to 5 minutes, or pick another phone |
503 | SERVICE_UNAVAILABLE | Redis unavailable; replay protection cannot be guaranteed | Retry with back-off |
500 | (none) | Unexpected failure | Retry later |
2. Attest Verification And Apply The Change
POST /api/v2/auth/phone-change/verification
Call this only after your backend has successfully verified the new phone number. The mobile API does not send, store, or validate your OTP.
Request
{
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"verification_id": "client-verification-12345",
"verified_at": 1789410200
}
| Field | Rule |
|---|---|
request_id | UUID returned by /request. |
verification_id | 1–128 printable ASCII characters. Use a unique value per agent for each verification. Together with request_id, this is the business idempotency key. |
verified_at | Unix seconds. Must be after the request was created, no more than 5 minutes old, and no more than 60 seconds in the future. |
new_phone, phone_code, and country_code are not accepted here. The server applies the phone that was reserved by /request.
Success response
{
"status_code": 200,
"message": "Phone address updated successfully.",
"data": {
"request_id": "7ee352c2-6ac6-4ef2-a275-71686d9788de",
"status": "completed"
}
}
Neither the old nor the new phone is returned. Refresh the user profile separately if you need it.
What happens on success
- If the user has an active UQPAY cardholder, the payment provider's cardholder phone is updated first.
- In one local transaction:
phone,phone_code, andcountry_codeare updated,is_phone_verifiedis set totrue, every other access/refresh token family for the user is revoked, and an audit record is written. - The calling bearer token (and its refresh token, if any) remains valid. All other sessions for the user are logged out.
- The completed response is cached for 24 hours for idempotent replay.
Idempotency and retries
The intended contract is described below. In implementation commit 200bb85e, the service passes the pending record's verification_id to the claim operation instead of the submitted value. This can prevent successful retries from matching the completed record. Confirm that this is corrected in your deployed API before relying on 24-hour idempotency.
- Resubmitting the same
request_idandverification_idwithin 24 hours of success returns the identical200 completedpayload without repeating any work. - For transport retries, reuse the same
request_idandverification_idbut generate a freshX-Timestamp,X-Nonce, andX-Signature. The nonce is a replay guard, not the idempotency key. - Any terminal failure (
PROVIDER_UPDATE_FAILED,500, orPHONE_ALREADY_EXISTSat verification) removes the request. Call/requestagain and repeat your own phone verification. There is no "failed but retryable" state.
Errors
status_code | error_code | When | Action |
|---|---|---|---|
400 | INVALID_REQUEST | Malformed body or fields; verified_at at or before request creation, or too far in the future | Fix the request |
401 | INVALID_SIGNATURE / REQUEST_REPLAYED | As above | As above |
403 | AGENT_USER_MISMATCH | Bearer user or signing agent does not match the pending request | Wrong principal |
403 | USER_OR_AGENT_INACTIVE | User or agent is not active | Stop |
404 | REQUEST_NOT_FOUND | Unknown request_id, or a request that expired or failed terminally | Start over |
410 | REQUEST_EXPIRED | Request is past its 5-minute lifetime | Start over |
410 | REQUEST_SUPERSEDED | A newer /request by this user replaced it | Verify against the newer request_id |
409 | ACCOUNT_STATE_CHANGED | The user's current phone changed after /request | Start over |
409 | VERIFICATION_TOO_OLD | verified_at is older than 5 minutes | Re-verify and start over |
409 | REQUEST_ALREADY_CLAIMED | The same verification_id is being processed right now | Retry the same IDs (fresh timestamp/nonce/signature) after about 1 second |
409 | VERIFICATION_ID_CONFLICT | Request already claimed or completed with a different verification_id | Do not retry; investigate |
409 | PHONE_ALREADY_EXISTS | Target phone was taken between request and verification (locally or at the provider) | Ask for a different phone |
502 | PROVIDER_UPDATE_FAILED | Payment-provider phone update failed | Start over |
503 | SERVICE_UNAVAILABLE | Redis or session store unavailable | Retry with back-off |
500 | (none) | Local update failed (possibly after the provider update succeeded) | Start over; a new request converges |
Decision table
error_code | Action |
|---|---|
REQUEST_ALREADY_CLAIMED, SERVICE_UNAVAILABLE, 500 on /request | Retry the same call with a fresh timestamp, nonce, and signature |
Success replay (status: completed) | Done |
REQUEST_NOT_FOUND, REQUEST_EXPIRED, REQUEST_SUPERSEDED, ACCOUNT_STATE_CHANGED, VERIFICATION_TOO_OLD, PROVIDER_UPDATE_FAILED, 500 on /verification | Start over: new /request, re-verify, new /verification |
VERIFICATION_ID_CONFLICT, AGENT_USER_MISMATCH, USER_OR_AGENT_INACTIVE | Do not retry; integration or configuration error |
PHONE_ALREADY_EXISTS, PHONE_CHANGE_IN_PROGRESS | Ask the user for a different phone (or wait up to 5 minutes for PHONE_CHANGE_IN_PROGRESS) |
INVALID_REQUEST, INVALID_SIGNATURE, REQUEST_REPLAYED | Fix the client: payload, clock, signing, or nonce generation |
Common Failure Cases
These apply to the set-phone and reset-phone flows. The client-verified flow uses the stable error_code values listed above.
400: invalid phone format, invalid OTP, expired session, or wrong session purpose403: resend requested too quickly, or reset session does not belong to the current user404: user not found409: new phone number already exists
Integration Notes
- Use
set-phoneonly for users who still need to verify or attach a phone. - Use
reset-phonewhen replacing an already registered phone. - The OTP steps here are route-specific and do not use
/connect/token. - Use the client-verified
phone-changeflow only from a trusted backend that holds the agent secret and performs its own phone verification. It requires both the user's bearer token and the agent signature headers.