Mobile User

Phone Management

Set an initial phone number, replace it with OTP verification, or apply a phone change verified by your own backend.

Flow Summary

The current phone module has three flows:

Set Phone Flow

Step 1. Send OTP
POST /api/v2/auth/set-phone/otp

Step 2. Verify and save
POST /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)

Step 1. Register the change

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 sets is_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_code and phone_number are required. country_code is 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_id that 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_code is required on this step.
  • The new_phone_session_id must 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_id value as the OTP session UUID.
  • Resending is limited to once per minute for the same new_phone_session_id. When blocked, the response includes retry_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 phone and phone_code in 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

FactorCarried inProves
End-user sessionAuthorization: Bearer <access_token>Who the user is, and which agent they belong to
Agent signatureX-Agent-ID, X-Timestamp, X-Nonce, X-SignatureThe 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

HeaderRequiredRule
AuthorizationYesBearer <access_token> of the mobile user whose phone is changing.
Content-TypeYesapplication/json
X-Agent-IDYesYour agent UUID. Must be the same agent whose secret signs the request.
X-TimestampYesUnix time in seconds. Must be within ±60 seconds of server time.
X-NonceYes16–64 characters from [A-Za-z0-9._~-]. Single use per agent for 5 minutes.
X-SignatureYes64 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.

  1. Hash the raw request body:
body_hash = lowercase_hex( SHA-256( exact request body bytes ) )
  1. Build the canonical string. It has six lines joined with \n and 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).

  1. 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_hash and rejects the call with INVALID_SIGNATURE.
  • The htp.phone-change.v1 prefix 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 (201 for /request, 200 for /verification).
  • On error, the HTTP transport status is 200. Read the class from status_code and branch on error_code. Never branch on message; it is localized.
  • A missing, invalid, or expired bearer is rejected by the shared auth middleware with status_code 10201 (invalid) or 10200 (expired) and no error_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"
}
FieldWhat to send
new_phoneNational phone number as a string, without the dialing code; for example 91234567.
phone_codeInternational dialing code as a string; for example 65.
country_codeISO 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_id is an opaque UUID. It conveys no authorization on its own.
  • expires_at is an absolute Unix timestamp in seconds (created_at + 300). This differs from the set-phone and reset-phone responses, where expires_at is a relative duration.

Rules

  • Only one pending request may exist per user. A new /request by the same user supersedes the previous one and releases its reservation.
  • Only one user may reserve a given normalized new_phone / phone_code pair at a time. Another user requesting a reserved phone receives PHONE_CHANGE_IN_PROGRESS.
  • The cleaned new_phone and phone_code pair must not belong to another non-deleted account (PHONE_ALREADY_EXISTS).
  • PHONE_UNCHANGED is declared in the API error catalog but is not emitted by this implementation. Check for an unchanged number in your backend.

Errors

status_codeerror_codeWhenAction
400INVALID_REQUESTMalformed JSON, unknown field, body over 4 KiB, bad header formatFix the request
401INVALID_SIGNATUREMissing signature headers, signature mismatch, unknown agent, timestamp outside ±60 sCheck clock and signing
401REQUEST_REPLAYEDNonce already usedUse a fresh nonce
403AGENT_USER_MISMATCHSigning agent does not own the bearer's userWrong agent credentials
403USER_OR_AGENT_INACTIVEUser or agent is not activeStop
409PHONE_ALREADY_EXISTSAnother non-deleted account holds this phoneAsk for a different phone
409PHONE_CHANGE_IN_PROGRESSAnother user holds a live reservation on this phoneRetry after up to 5 minutes, or pick another phone
503SERVICE_UNAVAILABLERedis unavailable; replay protection cannot be guaranteedRetry with back-off
500(none)Unexpected failureRetry 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
}
FieldRule
request_idUUID returned by /request.
verification_id1–128 printable ASCII characters. Use a unique value per agent for each verification. Together with request_id, this is the business idempotency key.
verified_atUnix 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

  1. If the user has an active UQPAY cardholder, the payment provider's cardholder phone is updated first.
  2. In one local transaction: phone, phone_code, and country_code are updated, is_phone_verified is set to true, every other access/refresh token family for the user is revoked, and an audit record is written.
  3. The calling bearer token (and its refresh token, if any) remains valid. All other sessions for the user are logged out.
  4. 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_id and verification_id within 24 hours of success returns the identical 200 completed payload without repeating any work.
  • For transport retries, reuse the same request_id and verification_id but generate a fresh X-Timestamp, X-Nonce, and X-Signature. The nonce is a replay guard, not the idempotency key.
  • Any terminal failure (PROVIDER_UPDATE_FAILED, 500, or PHONE_ALREADY_EXISTS at verification) removes the request. Call /request again and repeat your own phone verification. There is no "failed but retryable" state.

Errors

status_codeerror_codeWhenAction
400INVALID_REQUESTMalformed body or fields; verified_at at or before request creation, or too far in the futureFix the request
401INVALID_SIGNATURE / REQUEST_REPLAYEDAs aboveAs above
403AGENT_USER_MISMATCHBearer user or signing agent does not match the pending requestWrong principal
403USER_OR_AGENT_INACTIVEUser or agent is not activeStop
404REQUEST_NOT_FOUNDUnknown request_id, or a request that expired or failed terminallyStart over
410REQUEST_EXPIREDRequest is past its 5-minute lifetimeStart over
410REQUEST_SUPERSEDEDA newer /request by this user replaced itVerify against the newer request_id
409ACCOUNT_STATE_CHANGEDThe user's current phone changed after /requestStart over
409VERIFICATION_TOO_OLDverified_at is older than 5 minutesRe-verify and start over
409REQUEST_ALREADY_CLAIMEDThe same verification_id is being processed right nowRetry the same IDs (fresh timestamp/nonce/signature) after about 1 second
409VERIFICATION_ID_CONFLICTRequest already claimed or completed with a different verification_idDo not retry; investigate
409PHONE_ALREADY_EXISTSTarget phone was taken between request and verification (locally or at the provider)Ask for a different phone
502PROVIDER_UPDATE_FAILEDPayment-provider phone update failedStart over
503SERVICE_UNAVAILABLERedis or session store unavailableRetry with back-off
500(none)Local update failed (possibly after the provider update succeeded)Start over; a new request converges

Decision table

error_codeAction
REQUEST_ALREADY_CLAIMED, SERVICE_UNAVAILABLE, 500 on /requestRetry 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 /verificationStart over: new /request, re-verify, new /verification
VERIFICATION_ID_CONFLICT, AGENT_USER_MISMATCH, USER_OR_AGENT_INACTIVEDo not retry; integration or configuration error
PHONE_ALREADY_EXISTS, PHONE_CHANGE_IN_PROGRESSAsk the user for a different phone (or wait up to 5 minutes for PHONE_CHANGE_IN_PROGRESS)
INVALID_REQUEST, INVALID_SIGNATURE, REQUEST_REPLAYEDFix 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 purpose
  • 403: resend requested too quickly, or reset session does not belong to the current user
  • 404: user not found
  • 409: new phone number already exists

Integration Notes

  1. Use set-phone only for users who still need to verify or attach a phone.
  2. Use reset-phone when replacing an already registered phone.
  3. The OTP steps here are route-specific and do not use /connect/token.
  4. Use the client-verified phone-change flow 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.
Copyright © 2026