# OTP.ps — full developer documentation Source: https://otp.ps/docs. OpenAPI: https://otp.ps/openapi.json. --- # Quickstart > Send your first verification code and check it in five minutes, without sending a real message. OTP.ps sends one-time verification codes by text message to Palestinian mobile numbers on **Jawwal (059)** and **Ooredoo (056)**, in Arabic or English, starting with your business's name. Your server makes two calls: one to send a code, one to check what the customer typed. ## 1. Get a test key [Create an account](https://otp.ps/signup). You get a **test key** (`otp_test_…`) straight away, on the dashboard's **API keys** page. Test keys never send a message and never cost anything, and they work before your account is approved. Keep the key in an environment variable on your server: ```bash OTP_PS_API_KEY=otp_test_your_key_here ``` ## 2. Send a code `0599000001` is a [sandbox number](/docs/sandbox): with a test key, its code is always `1234`. ```bash curl https://otp.ps/api/v1/verify/send \ -H "Authorization: Bearer $OTP_PS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"phone": "0599000001", "purpose": "verify", "locale": "ar"}' ``` ```json { "id": "ver_9f2KxQe1Lm0aBcDe", "status": "pending", "to": "0599 ••• 001", "network": "jawwal", "purpose": "verify", "locale": "ar", "segments": 0, "attempts": 0, "test": true, "created_at": "2026-11-19T10:00:00.000Z", "expires_at": "2026-11-19T10:05:00.000Z", "verified_at": null, "test_code": "1234" } ``` Keep the `id` on your server (in the session or on the order). With a live key, the customer receives: > متجر نور: رمز التحقق 4821، صالح 5 دقائق، لا تشاركه. ## 3. Check the code ```bash curl https://otp.ps/api/v1/verify/check \ -H "Authorization: Bearer $OTP_PS_API_KEY" \ -H "Content-Type: application/json" \ -d '{"id": "ver_9f2KxQe1Lm0aBcDe", "code": "1234"}' ``` ```json { "valid": true, "attempts_left": 0, "status": "approved", "id": "ver_9f2KxQe1Lm0aBcDe", "…": "…" } ``` **Trust only `valid: true`.** It is true once, on the check that approved the code. ## 4. Go live When your integration works in the sandbox, OTP.ps approves your account and you top up your balance. Then create a **live key** (`otp_live_…`), put it in the same environment variable, and go through the [production checklist](/docs/production-checklist). ## Next - [Verification lifecycle](/docs/verification-lifecycle): statuses, expiry, tries, resending. - [Sandbox](/docs/sandbox): test numbers that simulate every outcome. - Examples: [Node.js](/docs/examples/nodejs), [Next.js](/docs/examples/nextjs), [PHP](/docs/examples/php), [Laravel](/docs/examples/laravel), [Python](/docs/examples/python), [WooCommerce](/docs/examples/woocommerce). - [API reference](/docs/api-reference) and the [OpenAPI document](/openapi.json). --- # Authentication > API keys, test and live mode, and where keys must (and must never) be kept. Every request carries an API key: ```http Authorization: Bearer otp_live_your_key_here ``` The `X-API-Key: ` header is accepted too. Keys are created and revoked on the dashboard (**API keys**). A key is shown once, when it is made; OTP.ps keeps only a hash of it. ## Two kinds of key | Key | Sends messages | Uses credit | Works before approval | Answer includes the code | |---|---|---|---|---| | `otp_test_…` (sandbox) | Never | Never | Yes | Yes, as `test_code` | | `otp_live_…` | Yes | Yes | No | Never | Test and live are completely separate: a verification made with a test key can't be checked or read with a live key, and the reverse. Limits are counted separately too. See [Sandbox](/docs/sandbox). ## Permissions and daily limits Each key has permissions (scopes), chosen when you create it: | Scope | Allows | |---|---| | `send` | `POST /api/v1/verify/send` | | `check` | `POST /api/v1/verify/check` | | `read` | `GET /api/v1/verify/{id}`, `/balance`, `/usage`, `/limits` | Give each key only what it needs: a reporting script needs `read` only. Without the needed scope the API answers `403 insufficient_scope`. Keys created before permissions existed have all three. A key can also have its own **daily message limit**, on top of the account's [spending limits](/docs/security#spending-limits): once reached, that key alone answers `429 spending_limit_reached` until the next day. `GET /api/v1/limits` shows a key's permissions and limits. ## Keep keys on the server - Put the key in an environment variable (`OTP_PS_API_KEY`) on your backend. Never commit it to Git; add your `.env` file to `.gitignore`. - **Never** put a key in browser JavaScript, a mobile app, a React/Vue/Next.js client component, or anything the customer downloads. The API sends no CORS headers, so a browser can't call it anyway. - Your website or app calls **your own** backend (for example `/api/otp/send`), and your backend calls OTP.ps. - Use separate keys per application, so one can be revoked without stopping the others. - If a key leaks, revoke it on the dashboard at once and create a new one. ## Errors A missing, malformed or revoked key answers `401 unauthorized`. A live key on an account that isn't approved yet answers `403 account_pending`. See [Errors](/docs/errors). --- # Verification lifecycle > What happens to a code from sending to approval, expiry or failure, and how resending works. ## Statuses ```text send │ ▼ ┌────────┐ right code ┌──────────┐ │pending │─────────────▶│ approved │ └────────┘ └──────────┘ time runs out │ │ 5 wrong tries a newer code to the same number ▼ ▼ │ ┌────────┐ ┌────────┐ ┌──────────┐ │expired │ │ failed │ │ canceled │ └────────┘ └────────┘ └──────────┘ ``` | Status | Meaning | What to show the customer | |---|---|---| | `pending` | Waiting for the code | The code box | | `approved` | The right code was checked | Continue | | `expired` | Not checked in time | "The code expired, ask for a new one" | | `failed` | 5 wrong tries, or the message couldn't be sent | "Ask for a new code" | | `canceled` | Replaced by a newer code to the same number | Use the newest code | ## Rules - **Code:** 4 digits, or 6 if you choose so in your settings. - **Valid for:** 5 minutes by default; you can choose 1 to 15 minutes in your settings. `expires_at` gives the exact time. - **Tries:** 5 checks per code, counted before the code is compared, so parallel guesses can't go past the limit. `attempts_left` tells you how many remain. - **Single use:** `valid: true` comes back once, on the check that approved the code. Later checks answer `valid: false` with status `approved`. This stops replays: always act on `valid`, never on `status` alone. - **One code per number at a time:** sending a new code to the same number cancels the previous one (per key mode). - **Customer input:** spaces and Arabic-Indic digits (`٤٨٢١`) are accepted in `code`. ## Resending There is no separate resend endpoint: **sending again is the resend**. Limits apply: per number: one code every 30 seconds, 5 an hour and 10 a day; per account: 120 codes a minute (test and live keys are counted separately). Show a countdown of 30 seconds after each send, and disable the button while a request is in flight so a double click can't send (and charge) twice. A `429 rate_limited` answer says how long to wait in `retry_after`. ## Checking by phone number Instead of `id`, `/verify/check` accepts `phone` and checks the **latest** code sent to that number with the same key mode. Prefer `id`: it can't pick up a different, newer code. ## Delivery OTP.ps hands the message to the gateway and knows whether it was **accepted** or refused (`502 sms_failed`, nothing charged). It does not receive delivery reports from the networks, so there is no "delivered" status. If a customer says they got nothing, let them resend after the cooldown and double-check the number. --- # Sandbox > Build and test the whole integration for free with test keys and sandbox numbers that simulate every outcome. The sandbox is **test keys** (`otp_test_…`). They use the same endpoints, requests and answers as live keys, so moving to production is just changing the key. With a test key: - No text message is ever sent, and no credit is ever used. - Every answer has `"test": true` and `"segments": 0`, and the send answer includes the code as `test_code`. - It works as soon as you sign up, before your account is approved. - Test verifications are separate from live ones: they never cancel a real customer's code, never use up live limits, and can't be read with a live key. ## Sandbox numbers Any valid Jawwal or Ooredoo number works with a test key and gets a random code. These numbers give predictable results, so you (or your AI coding assistant) can test every branch of your code: | Number | Network | With a test key | |---|---|---| | `0599000001` | Jawwal | Sent successfully. The code is always 1234 (or 123456 for 6-digit codes). | | `0569000001` | Ooredoo | Ooredoo number, sent successfully. The code is always 1234 (or 123456). | | `0599000002` | Jawwal | The gateway refuses the message: 502 sms_failed. Nothing is charged. | | `0599000003` | Jawwal | Answers 402 insufficient_balance, as if the account had no credit left. | | `0599000004` | Jawwal | Answers 429 rate_limited with retry_after 30, as if the number had just received a code. | | `0599000005` | Jawwal | Sent successfully with code 1234 (or 123456), but the code has already expired: checking it answers status expired. | Sandbox numbers are exempt from the per-number limits, so tests can reuse them freely; the per-account limit still applies. With a **live** key they are ordinary numbers. Other outcomes need no special number: - **Wrong code:** check any other code; `attempts_left` goes down and after 5 tries the status is `failed`. - **Invalid number:** `12345` answers `422 invalid_phone`; `0521234567` answers `422 unsupported_network`. - **Rate limit on a real number:** send twice to the same non-sandbox number within 30 seconds. - **Retries:** send twice with the same `Idempotency-Key`: the second answer is the first one again, with `Idempotent-Replayed: true`. ## A complete sandbox run ```bash title="examples/curl/sandbox-flow.sh" #!/usr/bin/env bash # The whole flow with a test key: no message is sent and nothing is charged. # OTP_PS_API_KEY=otp_test_… ./sandbox-flow.sh set -euo pipefail BASE="${OTP_PS_BASE_URL:-https://otp.ps}" AUTH="Authorization: Bearer ${OTP_PS_API_KEY:?Set OTP_PS_API_KEY to a test key}" # 1. Send a code to the sandbox number (its code is always 1234). SEND=$(curl -sS "$BASE/api/v1/verify/send" -H "$AUTH" -H "Content-Type: application/json" \ -H "Idempotency-Key: sandbox-$(date +%s)" \ -d '{"phone": "0599000001", "purpose": "verify", "locale": "en"}') echo "$SEND" ID=$(printf '%s' "$SEND" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p') # 2. A wrong code: valid is false, attempts_left goes down. curl -sS "$BASE/api/v1/verify/check" -H "$AUTH" -H "Content-Type: application/json" -d "{\"id\": \"$ID\", \"code\": \"0000\"}" echo # 3. The right code: valid is true. curl -sS "$BASE/api/v1/verify/check" -H "$AUTH" -H "Content-Type: application/json" -d "{\"id\": \"$ID\", \"code\": \"1234\"}" echo ``` ## What to test before going live 1. The right code passes, and your server marks the number verified. 2. A wrong code shows the tries left; the 5th wrong try asks for a new code. 3. `0599000005` (expired) asks for a new code. 4. `0599000002` (message refused) and `0599000003` (no balance) show a friendly error and alert your team for the latter. 5. `0599000004` (rate limited) shows a countdown using `retry_after`. 6. Double-clicking "Send" sends one code. 7. The browser never receives the API key, the verification `id` or the code. --- # Verification links > Confirm a number without building any screen: OTP.ps hosts the page, texts the link or a code, and tells you when the customer confirms. A verification link is a page OTP.ps hosts where your customer confirms the number **you** chose. Use it when you have no screen of your own to ask for a code: Shopify Flow, Zapier, Make, n8n, a WooCommerce block checkout, an order taken by phone, a thank-you page. ```text your system ──POST /api/v1/verify/links──▶ OTP.ps ──text message──▶ customer │ opens the link, confirms your system ◀── link.approved (webhook) ────────── OTP.ps ◀───────────┘ ``` ## Two ways to confirm | `delivery` | What happens | Messages charged | |---|---|---| | `sms` (default) | OTP.ps texts the link to the number. The customer opens it and presses **Confirm**. Receiving the link proves they have the phone | One, when the link is made | | `none` | You share the link yourself (redirect after checkout, email, chat). The page texts a code to the number and the customer types it. At most 3 codes per link | One per code the customer asks for | The text message for `sms` looks like this (one message, with your business's name): > متجر نور: لتأكيد طلبك افتح: https://otp.ps/v/Ab3dE5gH7jK9 The page shows your business's name, the masked number and nothing else: no OTP.ps menus, no sign-in. It speaks the link's `locale`. ## Create a link `POST /api/v1/verify/links` (scope `send`): ```bash curl https://otp.ps/api/v1/verify/links \ -H "Authorization: Bearer $OTP_PS_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042-link" \ -d '{"phone": "0599123456", "purpose": "order", "reference": "#1042", "delivery": "sms"}' ``` | Field | | Description | |---|---|---| | `phone` | required | A Jawwal or Ooredoo number. The customer can't change it on the page. | | `purpose` | optional | `verify`, `login`, `signup`, `order`, `appointment`. Changes the wording ("confirm your order"). | | `locale` | optional | `ar` or `en`. Defaults to your account's setting. | | `delivery` | optional | `sms` (default) or `none`, see above. | | `reference` | optional | Your own id, up to 100 characters, e.g. an order number. Comes back in every answer and webhook. | | `return_url` | optional | An https address. After confirming, the page sends the customer there with `otp_link=&otp_status=approved` added. | | `expires_in_minutes` | optional | 5 to 4320 (3 days). Default 1440 (24 hours). | The answer (`201`) is the link, plus `url`, the address to give the customer. **`url` is only in this answer**: OTP.ps keeps only a hash of it. An idempotent replay returns the link without `url`. ## Know when it's confirmed - **Webhook (recommended):** `link.approved` arrives within seconds. See [Webhooks](/docs/webhooks). - **Polling:** `GET /api/v1/verify/links/{id}`, or `GET /api/v1/verify/links?status=approved` for the latest confirmed links. - **Never** trust `otp_status=approved` in the return address on its own: anyone can type it. Check the link's status with the API or wait for the webhook. ## Statuses | Status | Meaning | Webhook | |---|---|---| | `pending` | Waiting for the customer | | | `approved` | Confirmed | `link.approved` | | `expired` | Not confirmed in time | `link.expired` | | `canceled` | You canceled it (`POST /api/v1/verify/links/{id}/cancel`) | `link.canceled` | ## Limits and safety - Everything that applies to codes applies to links: the per-number limits, your [spending limits](/docs/security#spending-limits), your balance, test and live separation, idempotency. - The link's secret part is 12 random characters. Pages can't be shown inside other sites, aren't indexed by search engines, and don't pass their address to other sites. - Confirming needs a button press: a link preview or a virus scanner that opens the link doesn't confirm it. - With a **test key**, no message is sent, the answer still has `url`, and a code page shows the code (`1234` on [sandbox numbers](/docs/sandbox)). --- # API reference > Every endpoint, field and answer of the OTP.ps REST API. Base address: `https://otp.ps`. All requests need an [API key](/docs/authentication). Bodies are JSON (form-encoded bodies are accepted too); answers are JSON. The machine-readable version of this page is the **[OpenAPI 3.1 document](/openapi.json)**, built from the same code as the API. ## Send a code `POST /api/v1/verify/send` | Field | Type | | Description | |---|---|---|---| | `phone` | string | required | A Jawwal (059) or Ooredoo (056) mobile, written any common way. See [Phone numbers](/docs/phone-numbers). | | `locale` | `"ar"` \| `"en"` | optional | Language of the message. Defaults to your account setting (Arabic for new accounts). | | `purpose` | string | optional | One of `verify`, `login`, `signup`, `order`, `appointment`. Only changes the wording. Default `verify`. | | Header | | Description | |---|---|---| | `Idempotency-Key` | optional | Up to 100 letters, digits or `- _ : .`. Retrying with the same key and request within 24 hours returns the first answer (with the header `Idempotent-Replayed: true`) instead of sending and charging again. The same key with a different request answers `409 idempotency_conflict`. Refusals that created nothing (validation, limits, balance) are not remembered, so they can be retried with the same key. | **Answer `201`:** the [verification](#the-verification-object), plus `test_code` with a test key. The message wording, by `purpose` (Arabic / English), after your business's name: | `purpose` | Arabic | English | |---|---|---| | `verify` | رمز التحقق 4821، صالح 5 دقائق، لا تشاركه. | Your verification code is 4821. Valid for 5 min. Don't share it. | | `login` | رمز الدخول … | Your login code is … | | `signup` | رمز تفعيل حسابك … | Your sign-up code is … | | `order` | رمز تأكيد طلبك … | Your order confirmation code is … | | `appointment` | رمز تأكيد موعدك … | Your appointment confirmation code is … | ## Check a code `POST /api/v1/verify/check` | Field | Type | | Description | |---|---|---|---| | `id` | string | one of `id` / `phone` | The verification id from the send answer. Preferred. | | `phone` | string | one of `id` / `phone` | Checks the latest code sent to this number with this key's mode. | | `code` | string | required | What the customer typed. Spaces and Arabic-Indic digits are fine. | **Answer `200`:** the verification plus: | Field | Type | Description | |---|---|---| | `valid` | boolean | `true` only on the check that approved the code. **Rely on this.** | | `attempts_left` | integer | Checks left for this code (0 once it is no longer pending). | A wrong code is still a `200` answer, with `valid: false`. ## Get a verification `GET /api/v1/verify/{id}`: **answer `200`:** the verification, or `404 not_found`. ## Get the balance `GET /api/v1/balance`: **answer `200`:** ```json { "credits": 1250, "status": "active", "mode": "live" } ``` `credits` is the number of text messages left; `status` is `pending` (waiting for approval), `active` or `suspended`; `mode` is the key's mode. ## Get usage `GET /api/v1/usage` (scope `read`): codes sent, approved and failed, and messages charged, for the key's mode, in Palestine time. ```json { "mode": "live", "timezone": "Asia/Hebron", "today": { "date": "2026-11-19", "sent": 42, "approved": 37, "failed": 0, "segments": 42 }, "month": { "month": "2026-11", "sent": 812, "approved": 701, "failed": 3, "segments": 812 }, "days": [{ "date": "2026-11-19", "sent": 42, "approved": 37, "failed": 0, "segments": 42 }] } ``` `days` has the last 30 days with any codes, newest first. ## Get limits `GET /api/v1/limits` (scope `read`): the key's permissions, the code settings, the rate limits, and the spending limits with what has been used today and this month. ```json { "mode": "live", "scopes": ["send", "check", "read"], "credits": 1250, "status": "active", "code": { "length": 4, "valid_minutes": 5, "max_attempts": 5 }, "rate_limits": { "per_phone": [{ "seconds": 30, "max": 1 }, { "seconds": 3600, "max": 5 }, { "seconds": 86400, "max": 10 }], "per_account_per_minute": 120 }, "spending": { "daily": { "limit": 300, "owner_cap": 500, "effective": 300, "used": 42 }, "monthly": { "limit": null, "used": 812 }, "key_daily": { "limit": null, "used": 40 }, "resets": { "day_in_seconds": 36000, "month_in_seconds": 986400 } } } ``` A `null` limit means there is none of that kind. See [spending limits](/docs/security#spending-limits). ## Verification links and webhooks | | Scope | | |---|---|---| | `POST /api/v1/verify/links` | send | Create a [verification link](/docs/verification-links) (`url` only in this answer) | | `GET /api/v1/verify/links` | read | List, newest first: `status`, `reference`, `limit` (1–100), `before` (a link id) | | `GET /api/v1/verify/links/{id}` | read | One link | | `POST /api/v1/verify/links/{id}/cancel` | send | Cancel a pending link (`409 invalid_state` otherwise) | | `POST /api/v1/webhooks`, `GET /api/v1/webhooks`, `DELETE /api/v1/webhooks/{id}` | read | [Webhook](/docs/webhooks) addresses | ## The verification object | Field | Type | Description | |---|---|---| | `id` | string | `ver_…` | | `status` | string | `pending`, `approved`, `expired`, `failed` or `canceled`. See [lifecycle](/docs/verification-lifecycle). | | `to` | string | The number, partly hidden: `0599 ••• 456`. | | `network` | string | `jawwal` or `ooredoo`. | | `purpose`, `locale` | string | As sent. | | `segments` | integer | Text messages charged (0 with a test key, and when the message couldn't be sent). | | `attempts` | integer | Checks made so far. | | `test` | boolean | Made with a test key. | | `created_at`, `expires_at` | string | ISO 8601, UTC. | | `verified_at` | string \| null | When it was approved. | ## Errors Errors answer an HTTP status of 400 or more with: ```json { "error": "rate_limited", "message": "Too many codes for this phone number. Try again later.", "retry_after": 27 } ``` The full list is on [Errors](/docs/errors). ## Limits per number: one code every 30 seconds, 5 an hour and 10 a day; per account: 120 codes a minute (test and live keys are counted separately). `5` checks per code. ## Billing A live send takes one credit per text message part: 70 characters in Arabic, 160 in English. The standard wording, with your name cut to 18 characters, always fits in one. A message the gateway refuses is not charged. Top-ups are done with OTP.ps; the balance is on the dashboard and at `GET /api/v1/balance`. ## Not available No delivery reports or webhooks yet, and no separate resend endpoint (send again). Their absence is deliberate, not an omission in this page. --- # Phone numbers > Which numbers OTP.ps sends to, the formats it accepts, and how to normalize them yourself. OTP.ps sends to **Palestinian mobile numbers on Jawwal (059) and Ooredoo (056)** only. It always sends on the Palestinian country code **+970**. ## Accepted formats The API reads every common way of writing a number. All of these are the same number, `+970599123456`: | Written as | Notes | |---|---| | `0599123456` | Local, 10 digits | | `599123456` | Without the leading 0 | | `+970599123456`, `00970599123456`, `970599123456` | Palestinian code | | `+972599123456`, `00972599123456` | The Israeli code, often used for the same Jawwal/Ooredoo numbers; sent on +970 | | `059-912-3456`, `+970 59 912 3456`, `(059) 912 3456` | Spaces, dashes and brackets are ignored | | `٠٥٩٩١٢٣٤٥٦` | Arabic-Indic digits (and Persian digits) | ## Refused numbers | Number | Error | |---|---| | Other mobiles, e.g. `052…`, `054…`, `050…` (Israeli operators) | `422 unsupported_network` | | Landlines (`02…`, `04…`, `08…`, `09…`), wrong length, letters | `422 invalid_phone` | ## Normalizing on your side You can send the number exactly as the customer typed it. If you want to validate it in your form first, or store it in one format, use the same rules as the API: take the digits, drop `00`, then a `970` or `972` prefix on a 12-digit number, then a leading `0` on a 10-digit number; what remains must be 9 digits starting with `59` or `56`. ```ts export function normalizePhone(raw: string): string | null { let d = raw .replace(/[٠-٩]/g, (c) => String(c.charCodeAt(0) - 0x0660)) .replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)) .replace(/\D/g, ""); if (d.startsWith("00")) d = d.slice(2); if (d.length === 12 && (d.startsWith("970") || d.startsWith("972"))) d = d.slice(3); if (d.length === 10 && d.startsWith("0")) d = d.slice(1); return /^5[96]\d{7}$/.test(d) ? `+970${d}` : null; } ``` The same function is in the [TypeScript example](/docs/examples/javascript-typescript) and the [WooCommerce plugin](/docs/examples/woocommerce) (PHP). ## In your form - Use `type="tel"`, `inputmode="tel"` and `autocomplete="tel"`, and `dir="ltr"` on the input even on an Arabic (RTL) page. - Placeholder: `059X XXX XXX`. - Tell the customer that only Jawwal and Ooredoo numbers can receive codes. - The API answers show the number masked (`0599 ••• 456`); keep the full number on your server. --- # Errors > Every error code the API can answer, what it means and what your integration should do. Every error has an HTTP status of 400 or more and this body: ```json { "error": "invalid_phone", "message": "The phone number is not a valid Palestinian mobile number." } ``` Switch on `error`, never on `message` (the wording may change). `rate_limited` also has `retry_after` (seconds) and a `Retry-After` header. | `error` | HTTP | Meaning | What to do | Retry? | |---|---|---|---|---| | `unauthorized` | 401 | The API key is missing, malformed, unknown or revoked. | Send `Authorization: Bearer ` with a key from the dashboard. Check the server's environment variable, not the code. | No | | `insufficient_scope` | 403 | This API key isn't allowed to do this (its permissions don't include send, check or read). | Use a key with the needed permission, or create one on the dashboard (API keys). | No | | `invalid_request` | 400 | The body isn't a JSON object, or a field is missing or has a value that isn't allowed. | Fix the request: `phone` is required on send; `locale` is `ar` or `en`; `purpose` is one of the listed purposes; check needs `code` and `id` or `phone`. | No | | `invalid_phone` | 422 | The number is not a valid Palestinian mobile number. | Ask the customer to correct the number. Accepted: 059XXXXXXX / 056XXXXXXX, with or without +970 / +972 / 00970. | No | | `unsupported_network` | 422 | The number is valid but not on Jawwal (059) or Ooredoo (056). | Tell the customer only Jawwal and Ooredoo numbers can receive codes. | No | | `idempotency_conflict` | 409 | This Idempotency-Key was already used with a different request. | Use a new key for every new send; reuse a key only to retry the exact same request. | No | | `invalid_state` | 409 | The verification link can't be changed any more: it is already approved, expired or canceled. | Read the link's status; create a new link if the customer still needs to confirm. | No | | `account_pending` | 403 | The account is waiting for approval, so live keys can't send yet. | Use a test key until OTP.ps approves the account. | No | | `account_suspended` | 403 | The account is suspended. | Contact OTP.ps support. | No | | `insufficient_balance` | 402 | Not enough credit left for this message. | Top up the balance. Show the customer a friendly 'try again later' message and alert your team. | No | | `rate_limited` | 429 | Too many codes for this number (or this account) in a short time. | Wait `retry_after` seconds (also in the Retry-After header). Show the customer a countdown before they can resend. | Yes, later | | `spending_limit_reached` | 429 | A spending limit is reached: the account's daily or monthly message limit, the daily ceiling set by OTP.ps, or this key's daily limit. | No more live codes until it resets (retry_after, in seconds). Alert your team; raise the limit on the dashboard (Settings) if it's expected. | Yes, later | | `sms_failed` | 502 | The text message gateway refused or couldn't take the message. Nothing was charged. | Let the customer try again in a moment. If it keeps happening, contact OTP.ps support. | Yes, later | | `not_found` | 404 | No verification with that id (or for that number) exists for this key's account and mode. | Check the id from the send answer, and that you check with a key of the same mode (test or live) that sent it. | No | A wrong code is **not** an error: `/verify/check` answers `200` with `valid: false` and `attempts_left`. ## Showing errors to customers Map codes to your own messages, in the customer's language; never show the raw `message`. For example: | `error` | Arabic | English | |---|---|---| | `invalid_phone` | رقم الجوال غير صحيح. | Please check the mobile number. | | `unsupported_network` | نرسل الرموز لأرقام جوال و Ooredoo فقط. | We can only send codes to Jawwal and Ooredoo numbers. | | `rate_limited` | انتظر قليلاً قبل طلب رمز جديد. | Please wait before asking for a new code. | | `sms_failed` | تعذّر إرسال الرسالة. حاول مرة أخرى. | We couldn't send the message. Please try again. | | anything else | تعذّر التحقق الآن. حاول لاحقاً. | Verification isn't available right now. | `unauthorized`, `insufficient_scope`, `account_pending`, `account_suspended`, `insufficient_balance` and `spending_limit_reached` are problems for **your team**, not the customer: log them and alert someone. ## Retrying - Retry only errors marked "Yes, later" above, and network failures. - For `/verify/send`, retry with the **same `Idempotency-Key`** so a request that actually went through isn't sent and charged twice. - Never retry automatically in a tight loop; respect `retry_after`. --- # Webhooks > Get told the moment a customer confirms a verification link, with signed messages, retries and a log. A webhook is an address on your system that OTP.ps posts to when something happens. Add one on the dashboard (**Webhooks**) or with the API. Each address belongs to one mode: it receives events of **live** links or of **test** links. ## Events | Type | When | |---|---| | `link.approved` | The customer confirmed a [verification link](/docs/verification-links) | | `link.expired` | A link wasn't confirmed in time | | `link.canceled` | You canceled a link | | `ping` | You pressed "Send test event" on the dashboard | The body (JSON): ```json { "id": "evt_9aB3cD4eF5gH6iJ7", "type": "link.approved", "created_at": "2026-11-19T10:03:00.000Z", "test": false, "data": { "id": "lnk_Xq3vB9kLm2Pz7RtY", "object": "link", "status": "approved", "to": "0599 ••• 456", "network": "jawwal", "purpose": "order", "locale": "ar", "delivery": "sms", "reference": "#1042", "return_url": null, "segments": 1, "test": false, "created_at": "2026-11-19T10:00:00.000Z", "expires_at": "2026-11-20T10:00:00.000Z", "opened_at": "2026-11-19T10:02:41.000Z", "approved_at": "2026-11-19T10:03:00.000Z" } } ``` Use `data.reference` to find your order. The full number is never sent; you already know it. ## Check the signature Every request carries `OTP-Signature: t=,v1=`, where the signature is the hex HMAC-SHA256 of `"."` with your address's secret (`whsec_…`, shown once when the address is made). Always check it, using the **raw** body (before parsing the JSON), and refuse anything older than 5 minutes. The [SDKs](/docs/sdks/javascript) do this for you (`verifyWebhook`, `OtpPs\Webhook::verify`). ```js title="examples/webhooks/verify-node.mjs" // Checking an OTP.ps webhook in Node.js (Express shown; any framework works). // Use the RAW body: parsing the JSON first changes the bytes and the signature won't match. // OTP_PS_WEBHOOK_SECRET=whsec_… (from the dashboard, or POST /api/v1/webhooks) import { createHmac, timingSafeEqual } from "node:crypto"; /** Returns the event, or throws when the signature is wrong or more than 5 minutes old. */ export function verifyOtpWebhook(rawBody, signatureHeader, secret = process.env.OTP_PS_WEBHOOK_SECRET) { const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(signatureHeader ?? ""); if (!m) throw new Error("Missing or malformed OTP-Signature"); if (Math.abs(Date.now() / 1000 - Number(m[1])) > 300) throw new Error("Webhook too old"); const expected = createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest(); if (!timingSafeEqual(expected, Buffer.from(m[2], "hex"))) throw new Error("Bad signature"); return JSON.parse(rawBody); } // Express: // app.post("/webhooks/otp", express.raw({ type: "application/json" }), (req, res) => { // let event; // try { event = verifyOtpWebhook(req.body.toString("utf8"), req.get("OTP-Signature")); } // catch { return res.sendStatus(400); } // if (event.type === "link.approved") markOrderConfirmed(event.data.reference); // your code // res.sendStatus(200); // answer fast; OTP.ps retries anything that isn't 2xx // }); ``` ```php title="examples/webhooks/verify-php.php" 300) { return null; } $expected = hash_hmac('sha256', $m[1] . '.' . $rawBody, $secret); return hash_equals($expected, $m[2]) ? json_decode($rawBody, true) : null; } // As a webhook endpoint (webhook.php): if (PHP_SAPI !== 'cli') { $event = verify_otp_webhook(file_get_contents('php://input'), $_SERVER['HTTP_OTP_SIGNATURE'] ?? '', getenv('OTP_PS_WEBHOOK_SECRET')); if ($event === null) { http_response_code(400); exit; } if ($event['type'] === 'link.approved') { // mark_order_confirmed($event['data']['reference']); // your code } http_response_code(200); } ``` ```python title="examples/webhooks/verify_python.py" """Checking an OTP.ps webhook in Python (Flask shown). Use the RAW body. OTP_PS_WEBHOOK_SECRET=whsec_... """ import hashlib import hmac import json import os import re import time def verify_otp_webhook(raw_body: bytes, signature_header: str, secret: str = None): """Returns the event, or raises ValueError when the signature is wrong or more than 5 minutes old.""" secret = secret or os.environ["OTP_PS_WEBHOOK_SECRET"] m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", signature_header or "") if not m: raise ValueError("Missing or malformed OTP-Signature") if abs(time.time() - int(m.group(1))) > 300: raise ValueError("Webhook too old") expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, m.group(2)): raise ValueError("Bad signature") return json.loads(raw_body) # Flask: # @app.post("/webhooks/otp") # def otp_webhook(): # try: # event = verify_otp_webhook(request.get_data(), request.headers.get("OTP-Signature", "")) # except ValueError: # return "", 400 # if event["type"] == "link.approved": # mark_order_confirmed(event["data"]["reference"]) # your code # return "", 200 ``` ## Answer quickly, handle repeats - Answer `2xx` within 8 seconds; do slow work afterwards. Anything else (including redirects, which are not followed) counts as a failure. - Failed deliveries are retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours, then given up. The dashboard shows every delivery and its last result. - The same event can arrive more than once. Use the event `id` (also in the `OTP-Event-Id` header) to ignore repeats. ## Manage addresses with the API For tools that subscribe themselves (Zapier, Make, n8n), with the `read` scope: | | | |---|---| | `POST /api/v1/webhooks` | `{ url, events?, description? }` → the address and its `secret` (once) | | `GET /api/v1/webhooks` | the key's mode's addresses (no secrets) | | `DELETE /api/v1/webhooks/{id}` | stop sending there | Addresses must be public `https://` addresses: private networks, `localhost` and IP addresses of internal networks are refused, and the address is checked again before every delivery. At most 10 addresses per account. --- # Cash-on-delivery order confirmation > Confirm the customer's number with a code before accepting a cash-on-delivery order, to cut fake orders and returns. Fake and mistyped numbers are the main cost of cash-on-delivery: the courier drives out and nobody answers. Confirming the number with a code before the order is accepted removes most of them. ## Two ways to do it | | Before placing the order | After placing the order | |---|---|---| | When | At checkout, before "Place order" | Right after the order is created | | How | The checkout asks for the code; the order can't be placed until it's confirmed | The order is created as "unconfirmed"; it ships only once the customer types the code (on the thank-you page or a link) | | Best for | Your own checkout, WooCommerce | Platforms where you can't change checkout (e.g. Shopify), orders taken by phone or chat | ## Before placing the order (recommended) 1. The customer fills in the checkout and chooses cash on delivery. 2. Your **server** sends a code with `purpose: "order"`, using an `Idempotency-Key` tied to the cart (e.g. `cart-8812-otp-1`), so a double click or a retry doesn't send twice. 3. Keep the verification `id` **and the normalized number** in the server-side session, never in a hidden form field. 4. The customer types the code; your server checks it. On `valid: true`, store the verified number in the session. 5. When the order is submitted, your server refuses it unless the order's phone **equals** the verified number in the session. This stops a customer from verifying one number and changing it afterwards. 6. Save on the order that the phone was verified (and when), so your team can see it. ```js // On "Place order", server side: if (order.paymentMethod === "cod" && normalizePhone(order.phone) !== session.verifiedPhone) { return refuse("Please confirm your mobile number first."); } ``` The [WooCommerce plugin](/docs/examples/woocommerce) is a complete implementation of this flow. ## After placing the order 1. Create the order with a status or tag like "awaiting phone confirmation" and don't ship it. 2. Send the code (`purpose: "order"`, `Idempotency-Key: order--otp-1`) and show a code box on the confirmation page. 3. On `valid: true`, mark the order confirmed. Orders still unconfirmed after a few hours can be cancelled or called by your team. ## Without your own screen: verification links If you can't add a code box anywhere (Shopify, an order taken by phone or chat, a no-code tool), create a [verification link](/docs/verification-links) when the order comes in: ```json POST /api/v1/verify/links { "phone": "0599123456", "purpose": "order", "reference": "#1042", "delivery": "sms" } ``` OTP.ps texts the customer "confirm your order" with a link; they open it and press Confirm. Your [webhook](/docs/webhooks) receives `link.approved` with `reference: "#1042"`, and you ship. If it expires (`link.expired`), call the customer or cancel the order. ## Good practice - Only ask for a code for cash-on-delivery (paid orders don't need it). - Use `locale` to match the shop's language. - Limit sends per cart and per visitor on your side (e.g. 3 codes per cart), on top of OTP.ps's limits. - If OTP.ps answers `insufficient_balance` or is unreachable, decide in advance: block COD, or accept the order as "unconfirmed" and alert your team. Don't silently skip the check. --- # Customer registration > Verify a new customer's mobile number while they create an account. 1. The sign-up form collects the number with the rest of the details. 2. Your server validates the details, then sends a code with `purpose: "signup"`. Create the account as **unverified**, or keep the sign-up data in the session until the number is confirmed. 3. Show a code box. Your server checks the code with the verification `id` from the session. 4. On `valid: true`, set `phone_verified_at` on the account. Use the number the **server** sent the code to, not one sent by the browser. ## Details that matter - **One account per number:** check that no other account owns the number *before* sending a code, so you don't pay to verify a number you'll refuse anyway. - **Unverified accounts:** decide what they can do (e.g. browse but not order), and remove ones that never verify. - **Changing the number later:** treat it as a new verification ([phone verification](/docs/guides/phone-verification)), and keep the old number until the new one is confirmed. - **Abuse:** sign-up forms are public. Add a CAPTCHA or a per-IP limit before the send, so bots can't make you pay for messages to random numbers. Code: [Next.js](/docs/examples/nextjs), [Laravel](/docs/examples/laravel), [Node.js](/docs/examples/nodejs), [Python](/docs/examples/python). --- # Passwordless login > Let customers sign in with their mobile number and a code instead of a password. 1. The customer types their number. Your server normalizes it and looks up the account. 2. **Send the code whether or not an account exists**, or answer the same way in both cases, so the form doesn't reveal which numbers are registered. (Sending only to known numbers saves money; then show the same "If this number has an account, we sent a code" message either way.) 3. Send with `purpose: "login"` and keep the `id` and the account id in the session. 4. On `valid: true`, start the session for **that** account. Rotate the session id when signing in. ## Security - Never accept a "verified" flag, a phone number or an account id from the browser at step 4: use only what your server stored at step 3. - OTP.ps allows 5 tries per code and limits codes per number (per number: one code every 30 seconds, 5 an hour and 10 a day; per account: 120 codes a minute (test and live keys are counted separately)). Also limit login attempts per account and per IP on your side. - Codes expire (5 minutes by default). Keep the login session short-lived until the code is checked. - A text message is a reasonable second factor for a shop, but not for high-value accounts on its own: offer something stronger for admins. --- # Phone number verification > Confirm that a number belongs to the customer, for example on their profile or before saving a delivery number. The general pattern behind every other guide: 1. **Send:** your server sends a code to the number (`purpose: "verify"`) and stores `{ id, number }` against the user or session. 2. **Check:** the customer types the code; your server checks it with the stored `id`. 3. **Record:** on `valid: true`, your server saves the stored number as verified, with the time. ## Where to keep the pending verification | Your app | Store `{ id, number }` in | |---|---| | Server-rendered site with sessions (PHP, Laravel, Django, Rails, Express) | The server-side session | | Next.js / serverless | A signed, httpOnly cookie (see the [Next.js example](/docs/examples/nextjs)) or your database | | Mobile app with an API | Your database, keyed by the user; the app only gets "code sent" | Never let the browser or app send back the number or the `id` at step 2: otherwise someone can verify one number and claim another. ## Changing a verified number Keep the old number active until the new one is verified, then switch. Notify the old number (by text or email) that it was replaced, if your business needs that level of protection. --- # Delivery confirmation > Have the customer give the courier a code at the door, to prove the order was handed to the right person. 1. When the courier is about to deliver (or when the order goes out), your server sends a code to the customer's verified number with `purpose: "order"`. Set your account's code validity to the maximum (15 minutes) if the courier needs time, or send the code when the courier arrives. 2. At the door, the customer reads the code to the courier. 3. The courier types it into **your** courier app or page, which calls your server; your server checks it with the stored verification `id` and marks the order delivered on `valid: true`. ## Notes - The courier app must never hold the OTP.ps key: it calls your backend, which calls OTP.ps. - If the customer didn't receive the code, the courier can request a new one after 30 seconds (each send cancels the previous code). - Codes expire. For deliveries later in the day, send the code on arrival, not at dispatch. - Record who checked the code (courier id) and when, for disputes. --- # Appointment confirmation > Confirm bookings for clinics, salons and service centres with a code, so slots aren't held by fake numbers. 1. The customer picks a slot and gives their number. Your server **holds** the slot for a few minutes and sends a code with `purpose: "appointment"`. 2. The customer types the code. On `valid: true`, your server confirms the booking; otherwise the hold expires and the slot is free again. The message reads, for example: "عيادة الأمل: رمز تأكيد موعدك 7305، صالح 5 دقائق، لا تشاركه." ## Notes - Make the hold slightly longer than the code's validity (5 minutes by default), so a customer typing the code at the last second still gets the slot. - Limit how many slots one number can hold at once. - For reminders the day before, use your own SMS or WhatsApp messages: OTP.ps sends verification codes only. --- # cURL > Every endpoint from the command line, and a complete sandbox run. ```bash export OTP_PS_API_KEY=otp_test_… # from the dashboard # Send curl https://otp.ps/api/v1/verify/send \ -H "Authorization: Bearer $OTP_PS_API_KEY" -H "Content-Type: application/json" \ -H "Idempotency-Key: order-1042-otp-1" \ -d '{"phone": "0599123456", "purpose": "order", "locale": "ar"}' # Check curl https://otp.ps/api/v1/verify/check \ -H "Authorization: Bearer $OTP_PS_API_KEY" -H "Content-Type: application/json" \ -d '{"id": "ver_…", "code": "4821"}' # Status and balance curl https://otp.ps/api/v1/verify/ver_… -H "Authorization: Bearer $OTP_PS_API_KEY" curl https://otp.ps/api/v1/balance -H "Authorization: Bearer $OTP_PS_API_KEY" ``` ## Complete sandbox run Tested against the API on every change. ```bash title="examples/curl/sandbox-flow.sh" #!/usr/bin/env bash # The whole flow with a test key: no message is sent and nothing is charged. # OTP_PS_API_KEY=otp_test_… ./sandbox-flow.sh set -euo pipefail BASE="${OTP_PS_BASE_URL:-https://otp.ps}" AUTH="Authorization: Bearer ${OTP_PS_API_KEY:?Set OTP_PS_API_KEY to a test key}" # 1. Send a code to the sandbox number (its code is always 1234). SEND=$(curl -sS "$BASE/api/v1/verify/send" -H "$AUTH" -H "Content-Type: application/json" \ -H "Idempotency-Key: sandbox-$(date +%s)" \ -d '{"phone": "0599000001", "purpose": "verify", "locale": "en"}') echo "$SEND" ID=$(printf '%s' "$SEND" | sed -n 's/.*"id":"\([^"]*\)".*/\1/p') # 2. A wrong code: valid is false, attempts_left goes down. curl -sS "$BASE/api/v1/verify/check" -H "$AUTH" -H "Content-Type: application/json" -d "{\"id\": \"$ID\", \"code\": \"0000\"}" echo # 3. The right code: valid is true. curl -sS "$BASE/api/v1/verify/check" -H "$AUTH" -H "Content-Type: application/json" -d "{\"id\": \"$ID\", \"code\": \"1234\"}" echo ``` --- # JavaScript and TypeScript > A typed, dependency-free OTP.ps client for any server-side TypeScript (Node.js, Bun, Deno, Next.js). A small client with typed answers, a typed error, a 15-second timeout and the same phone rules as the API. It is **server-side only** (`import "server-only"` makes Next.js refuse to bundle it for the browser; remove that line outside Next.js). ```ts title="examples/nextjs/lib/otp.ts" // OTP.ps client in TypeScript (server-side only: Next.js route handlers, server // actions, or any Node/Bun/Deno backend). Never import this from a client component. import "server-only"; export type OtpErrorCode = | "unauthorized" | "invalid_request" | "invalid_phone" | "unsupported_network" | "idempotency_conflict" | "account_pending" | "account_suspended" | "insufficient_balance" | "rate_limited" | "sms_failed" | "not_found"; export interface Verification { id: string; status: "pending" | "approved" | "expired" | "failed" | "canceled"; to: string; // masked, e.g. "0599 ••• 456" network: "jawwal" | "ooredoo"; purpose: "verify" | "login" | "signup" | "order" | "appointment"; locale: "ar" | "en"; segments: number; attempts: number; test: boolean; created_at: string; expires_at: string; verified_at: string | null; } export class OtpError extends Error { constructor( readonly status: number, readonly code: OtpErrorCode | "network_error", message: string, readonly retryAfter?: number, ) { super(message); this.name = "OtpError"; } } const BASE = (process.env.OTP_PS_BASE_URL ?? "https://otp.ps").replace(/\/$/, ""); async function call(method: "GET" | "POST", path: string, body?: unknown, headers: Record = {}): Promise { const key = process.env.OTP_PS_API_KEY; if (!key) throw new Error("OTP_PS_API_KEY is not set"); let res: Response; try { res = await fetch(`${BASE}/api/v1${path}`, { method, headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...headers }, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(15_000), cache: "no-store", }); } catch { throw new OtpError(0, "network_error", "OTP.ps could not be reached"); } const data = (await res.json().catch(() => null)) as { error?: OtpErrorCode; message?: string; retry_after?: number } | null; if (!res.ok) throw new OtpError(res.status, data?.error ?? "invalid_request", data?.message ?? `HTTP ${res.status}`, data?.retry_after); return data as T; } export function sendCode( phone: string, opts: { purpose?: Verification["purpose"]; locale?: "ar" | "en"; idempotencyKey?: string } = {}, ) { return call( "POST", "/verify/send", { phone, purpose: opts.purpose ?? "verify", ...(opts.locale ? { locale: opts.locale } : {}) }, opts.idempotencyKey ? { "Idempotency-Key": opts.idempotencyKey } : {}, ); } /** Trust only `valid === true`. */ export function checkCode(id: string, code: string) { return call("POST", "/verify/check", { id, code }); } export function getBalance() { return call<{ credits: number; status: "pending" | "active" | "suspended"; mode: "live" | "test" }>("GET", "/balance"); } /** Normalizes a Palestinian mobile number to +9705XXXXXXXX, or null. Same rules as the API. */ export function normalizePhone(raw: string): string | null { let d = raw .replace(/[٠-٩]/g, (c) => String(c.charCodeAt(0) - 0x0660)) .replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)) .replace(/\D/g, ""); if (d.startsWith("00")) d = d.slice(2); if (d.length === 12 && (d.startsWith("970") || d.startsWith("972"))) d = d.slice(3); if (d.length === 10 && d.startsWith("0")) d = d.slice(1); return /^5[96]\d{7}$/.test(d) ? `+970${d}` : null; } ``` Usage: ```ts import { checkCode, OtpError, sendCode } from "./lib/otp"; try { const v = await sendCode("0599123456", { purpose: "order", locale: "ar", idempotencyKey: `order-${orderId}-otp-1` }); // store v.id with the order / session } catch (e) { if (e instanceof OtpError && e.code === "rate_limited") { // tell the customer to wait e.retryAfter seconds } } const r = await checkCode(storedId, codeFromCustomer); if (r.valid) { // the number is verified } ``` An official `@otp-ps/sdk` package is planned; until then, copy this file. --- # Node.js > A plain Node.js client and an Express server with send and check endpoints. Both files are tested against the API's sandbox on every change. ## Client (no dependencies, Node 18+) ```js title="examples/nodejs/otp-client.mjs" // OTP.ps client for Node.js 18+ (no dependencies). Server-side only: // the API key comes from the environment and must never reach a browser. // // OTP_PS_API_KEY=otp_test_… (sandbox) or otp_live_… (real messages) // OTP_PS_BASE_URL=https://otp.ps (optional) export class OtpError extends Error { constructor(status, body) { super(body?.message ?? `OTP.ps answered HTTP ${status}`); this.name = "OtpError"; this.status = status; this.code = body?.error ?? "unknown"; // e.g. invalid_phone, rate_limited (see the errors reference) this.retryAfter = body?.retry_after; // seconds, for rate_limited } } function settings() { const key = process.env.OTP_PS_API_KEY; if (!key) throw new Error("OTP_PS_API_KEY is not set"); return { key, base: (process.env.OTP_PS_BASE_URL ?? "https://otp.ps").replace(/\/$/, "") }; } async function request(method, path, body, headers = {}) { const { key, base } = settings(); const res = await fetch(`${base}/api/v1${path}`, { method, headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json", ...headers }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(15_000), }); const data = await res.json().catch(() => null); if (!res.ok) throw new OtpError(res.status, data); return data; } /** * Sends a code. Returns { id, status, to, expires_at, … } (and test_code with a test key). * Pass an idempotencyKey (e.g. "order-1042-otp-1") to make retries safe: the same key * never sends or charges twice. */ export function sendCode(phone, { purpose = "verify", locale, idempotencyKey } = {}) { return request( "POST", "/verify/send", { phone, purpose, ...(locale ? { locale } : {}) }, idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}, ); } /** Checks the code the customer typed. Trust only `valid === true`. */ export function checkCode(id, code) { return request("POST", "/verify/check", { id, code: String(code) }); } export function getBalance() { return request("GET", "/balance"); } ``` ## Express endpoints Your page calls `POST /api/otp/send` with `{ phone }` and `POST /api/otp/check` with `{ code }`. The verification id and number stay on the server; the browser only learns that a code was sent. Pair it with the [React form](/docs/examples/react). ```js title="examples/nodejs/server.mjs" // Express example: phone verification endpoints for your own website or app. // The browser talks to these two routes; only this server talks to OTP.ps. // // npm install express // OTP_PS_API_KEY=otp_test_… node server.mjs import { randomUUID } from "node:crypto"; import express from "express"; import { checkCode, OtpError, sendCode } from "./otp-client.mjs"; export const app = express(); app.use(express.json()); // Pending verifications, by browser session. Use your real session store // (Redis, your database, express-session) in production. const pending = new Map(); // sessionId -> { id, phone, sentAt } const verifiedPhones = new Map(); // sessionId -> phone (server-side truth) function session(req, res) { let sid = /(?:^|;\s*)sid=([\w-]+)/.exec(req.headers.cookie ?? "")?.[1]; if (!sid) { sid = randomUUID(); res.cookie("sid", sid, { httpOnly: true, sameSite: "lax", secure: process.env.NODE_ENV === "production" }); } return sid; } // Your own limit per visitor, on top of OTP.ps's limits, so nobody can drain your balance. const hits = new Map(); function tooMany(key, max = 5, windowMs = 15 * 60_000) { const now = Date.now(); const list = (hits.get(key) ?? []).filter((t) => now - t < windowMs); hits.set(key, [...list, now]); return list.length >= max; } function fail(res, e) { if (e instanceof OtpError) { // Show the customer something useful, never the raw error. const message = { invalid_phone: "Please check the mobile number.", unsupported_network: "Only Jawwal and Ooredoo numbers can receive codes.", rate_limited: "Please wait before asking for a new code.", sms_failed: "We couldn't send the message. Please try again.", }[e.code] ?? "Verification is unavailable right now. Please try again later."; return res.status(e.status === 429 ? 429 : 400).json({ error: e.code, message, retryAfter: e.retryAfter }); } console.error("OTP.ps request failed:", e.message); // never log codes or keys return res.status(503).json({ error: "unavailable", message: "Verification is unavailable right now." }); } app.post("/api/otp/send", async (req, res) => { const sid = session(req, res); if (tooMany(`send:${sid}`) || tooMany(`ip:${req.ip}`, 20)) { return res.status(429).json({ error: "rate_limited", message: "Too many requests. Try again later." }); } try { const v = await sendCode(String(req.body?.phone ?? ""), { purpose: req.body?.purpose === "order" ? "order" : "verify", locale: req.body?.locale === "en" ? "en" : "ar", }); pending.set(sid, { id: v.id, phone: String(req.body.phone), sentAt: Date.now() }); // Don't send the verification id or test_code to the browser. res.json({ sent: true, to: v.to, expiresAt: v.expires_at }); } catch (e) { fail(res, e); } }); app.post("/api/otp/check", async (req, res) => { const sid = session(req, res); const p = pending.get(sid); if (!p) return res.status(400).json({ error: "no_code", message: "Ask for a code first." }); try { const r = await checkCode(p.id, String(req.body?.code ?? "")); if (r.valid) { pending.delete(sid); verifiedPhones.set(sid, p.phone); // mark the phone verified on the server, not in the browser return res.json({ verified: true }); } if (r.status !== "pending") pending.delete(sid); // expired, failed or replaced: a new code is needed res.status(400).json({ verified: false, status: r.status, attemptsLeft: r.attempts_left }); } catch (e) { fail(res, e); } }); export function verifiedPhoneFor(sid) { return verifiedPhones.get(sid) ?? null; } if (process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href) { app.listen(process.env.PORT ?? 3000, () => console.log("Listening")); } ``` --- # React > A bilingual (Arabic RTL / English) phone verification form with loading, errors, expiry and a resend countdown. The form calls **your** backend (`/api/otp/send`, `/api/otp/check`): the [Next.js](/docs/examples/nextjs), [Express](/docs/examples/nodejs), [Laravel](/docs/examples/laravel) or [Flask](/docs/examples/python) examples all provide those two routes. It never sees the API key, the verification id or the code. What it handles: - Arabic (right to left) or English, with the number and code inputs left to right. - `autocomplete="one-time-code"` and a numeric keyboard, so phones offer the code from the message. - A busy state that also stops double clicks (no duplicate, paid sends). - A 30-second resend countdown, and `retryAfter` from a rate-limit answer. - Wrong code (tries left), expired, too many tries, and unsupported numbers. ```tsx title="examples/react/OtpForm.tsx" "use client"; // A phone verification form for React (works as a Next.js client component). // It only talks to YOUR backend (/api/otp/send and /api/otp/check); the OTP.ps // key stays on the server. Arabic or English, right-to-left when Arabic. import { useEffect, useRef, useState } from "react"; type Lang = "ar" | "en"; type Step = "phone" | "code" | "done"; const TEXT = { ar: { phone: "رقم الجوال (جوال أو Ooredoo)", send: "أرسل الرمز", sending: "جارٍ الإرسال…", code: "رمز التحقق", sentTo: (to: string) => `أرسلنا رمزاً إلى ${to}`, verify: "تحقّق", checking: "جارٍ التحقق…", resend: "أعد إرسال الرمز", resendIn: (s: number) => `إعادة الإرسال بعد ${s} ث`, change: "غيّر الرقم", done: "تم التحقق من رقمك ✓", wrong: (left: number) => `الرمز غير صحيح. تبقّى ${left} محاولات.`, expired: "انتهت صلاحية الرمز. اطلب رمزاً جديداً.", failed: "محاولات كثيرة. اطلب رمزاً جديداً.", invalid_phone: "رقم الجوال غير صحيح.", unsupported_network: "نرسل الرموز لأرقام جوال و Ooredoo فقط.", rate_limited: "انتظر قليلاً قبل طلب رمز جديد.", generic: "تعذّر التحقق الآن. حاول مرة أخرى.", }, en: { phone: "Mobile number (Jawwal or Ooredoo)", send: "Send code", sending: "Sending…", code: "Verification code", sentTo: (to: string) => `We sent a code to ${to}`, verify: "Verify", checking: "Checking…", resend: "Resend code", resendIn: (s: number) => `Resend in ${s}s`, change: "Change number", done: "Your number is verified ✓", wrong: (left: number) => `Wrong code. ${left} tries left.`, expired: "The code expired. Ask for a new one.", failed: "Too many tries. Ask for a new code.", invalid_phone: "Please check the mobile number.", unsupported_network: "We can only send codes to Jawwal and Ooredoo numbers.", rate_limited: "Please wait a moment before asking for a new code.", generic: "Verification isn't available right now. Please try again.", }, }; const RESEND_SECONDS = 30; // OTP.ps allows one code per number every 30 seconds export function OtpForm({ lang = "ar", onVerified }: { lang?: Lang; onVerified?: () => void }) { const t = TEXT[lang]; const [step, setStep] = useState("phone"); const [phone, setPhone] = useState(""); const [code, setCode] = useState(""); const [to, setTo] = useState(""); const [busy, setBusy] = useState(false); // also blocks double clicks: no duplicate (paid) sends const [error, setError] = useState(null); const [wait, setWait] = useState(0); const codeInput = useRef(null); useEffect(() => { if (wait <= 0) return; const timer = setTimeout(() => setWait((w) => w - 1), 1000); return () => clearTimeout(timer); }, [wait]); async function post(path: string, body: unknown) { const res = await fetch(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); return { ok: res.ok, data: (await res.json().catch(() => ({}))) as Record }; } async function send() { if (busy || wait > 0) return; setBusy(true); setError(null); try { const { ok, data } = await post("/api/otp/send", { phone, locale: lang }); if (!ok) { setError((t as Record)[data.error] ?? t.generic); if (data.retryAfter) setWait(Number(data.retryAfter)); return; } setTo(data.to); setCode(""); setStep("code"); setWait(RESEND_SECONDS); setTimeout(() => codeInput.current?.focus(), 0); } catch { setError(t.generic); } finally { setBusy(false); } } async function verify() { if (busy || !code) return; setBusy(true); setError(null); try { const { ok, data } = await post("/api/otp/check", { code }); if (ok && data.verified) { setStep("done"); onVerified?.(); } else if (data.status === "expired" || data.status === "canceled" || data.error === "no_code") { setError(t.expired); } else if (data.status === "failed") { setError(t.failed); } else if (typeof data.attemptsLeft === "number") { setError(t.wrong(data.attemptsLeft)); } else { setError(t.generic); } } catch { setError(t.generic); } finally { setBusy(false); } } return (
{step === "phone" && (
{ e.preventDefault(); void send(); }} style={{ display: "grid", gap: 8 }}> setPhone(e.target.value)} />
)} {step === "code" && (
{ e.preventDefault(); void verify(); }} style={{ display: "grid", gap: 8 }}>

{t.sentTo(to)}

setCode(e.target.value.replace(/\s/g, ""))} />
)} {step === "done" &&

{t.done}

} {error &&

{error}

}
); } ``` ```tsx router.refresh()} /> ``` --- # Next.js > App Router route handlers that send and check codes, with the pending verification in a signed cookie. Files (App Router): ```text lib/otp.ts the OTP.ps client (server-only) lib/otp-session.ts signs the pending verification into an httpOnly cookie app/api/otp/send/route.ts POST { phone, locale } app/api/otp/check/route.ts POST { code } components/OtpForm.tsx the React form ``` Environment (`.env.local`, never committed): ```bash OTP_PS_API_KEY=otp_test_… OTP_SESSION_SECRET= # 32+ random characters ``` The route handlers are tested against the API's sandbox on every change, including a tampered cookie being refused. ```ts title="examples/nextjs/lib/otp-session.ts" // Remembers, in a signed httpOnly cookie, which verification this browser is // waiting for and which number it was sent to. Signed, so the browser can't // swap in another number; the verification id never reaches page code. import "server-only"; import { createHmac, timingSafeEqual } from "node:crypto"; export const COOKIE = "otp_pending"; export interface Pending { id: string; // OTP.ps verification id phone: string; // normalized number the code was sent to exp: number; // unix seconds } function secret(): string { const s = process.env.OTP_SESSION_SECRET; if (!s || s.length < 32) throw new Error("OTP_SESSION_SECRET must be set (32+ random characters)"); return s; } const sign = (data: string) => createHmac("sha256", secret()).update(data).digest("base64url"); export function seal(p: Pending): string { const data = Buffer.from(JSON.stringify(p)).toString("base64url"); return `${data}.${sign(data)}`; } export function unseal(value: string | undefined): Pending | null { if (!value) return null; const [data, sig] = value.split("."); if (!data || !sig) return null; const a = Buffer.from(sig); const b = Buffer.from(sign(data)); if (a.length !== b.length || !timingSafeEqual(a, b)) return null; const p = JSON.parse(Buffer.from(data, "base64url").toString()) as Pending; return p.exp * 1000 > Date.now() ? p : null; } ``` ```ts title="examples/nextjs/app/api/otp/send/route.ts" // POST /api/otp/send { phone, locale? } — called by the OtpForm component. import { NextResponse, type NextRequest } from "next/server"; import { normalizePhone, OtpError, sendCode } from "../../../../lib/otp"; import { COOKIE, seal } from "../../../../lib/otp-session"; export async function POST(req: NextRequest) { const body = (await req.json().catch(() => ({}))) as { phone?: string; locale?: string }; const locale = body.locale === "en" ? "en" : "ar"; const phone = normalizePhone(String(body.phone ?? "")); if (!phone) { return NextResponse.json( { error: "invalid_phone", message: locale === "ar" ? "رقم الجوال غير صحيح." : "Please check the mobile number." }, { status: 400 }, ); } // Add your own per-IP / per-user limit here (or a CAPTCHA on public forms). try { const v = await sendCode(phone, { purpose: "verify", locale }); const res = NextResponse.json({ sent: true, to: v.to, expiresAt: v.expires_at }); res.cookies.set(COOKIE, seal({ id: v.id, phone, exp: Math.floor(Date.parse(v.expires_at) / 1000) + 60 }), { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/", maxAge: 20 * 60, }); return res; } catch (e) { if (e instanceof OtpError) { return NextResponse.json( { error: e.code, retryAfter: e.retryAfter }, { status: e.code === "rate_limited" ? 429 : e.status >= 500 || e.status === 0 ? 503 : 400 }, ); } throw e; } } ``` ```ts title="examples/nextjs/app/api/otp/check/route.ts" // POST /api/otp/check { code } — the verification id comes from the signed cookie, not the browser. import { NextResponse, type NextRequest } from "next/server"; import { checkCode, OtpError } from "../../../../lib/otp"; import { COOKIE, unseal } from "../../../../lib/otp-session"; export async function POST(req: NextRequest) { const pending = unseal(req.cookies.get(COOKIE)?.value); if (!pending) return NextResponse.json({ error: "no_code" }, { status: 400 }); const { code } = (await req.json().catch(() => ({}))) as { code?: string }; try { const r = await checkCode(pending.id, String(code ?? "")); if (r.valid) { const res = NextResponse.json({ verified: true }); res.cookies.delete(COOKIE); // The number is verified: save `pending.phone` on the user or order HERE, on the server. return res; } const res = NextResponse.json({ verified: false, status: r.status, attemptsLeft: r.attempts_left }, { status: 400 }); if (r.status !== "pending") res.cookies.delete(COOKIE); // expired, failed or replaced: ask for a new code return res; } catch (e) { if (e instanceof OtpError) return NextResponse.json({ error: e.code }, { status: e.status === 404 ? 400 : 503 }); throw e; } } ``` The client (`lib/otp.ts`) is on the [JavaScript and TypeScript](/docs/examples/javascript-typescript) page, and the form on the [React](/docs/examples/react) page. Where the comment says *save `pending.phone`*, write the verified number to your user or order in your database. Don't trust anything the browser sends about the number after this point. --- # PHP > A PHP client (curl), a command-line sandbox demo, and session-based endpoints for a website form. PHP 7.4+, the curl extension. The client and the demo are tested against the API's sandbox on every change. ## Client ```php title="examples/php/OtpPs.php" status = $status; $this->errorCode = $body['error'] ?? 'unknown'; $this->retryAfter = $body['retry_after'] ?? null; } } class OtpPs { private $key; private $base; public function __construct(?string $apiKey = null, ?string $baseUrl = null) { $this->key = $apiKey ?? getenv('OTP_PS_API_KEY'); $this->base = rtrim($baseUrl ?? (getenv('OTP_PS_BASE_URL') ?: 'https://otp.ps'), '/'); if (!$this->key) { throw new RuntimeException('OTP_PS_API_KEY is not set'); } } /** Sends a code. Returns the verification (with test_code when using a test key). */ public function sendCode(string $phone, string $purpose = 'verify', ?string $locale = null, ?string $idempotencyKey = null): array { $body = ['phone' => $phone, 'purpose' => $purpose]; if ($locale) { $body['locale'] = $locale; } return $this->request('POST', '/verify/send', $body, $idempotencyKey ? ["Idempotency-Key: $idempotencyKey"] : []); } /** Checks what the customer typed. Trust only $result['valid'] === true. */ public function checkCode(string $id, string $code): array { return $this->request('POST', '/verify/check', ['id' => $id, 'code' => $code]); } public function balance(): array { return $this->request('GET', '/balance'); } private function request(string $method, string $path, ?array $body = null, array $headers = []): array { $ch = curl_init($this->base . '/api/v1' . $path); curl_setopt_array($ch, [ CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => array_merge(['Authorization: Bearer ' . $this->key, 'Content-Type: application/json'], $headers), ]); if ($body !== null) { curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); } $raw = curl_exec($ch); if ($raw === false) { $error = curl_error($ch); curl_close($ch); throw new RuntimeException("OTP.ps could not be reached: $error"); } $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); $data = json_decode($raw, true); if ($status >= 400) { throw new OtpPsException($status, is_array($data) ? $data : null); } return $data; } } ``` ## Sandbox demo ```bash OTP_PS_API_KEY=otp_test_… php demo.php ``` ```php title="examples/php/demo.php" sendCode('0599000001', 'verify', 'en', 'php-demo-' . bin2hex(random_bytes(4))); echo "Sent {$sent['id']} to {$sent['to']} (status {$sent['status']})\n"; $wrong = $otp->checkCode($sent['id'], '0000'); echo 'Wrong code: valid=' . var_export($wrong['valid'], true) . ", attempts_left={$wrong['attempts_left']}\n"; $right = $otp->checkCode($sent['id'], '1234'); // the sandbox number's fixed code echo 'Right code: valid=' . var_export($right['valid'], true) . ", status={$right['status']}\n"; try { $otp->sendCode('0521234567'); } catch (OtpPsException $e) { echo "Israeli number refused: {$e->errorCode}\n"; } ``` ## Endpoints for a form ```php title="examples/php/endpoints.php" $t > time() - 900); if (count($_SESSION['otp_sends']) >= 5) { reply(429, ['error' => 'rate_limited']); } $_SESSION['otp_sends'][] = time(); try { $v = $otp->sendCode((string)($_POST['phone'] ?? ''), 'verify', ($_POST['locale'] ?? 'ar') === 'en' ? 'en' : 'ar'); $_SESSION['otp_pending'] = ['id' => $v['id'], 'phone' => (string)$_POST['phone']]; reply(200, ['sent' => true, 'to' => $v['to'], 'expiresAt' => $v['expires_at']]); } catch (OtpPsException $e) { reply($e->status === 429 ? 429 : 400, ['error' => $e->errorCode, 'retryAfter' => $e->retryAfter]); } } if ($action === 'check') { $pending = $_SESSION['otp_pending'] ?? null; if (!$pending) { reply(400, ['error' => 'no_code']); } try { $r = $otp->checkCode($pending['id'], (string)($_POST['code'] ?? '')); } catch (OtpPsException $e) { reply(400, ['error' => $e->errorCode]); } if ($r['valid'] === true) { unset($_SESSION['otp_pending']); $_SESSION['verified_phone'] = $pending['phone']; // trust this, set on the server reply(200, ['verified' => true]); } if ($r['status'] !== 'pending') { unset($_SESSION['otp_pending']); } reply(400, ['verified' => false, 'status' => $r['status'], 'attemptsLeft' => $r['attempts_left']]); } reply(404, ['error' => 'unknown_action']); ``` --- # Laravel > A Laravel service using the HTTP client, a controller, routes with throttling, and configuration. `.env`: ```bash OTP_PS_API_KEY=otp_test_… OTP_PS_BASE_URL=https://otp.ps ``` ```php title="examples/laravel/config/services.php" [ 'key' => env('OTP_PS_API_KEY'), 'url' => env('OTP_PS_BASE_URL', 'https://otp.ps'), ], ]; ``` ```php title="examples/laravel/app/Services/OtpPs.php" withToken(config('services.otp_ps.key')) ->acceptJson() ->timeout(15); } /** Returns the verification; throws RequestException on an error answer ($e->response->json('error')). */ public function send(string $phone, string $purpose = 'verify', string $locale = 'ar', ?string $idempotencyKey = null): array { $request = $this->client(); if ($idempotencyKey) { $request = $request->withHeaders(['Idempotency-Key' => $idempotencyKey]); } return $request->post('/verify/send', compact('phone', 'purpose', 'locale'))->throw()->json(); } /** Trust only $result['valid'] === true. */ public function check(string $id, string $code): array { return $this->client()->post('/verify/check', compact('id', 'code'))->throw()->json(); } public static function errorCode(RequestException $e): string { return (string) ($e->response->json('error') ?? 'unknown'); } } ``` ```php title="examples/laravel/app/Http/Controllers/PhoneVerificationController.php" validate(['phone' => 'required|string|max:30', 'locale' => 'in:ar,en']); try { $v = $otp->send($data['phone'], 'verify', $data['locale'] ?? 'ar'); } catch (RequestException $e) { $code = OtpPs::errorCode($e); return response()->json(['error' => $code, 'retryAfter' => $e->response->json('retry_after')], $code === 'rate_limited' ? 429 : 422); } // Keep the id and the number in the session; the browser only learns that a code was sent. $request->session()->put('otp_pending', ['id' => $v['id'], 'phone' => $data['phone']]); return response()->json(['sent' => true, 'to' => $v['to'], 'expiresAt' => $v['expires_at']]); } public function check(Request $request, OtpPs $otp) { $data = $request->validate(['code' => 'required|string|max:10']); $pending = $request->session()->get('otp_pending'); if (!$pending) { return response()->json(['error' => 'no_code'], 422); } try { $r = $otp->check($pending['id'], $data['code']); } catch (RequestException $e) { return response()->json(['error' => OtpPs::errorCode($e)], 422); } if ($r['valid'] === true) { $request->session()->forget('otp_pending'); // The number is verified: save it on the user / order here, e.g. // $request->user()?->forceFill(['phone' => $pending['phone'], 'phone_verified_at' => now()])->save(); $request->session()->put('verified_phone', $pending['phone']); return response()->json(['verified' => true]); } if ($r['status'] !== 'pending') { $request->session()->forget('otp_pending'); } return response()->json(['verified' => false, 'status' => $r['status'], 'attemptsLeft' => $r['attempts_left']], 422); } } ``` ```php title="examples/laravel/routes/web.php" middleware('throttle:5,15'); Route::post('/otp/check', [PhoneVerificationController::class, 'check'])->middleware('throttle:20,15'); ``` The routes are in `web.php`, so Laravel's session and CSRF protection apply: send the CSRF token with your `fetch` calls (`X-CSRF-TOKEN` from the `csrf-token` meta tag). These files are syntax-checked on every change; the Laravel framework itself isn't run in OTP.ps's tests. --- # Python > A standard-library Python client, a sandbox demo, and Flask endpoints. Python 3.8+, no dependencies for the client. The client and demo are tested against the API's sandbox on every change. ## Client ```python title="examples/python/otp_ps.py" """OTP.ps client for Python 3.8+ (standard library only). Server-side only. OTP_PS_API_KEY=otp_test_... (sandbox) or otp_live_... (real messages) OTP_PS_BASE_URL=https://otp.ps (optional) """ import json import os import urllib.error import urllib.request class OtpPsError(Exception): def __init__(self, status, body): body = body or {} super().__init__(body.get("message") or f"OTP.ps answered HTTP {status}") self.status = status self.code = body.get("error", "unknown") # e.g. invalid_phone, rate_limited self.retry_after = body.get("retry_after") # seconds, for rate_limited class OtpPs: def __init__(self, api_key=None, base_url=None, timeout=15): self.key = api_key or os.environ.get("OTP_PS_API_KEY") if not self.key: raise RuntimeError("OTP_PS_API_KEY is not set") self.base = (base_url or os.environ.get("OTP_PS_BASE_URL") or "https://otp.ps").rstrip("/") self.timeout = timeout def _request(self, method, path, body=None, headers=None): req = urllib.request.Request( f"{self.base}/api/v1{path}", method=method, data=json.dumps(body).encode() if body is not None else None, headers={"Authorization": f"Bearer {self.key}", "Content-Type": "application/json", **(headers or {})}, ) try: with urllib.request.urlopen(req, timeout=self.timeout) as res: return json.loads(res.read()) except urllib.error.HTTPError as e: try: data = json.loads(e.read()) except ValueError: data = None raise OtpPsError(e.code, data) from None def send_code(self, phone, purpose="verify", locale=None, idempotency_key=None): """Sends a code. Returns the verification (with test_code when using a test key).""" body = {"phone": phone, "purpose": purpose} if locale: body["locale"] = locale return self._request("POST", "/verify/send", body, {"Idempotency-Key": idempotency_key} if idempotency_key else None) def check_code(self, verification_id, code): """Checks what the customer typed. Trust only result["valid"] is True.""" return self._request("POST", "/verify/check", {"id": verification_id, "code": str(code)}) def balance(self): return self._request("GET", "/balance") ``` ## Sandbox demo ```bash OTP_PS_API_KEY=otp_test_… python demo.py ``` ```python title="examples/python/demo.py" """Sandbox walk-through: OTP_PS_API_KEY=otp_test_... python demo.py""" import os import sys import uuid sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from otp_ps import OtpPs, OtpPsError # noqa: E402 otp = OtpPs() sent = otp.send_code("0599000001", locale="en", idempotency_key=f"py-demo-{uuid.uuid4()}") print(f"Sent {sent['id']} to {sent['to']} (status {sent['status']})") wrong = otp.check_code(sent["id"], "0000") print(f"Wrong code: valid={wrong['valid']}, attempts_left={wrong['attempts_left']}") right = otp.check_code(sent["id"], "1234") # the sandbox number's fixed code print(f"Right code: valid={right['valid']}, status={right['status']}") try: otp.send_code("0599000002") # sandbox: the gateway refuses the message except OtpPsError as e: print(f"Refused message: {e.code} (status {e.status})") ``` ## Flask endpoints ```python title="examples/python/flask_app.py" """Flask endpoints for a website form (pip install flask). The verification id and the number stay in the server-side session data; the browser only learns that a code was sent. """ import os from flask import Flask, jsonify, request, session from otp_ps import OtpPs, OtpPsError app = Flask(__name__) app.secret_key = os.environ["FLASK_SECRET_KEY"] # signs the session cookie otp = OtpPs() @app.post("/api/otp/send") def send(): # Add your own per-visitor limit here (e.g. Flask-Limiter), so nobody can drain your balance. phone = str((request.json or {}).get("phone", "")) locale = "en" if (request.json or {}).get("locale") == "en" else "ar" try: v = otp.send_code(phone, purpose="verify", locale=locale) except OtpPsError as e: return jsonify(error=e.code, retryAfter=e.retry_after), 429 if e.code == "rate_limited" else 400 session["otp_pending"] = {"id": v["id"], "phone": phone} return jsonify(sent=True, to=v["to"], expiresAt=v["expires_at"]) @app.post("/api/otp/check") def check(): pending = session.get("otp_pending") if not pending: return jsonify(error="no_code"), 400 try: r = otp.check_code(pending["id"], str((request.json or {}).get("code", ""))) except OtpPsError as e: return jsonify(error=e.code), 400 if r["valid"] is True: session.pop("otp_pending") session["verified_phone"] = pending["phone"] # trust this, set on the server return jsonify(verified=True) if r["status"] != "pending": session.pop("otp_pending") return jsonify(verified=False, status=r["status"], attemptsLeft=r["attempts_left"]), 400 ``` For Django, the same two views apply: keep `{"id", "phone"}` in `request.session`, and set the verified number on the user only after `valid` is `True`. --- # WooCommerce > The OTP.ps plugin for WooCommerce, which confirms the customer's number before you ship a cash-on-delivery order, plus a minimal example. ## The plugin **[Download OTP.ps for WooCommerce](https://otp.ps/downloads/otp-ps-for-woocommerce.zip)** (WordPress 6.2+, WooCommerce 7+, PHP 7.4+). Two ways for customers to confirm, chosen in **WooCommerce → Settings → OTP.ps**: | | How | Checkouts | |---|---|---| | **After the order** (default) | The order waits **on hold**. The customer confirms through a [verification link](/docs/verification-links), texted to them or shown on the thank-you page. The order then moves to **processing** by itself, with a note | Every checkout, including the block checkout | | **At checkout** | A code box under the phone field; the order can't be placed until the number is confirmed | Classic (shortcode) checkout | Setup: 1. **Plugins → Add New → Upload Plugin**, choose the zip, activate. 2. Put your key in `wp-config.php`: `define('OTP_PS_API_KEY', 'otp_test_…');`. You can also enter it on the settings tab, but wp-config.php keeps it out of the database. 3. **WooCommerce → Settings → OTP.ps**: choose the mode and which payment methods need a confirmed number (cash on delivery by default), then press **Connect** under "Instant updates" to set up [webhooks](/docs/webhooks) automatically. 4. Test with the number `0599000001` and a test key (nothing is sent; on a code page the code is `1234`), then switch to a live key. If the webhook can't reach the store, the order is still confirmed when the customer comes back to the thank-you page: the plugin asks OTP.ps; it never trusts the address alone. Orders not confirmed in time get a note so your team can call the customer. The plugin is tested against the OTP.ps API with a stand-in for WordPress (holding the order, the texted link, forged and genuine webhooks, the thank-you page). Try it on a staging site before your live shop. ## A minimal example If you'd rather write your own, the file below is the classic-checkout version in one file. What it does: on the checkout page, under the billing details, the customer can send a code to their billing phone and confirm it. A **cash-on-delivery** order is refused unless the billing phone matches the number confirmed in this session. Other payment methods are not affected. Setup: 1. Add the key to `wp-config.php` (not to the database or the theme): `define('OTP_PS_API_KEY', 'otp_test_…');` 2. Save the file as `wp-content/plugins/otp-ps-cod/otp-ps-cod.php` and activate **OTP.ps — verify the phone on cash-on-delivery orders**. 3. Test with the sandbox number `0599000001` (code `1234`), then switch to a live key. Limits of this example: it supports the **classic (shortcode) checkout**. The block-based Checkout needs a different integration (a Store API extension), not covered yet. The file is syntax-checked on every change; it hasn't been run inside a WordPress installation in OTP.ps's tests, so try it on a staging site first. ```php title="examples/woocommerce/otp-ps-cod.php" '0', '١' => '1', '٢' => '2', '٣' => '3', '٤' => '4', '٥' => '5', '٦' => '6', '٧' => '7', '٨' => '8', '٩' => '9'])); if (strpos($d, '00') === 0) $d = substr($d, 2); if (strlen($d) === 12 && (strpos($d, '970') === 0 || strpos($d, '972') === 0)) $d = substr($d, 3); if (strlen($d) === 10 && $d[0] === '0') $d = substr($d, 1); return preg_match('/^5[96]\d{7}$/', $d) ? '+970' . $d : null; } function otp_ps_cod_api(string $path, array $body, array $headers = []): array { $res = wp_remote_post(OTP_PS_COD_BASE . '/api/v1' . $path, [ 'timeout' => 15, 'headers' => array_merge(['Authorization' => 'Bearer ' . OTP_PS_API_KEY, 'Content-Type' => 'application/json'], $headers), 'body' => wp_json_encode($body), ]); if (is_wp_error($res)) { return ['ok' => false, 'data' => ['error' => 'unavailable']]; } $code = wp_remote_retrieve_response_code($res); return ['ok' => $code < 400, 'data' => json_decode(wp_remote_retrieve_body($res), true) ?: []]; } // AJAX: send a code to the billing phone. function otp_ps_cod_send(): void { check_ajax_referer('otp_ps_cod', 'nonce'); $phone = otp_ps_cod_normalize((string) ($_POST['phone'] ?? '')); if (!$phone) { wp_send_json_error(['error' => 'invalid_phone']); } $sends = array_filter((array) WC()->session->get('otp_ps_sends', []), fn($t) => $t > time() - 900); if (count($sends) >= 5) { wp_send_json_error(['error' => 'rate_limited']); // your own limit per visitor } $sends[] = time(); WC()->session->set('otp_ps_sends', $sends); $locale = strpos(get_locale(), 'ar') === 0 ? 'ar' : 'en'; $r = otp_ps_cod_api('/verify/send', ['phone' => $phone, 'purpose' => 'order', 'locale' => $locale]); if (!$r['ok']) { wp_send_json_error(['error' => $r['data']['error'] ?? 'unavailable', 'retryAfter' => $r['data']['retry_after'] ?? null]); } WC()->session->set('otp_ps_pending', ['id' => $r['data']['id'], 'phone' => $phone]); wp_send_json_success(['to' => $r['data']['to']]); } add_action('wp_ajax_otp_ps_cod_send', 'otp_ps_cod_send'); add_action('wp_ajax_nopriv_otp_ps_cod_send', 'otp_ps_cod_send'); // AJAX: check the code. function otp_ps_cod_check(): void { check_ajax_referer('otp_ps_cod', 'nonce'); $pending = WC()->session->get('otp_ps_pending'); if (!$pending) { wp_send_json_error(['error' => 'no_code']); } $r = otp_ps_cod_api('/verify/check', ['id' => $pending['id'], 'code' => sanitize_text_field((string) ($_POST['code'] ?? ''))]); if ($r['ok'] && ($r['data']['valid'] ?? false) === true) { WC()->session->set('otp_ps_pending', null); WC()->session->set('otp_ps_verified_phone', $pending['phone']); wp_send_json_success(['verified' => true]); } if (($r['data']['status'] ?? '') !== 'pending') { WC()->session->set('otp_ps_pending', null); } wp_send_json_error(['status' => $r['data']['status'] ?? null, 'attemptsLeft' => $r['data']['attempts_left'] ?? null]); } add_action('wp_ajax_otp_ps_cod_check', 'otp_ps_cod_check'); add_action('wp_ajax_nopriv_otp_ps_cod_check', 'otp_ps_cod_check'); // The order is refused unless the billing phone was verified in this session. add_action('woocommerce_checkout_process', function () { if (($_POST['payment_method'] ?? '') !== 'cod') { return; } $phone = otp_ps_cod_normalize((string) ($_POST['billing_phone'] ?? '')); if (!$phone || WC()->session->get('otp_ps_verified_phone') !== $phone) { wc_add_notice(__('Please confirm your mobile number with the code we send you before placing a cash-on-delivery order.', 'otp-ps-cod'), 'error'); } }); // The code box under the billing phone, and its script. add_action('woocommerce_after_checkout_billing_form', function () { echo '
' . ' ' . ' ' . '' . '

'; }); add_action('wp_enqueue_scripts', function () { if (!function_exists('is_checkout') || !is_checkout()) { return; } wp_register_script('otp-ps-cod', '', ['jquery'], '1.0.0', true); wp_enqueue_script('otp-ps-cod'); wp_localize_script('otp-ps-cod', 'otpPsCod', [ 'ajax' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('otp_ps_cod'), 'sent' => __('Code sent to', 'otp-ps-cod'), 'ok' => __('Number confirmed ✓', 'otp-ps-cod'), 'wrong' => __('Wrong code. Tries left:', 'otp-ps-cod'), 'again' => __('Please ask for a new code.', 'otp-ps-cod'), 'error' => __('Could not send the code. Check the number and try again.', 'otp-ps-cod'), ]); wp_add_inline_script('otp-ps-cod', <<<'JS' jQuery(function ($) { var busy = false, msg = function (t) { $('#otp-ps-msg').text(t); }; $(document).on('click', '#otp-ps-send', function () { if (busy) return; busy = true; var b = $(this).prop('disabled', true); $.post(otpPsCod.ajax, { action: 'otp_ps_cod_send', nonce: otpPsCod.nonce, phone: $('#billing_phone').val() }) .done(function (r) { msg(r.success ? otpPsCod.sent + ' ' + r.data.to : otpPsCod.error); }) .always(function () { busy = false; setTimeout(function () { b.prop('disabled', false); }, 30000); }); }); $(document).on('click', '#otp-ps-check', function () { if (busy) return; busy = true; $.post(otpPsCod.ajax, { action: 'otp_ps_cod_check', nonce: otpPsCod.nonce, code: $('#otp-ps-code').val() }) .done(function (r) { if (r.success) msg(otpPsCod.ok); else if (r.data && r.data.status === 'pending') msg(otpPsCod.wrong + ' ' + r.data.attemptsLeft); else msg(otpPsCod.again); }) .always(function () { busy = false; }); }); }); JS ); }); ``` --- # Shopify > What is and isn't possible with Shopify today, and the recommended pattern. There is **no OTP.ps Shopify app yet**. Shopify controls its checkout, so a third party can't add a required code step before "Place order" on most plans. What works today: ## Easiest: verification links, no app needed 1. In **Shopify Flow**, trigger **Order created**. Add a condition: the payment gateway is cash on delivery. 2. Add the action **Send HTTP request**: `POST https://otp.ps/api/v1/verify/links` with the header `Authorization: Bearer ` and the body: ```json { "phone": "{{order.shippingAddress.phone}}", "purpose": "order", "reference": "{{order.name}}", "delivery": "sms" } ``` Pick the fields with Flow's variable picker (the phone may be on the shipping address or the customer). Also tag the order `awaiting-phone-confirmation` in Flow. 3. OTP.ps texts the customer a link; they press Confirm. 4. In Zapier, Make or n8n, the OTP.ps trigger **Link approved** starts a step that replaces the tag with `phone-confirmed` (Shopify's "Update order" or "Add tag" action, matching `reference` to the order name). Your team ships only orders tagged `phone-confirmed`. ## With your own backend: confirm after the order is placed 1. A small backend of yours subscribes to Shopify's `orders/create` webhook. 2. For cash-on-delivery orders, it tags the order `awaiting-phone-confirmation` and sends a code with `purpose: "order"` and `Idempotency-Key: shopify--otp-1` to the order's phone. 3. The customer types the code on a page of yours, linked from the order confirmation email or shown on the thank-you page (where your Shopify app or theme allows it). 4. On `valid: true`, your backend replaces the tag with `phone-confirmed`. Your team ships only confirmed orders, and calls or cancels the rest after a few hours. This uses Shopify's Admin API (order tags) and webhooks from your own backend. The OTP.ps key stays on that backend, never in the theme. ## Not possible / not recommended - Calling OTP.ps from theme JavaScript: the key would be public. - Blocking checkout before payment: only possible with checkout extensions on plans that allow them; not covered by this guide. A ready-made Shopify app is on the roadmap. --- # Zapier > Confirm customers' numbers from any Zapier workflow, for example Shopify cash-on-delivery orders, with the OTP.ps app's triggers and actions. > **Status: built and tested, not yet in Zapier's app directory.** OTP.ps publishes it from its Zapier developer account; until then, use the [no-app route](#without-the-app) below. ## What the app does | | | |---|---| | **Trigger: Link Confirmed** (instant) | A customer confirmed a [verification link](/docs/verification-links). Gives the link, including your `reference` | | **Trigger: Link Expired** (instant) | A link wasn't confirmed in time | | **Action: Create Verification Link** | Texts the customer a link to confirm (or gives you one to share) | | **Action: Send Verification Code** / **Check Verification Code** | The code flow, for Zaps that collect the code themselves (a form, a chat) | | **Search: Find Verification Link** | The latest link with your reference | Connecting asks for an API key; start with a test key (`otp_test_…`), which sends nothing. The triggers register their own [webhook](/docs/webhooks) with OTP.ps and remove it when the Zap is turned off. ## Cash-on-delivery orders from Shopify **Zap 1**, when an order comes in: 1. Trigger: **Shopify → New Order**. Filter: payment gateway is cash on delivery. 2. Action: **OTP.ps → Create Verification Link**: Mobile Number = the order's phone, What Is Confirmed = Order, Your Reference = the order name (e.g. `#1042`), How = Text the link. 3. Action: **Shopify → Add tag to order**: `awaiting-phone-confirmation`. **Zap 2**, when the customer confirms: 1. Trigger: **OTP.ps → Link Confirmed**. 2. Action: **Shopify → Find Order** by name = Your Reference, then **Update order**: tag `phone-confirmed`. Add a third Zap on **Link Expired** to notify your team. ## Without the app **Webhooks by Zapier** (a paid Zapier plan) does the same with plain requests: - Create the link with **Webhooks by Zapier → Custom Request**, `POST https://otp.ps/api/v1/verify/links` with the header `Authorization: Bearer ` and the JSON body from [Verification links](/docs/verification-links). - Receive confirmations with **Webhooks by Zapier → Catch Hook**, and add its address on the OTP.ps dashboard (Webhooks, event `link.approved`). ## How it was tested The app runs with Zapier's own local test tool against the OTP.ps API: - the connection test, and a wrong key being refused; - creating, finding and checking; - the instant trigger subscribing, receiving a confirmed link and unsubscribing. It also passes the same validation Zapier's publishing tool runs. --- # n8n > OTP.ps nodes for n8n (an action node and an instant trigger), or the same with n8n's built-in HTTP Request and Webhook nodes. > **Status: built and tested, not yet on npm.** Once OTP.ps publishes `n8n-nodes-otp-ps`, install it in **Settings → Community Nodes**. Until then, use the [built-in nodes](#with-n8ns-built-in-nodes). ## The OTP.ps nodes - **OTP.ps**: verification links (create, get, get many, cancel), codes (send, check), account (balance, usage). - **OTP.ps Trigger**: starts the workflow when a customer confirms a link (or it expires or is canceled). It registers its own [webhook](/docs/webhooks) with OTP.ps when the workflow is activated, removes it when deactivated, and **refuses any request whose signature doesn't match**. Add an **OTP.ps API** credential with your key (start with a test key). A cash-on-delivery workflow: **WooCommerce / Shopify Trigger** (order created) → **IF** cash on delivery → **OTP.ps: Create verification link** (reference = order number). A second workflow: **OTP.ps Trigger** (Link confirmed) → **Shopify / WooCommerce: Update order** using `reference`. ## With n8n's built-in nodes - **HTTP Request**: `POST https://otp.ps/api/v1/verify/links`, authentication "Header Auth" (`Authorization` = `Bearer `), JSON body as in [Verification links](/docs/verification-links). - **Webhook** node (POST): copy its production URL into the OTP.ps dashboard (Webhooks). Before acting on an event, confirm it with an **HTTP Request** `GET https://otp.ps/api/v1/verify/links/{{$json.body.data.id}}` and check `status` is `approved`, or check the `OTP-Signature` header in a **Code** node as on the [Webhooks](/docs/webhooks) page. ## How it was tested Both nodes run against the OTP.ps API with a stand-in for n8n's runtime: - every operation of the action node; - the trigger registering itself, accepting a genuine signed event, refusing a forged one, and removing itself. The package also builds to the files n8n loads. --- # Make > Confirm customers' numbers in Make scenarios with the built-in HTTP and Webhooks modules. > **Status:** there is no OTP.ps app in Make yet. Everything below uses Make's built-in modules and works today. It follows Make's documented modules, but OTP.ps hasn't run these scenarios inside Make itself. ## Scenario 1: when an order comes in 1. **Shopify → Watch Orders** (or **WooCommerce → Watch Orders**), with a filter: payment is cash on delivery. 2. **HTTP → Make an API Key Auth request**. Put your OTP.ps key in a keychain: "In" = Header, name `Authorization`, key `Bearer otp_live_…` (keychains keep it out of the scenario). - URL: `https://otp.ps/api/v1/verify/links`, method POST, body type Raw, content type JSON: ```json { "phone": "{{1.phone}}", "purpose": "order", "reference": "{{1.name}}", "delivery": "sms" } ``` - Header `Idempotency-Key`: the order id, so a retried run never texts twice. 3. **Shopify → Add tag** `awaiting-phone-confirmation`. ## Scenario 2: when the customer confirms 1. **Webhooks → Custom webhook**. Copy its address and add it on the OTP.ps dashboard (**Webhooks**, event `link.approved`, live links). 2. **HTTP → Make an API Key Auth request**, `GET https://otp.ps/api/v1/verify/links/{{1.data.id}}` with the same keychain. Continue only if `status` = `approved`. This checks the event really came from OTP.ps; anyone who learned the webhook address could post to it. 3. **Shopify → Search orders** by name = `{{1.data.reference}}`, then **Update order** / **Add tag** `phone-confirmed`. ## Notes - With a test key, use the [sandbox numbers](/docs/sandbox); nothing is sent. - Make retries failed operations: the `Idempotency-Key` header keeps a retry from texting the customer twice. --- # JavaScript / TypeScript SDK > @otp-ps/sdk: typed client with safe retries, timeouts, sandbox helpers and phone validation. > **Status: ready, not yet published.** `@otp-ps/sdk` will be on npm once OTP.ps releases it. Until then, use the [TypeScript example client](/docs/examples/javascript-typescript), which has the same calls. Server-side only: Node.js 20+, Bun, Deno, Cloudflare Workers, Vercel and Next.js server code. No dependencies. It refuses to start in a browser, where the key would be public. ```bash npm install @otp-ps/sdk ``` ```ts import { OtpPs, OtpPsError } from "@otp-ps/sdk"; const otp = new OtpPs(); // reads OTP_PS_API_KEY (and OTP_PS_BASE_URL) const v = await otp.verify.send({ phone: "0599123456", purpose: "order", locale: "ar" }); // keep v.id on your server const r = await otp.verify.check({ id: v.id, code: codeFromCustomer }); if (r.valid) { // verified } ``` ## What it handles for you | | | |---|---| | Types | `Verification`, `SendResult`, `CheckResult`, `Balance` and `ApiErrorCode` match the API contract exactly (checked by OTP.ps's tests at compile time). | | Errors | Every failure is an `OtpPsError` with `code` (an API error code, or `network_error`, `timeout`, `server_error`), `status`, `retryAfter` and `retryable`. | | Timeouts | `timeoutMs`, default 15 seconds per attempt. | | Safe retries | Sends always carry an `Idempotency-Key` (yours or a generated one), so after a network failure or server error the SDK retries them (`maxRetries`, default 2) **without sending or charging twice**. Checks are never retried: a lost answer may already have used an attempt or approved the code. | | Sandbox | `otp.mode` is `"test"` with a test key; `SANDBOX_NUMBERS` and `SANDBOX_CODE` give the [sandbox numbers](/docs/sandbox). | | Numbers | `normalizePhone(raw)` → `+9705XXXXXXXX` or `null`, the API's rules. | ## Account information ```ts const usage = await otp.usage(); // today, this month, last 30 days const limits = await otp.limits(); // permissions, spending limits and what's used ``` ## Options ```ts new OtpPs({ apiKey: "otp_test_…", // default: OTP_PS_API_KEY baseUrl: "https://otp.ps", // default: OTP_PS_BASE_URL, else https://otp.ps timeoutMs: 15_000, maxRetries: 2, fetch: customFetch, // optional }); ``` ## Errors ```ts try { await otp.verify.send({ phone, idempotencyKey: `order-${orderId}-otp-1` }); } catch (e) { if (!(e instanceof OtpPsError)) throw e; switch (e.code) { case "invalid_phone": case "unsupported_network": return showError("Please check the number (Jawwal or Ooredoo only)."); case "rate_limited": return showCountdown(e.retryAfter ?? 30); default: alertTeam(e); // insufficient_balance, unauthorized, network_error… return showError("Verification isn't available right now."); } } ``` ## Testing with the sandbox ```ts import { OtpPs, SANDBOX_CODE, SANDBOX_NUMBERS } from "@otp-ps/sdk"; const otp = new OtpPs({ apiKey: process.env.OTP_PS_TEST_KEY }); const v = await otp.verify.send({ phone: SANDBOX_NUMBERS.success }); const r = await otp.verify.check({ id: v.id, code: SANDBOX_CODE }); // r.valid === true await otp.verify.send({ phone: SANDBOX_NUMBERS.smsFailed }); // throws OtpPsError "sms_failed" ``` --- # PHP SDK > otp-ps/sdk: typed PHP 8.1+ client with safe retries, timeouts, sandbox constants and phone validation; works with or without Composer. > **Status: ready, not yet published.** `otp-ps/sdk` will be on Packagist once OTP.ps releases it. Until then, use the [PHP example client](/docs/examples/php) or the [Laravel example](/docs/examples/laravel). PHP 8.1+, with the curl and json extensions (both standard). No other dependencies. ```bash composer require otp-ps/sdk ``` On hosting without Composer, upload the package folder and `require 'otp-ps-sdk/autoload.php';`. ```php id in the session, never in a hidden form field. $v = $otp->send('0599123456', purpose: 'order', locale: 'ar'); $_SESSION['otp'] = ['id' => $v->id, 'phone' => OtpPs\Phone::normalize('0599123456')]; // 2. Check what the customer typed. Trust only ->valid. $r = $otp->check($_SESSION['otp']['id'], $_POST['code']); if ($r->valid) { // verified: save $_SESSION['otp']['phone'] on the order or user } elseif ($r->status === 'pending') { echo "Wrong code, {$r->attemptsLeft} tries left"; } else { echo 'Please ask for a new code'; // expired, failed or replaced } ``` ## What it handles for you | | | |---|---| | Typed answers | `SendResult` (with `testCode` for test keys), `CheckResult` (`valid`, `attemptsLeft`), `Verification`, `Balance`, all with read-only properties. | | Errors | Every failure is an `OtpPs\OtpPsException` with `errorCode` (an API error code, or `network_error`, `timeout`, `server_error`), `status`, `retryAfter` and `isRetryable()`. | | Timeouts | `timeout`, default 15 seconds per attempt. | | Safe retries | Sends always carry an `Idempotency-Key` (yours or a generated one), so after a network failure or server error the client retries them (`maxRetries`, default 2) **without sending or charging twice**. Checks are never retried. | | Sandbox | `$otp->mode` is `'test'` with a test key; `OtpPs\Sandbox::SUCCESS`, `SMS_FAILED`, `INSUFFICIENT_BALANCE`, `RATE_LIMITED`, `EXPIRED` and `Sandbox::CODE` give the [sandbox numbers](/docs/sandbox). | | Numbers | `OtpPs\Phone::normalize($raw)` → `+9705XXXXXXXX` or `null`, the API's rules. | ## Account information ```php $usage = $otp->usage(); // today, this month, last 30 days (array) $limits = $otp->limits(); // permissions, spending limits and what's used (array) ``` ## Options ```php $otp = new OtpPs\Client( apiKey: getenv('OTP_PS_API_KEY'), baseUrl: 'https://otp.ps', timeout: 15, maxRetries: 2, ); ``` ## Errors ```php try { $v = $otp->send($phone, purpose: 'order', idempotencyKey: "order-{$orderId}-otp-1"); } catch (OtpPs\OtpPsException $e) { match ($e->errorCode) { 'invalid_phone', 'unsupported_network' => showError('رقم الجوال غير صحيح (جوال أو Ooredoo فقط).'), 'rate_limited' => showCountdown($e->retryAfter ?? 30), default => alertTeamAndShowGenericError($e), }; } ``` --- # Security best practices > Keeping keys safe, preventing abuse and SMS pumping, and verifying correctly. ## Keys - Keys live only on your server, in environment variables. Never in browser code, mobile apps, Git, logs or error messages. - Use test keys in development and CI; only production has the live key. - One key per application; revoke a key on the dashboard as soon as it may have leaked. ## Verify correctly - **Act only on `valid: true`** from your own server's call to `/verify/check`. Never trust a "verified" flag, a phone number or a verification id sent by the browser. - Keep `{ verification id, number }` on the server (session, signed cookie or database) between send and check. - When the order or account is saved, compare its phone with the number you verified. Otherwise a customer can verify one number and submit another. - Never log, store or display the code. Never send `test_code` to the browser, even in the sandbox. ## Stop abuse and SMS pumping Every code you send costs money, and public forms attract bots that trigger messages to random or premium numbers ("SMS pumping"). OTP.ps only sends to Palestinian mobiles and limits per number: one code every 30 seconds, 5 an hour and 10 a day; per account: 120 codes a minute (test and live keys are counted separately). Add your own layers: - A per-IP and per-session limit on your send endpoint (e.g. 5 per 15 minutes). - A CAPTCHA (or a similar check) on public forms before sending. - Send only when it's needed: e.g. only for cash-on-delivery, only after the rest of the form is valid. - Disable the send button while a request is in flight and for 30 seconds after; use an `Idempotency-Key` on retries. - Watch your balance and usage on the dashboard; a sudden jump means abuse. ## Spending limits Every live message counts against limits that stop a bug or an attack from draining your balance. Test keys spend nothing and have none. | Limit | Set by | Where | |---|---|---| | Daily ceiling per account | OTP.ps (500 messages a day for new accounts, raised for trusted high-volume businesses) | Contact OTP.ps | | Your daily limit | You | Dashboard → Settings → Spending limits | | Your monthly limit | You | Dashboard → Settings → Spending limits | | A key's daily limit | You, per key | Dashboard → API keys, when creating the key | Days and months are in Palestine time. When a limit is reached, sends answer `429 spending_limit_reached` with `retry_after` (seconds until it resets), nothing is charged, and the event appears in your **activity log**. Limits are counted atomically: parallel requests can't slip past them. `GET /api/v1/limits` shows them all with what is used. Set your daily limit a little above your busiest real day; that alone stops most SMS pumping. ## Activity log The dashboard's **Activity log** lists sign-ins (and wrong passwords), keys created and revoked, settings and limit changes, limits reached, AI tools connected, and every change made by the OTP.ps team, with the time and IP address. If you see something you didn't do, change your password and revoke your keys. ## Data - Numbers are personal data: keep them only as long as needed, and show them masked where possible (the API's `to` field is already masked). - Use HTTPS everywhere, so the session that holds the pending verification is protected. --- # Production checklist > What to check before switching from a test key to a live key. Copy this list into your pull request or ticket. ### Keys and configuration - [ ] The live key is in the production environment only (`OTP_PS_API_KEY`), marked secret, not in Git. - [ ] No key, verification id, code or `test_code` reaches the browser or app (check the network tab). - [ ] Development and CI use a test key. - [ ] The account is approved and has credit (`GET /api/v1/balance` answers `status: "active"`). - [ ] Each key has only the permissions it needs (e.g. no `read` on the website's key, `read` only for reporting). - [ ] A daily (and monthly) spending limit is set a little above your busiest real day. ### Flow - [ ] The right code verifies; your server records the number it sent the code to. - [ ] The saved order or account phone is compared with the verified number. - [ ] Wrong code shows the tries left; after 5 the customer is asked for a new code. - [ ] Expired codes ask for a new one (sandbox number `0599000005`). - [ ] Resend has a 30-second countdown and respects `retry_after`. - [ ] Double-clicking "Send" sends one message; retries use an `Idempotency-Key`. ### Errors - [ ] `invalid_phone` and `unsupported_network` show a clear message in the customer's language. - [ ] `sms_failed` (`0599000002`) lets the customer retry. - [ ] `insufficient_balance` (`0599000003`), `spending_limit_reached`, `insufficient_scope`, `unauthorized`, `account_pending` and `account_suspended` alert your team. - [ ] Network failures and timeouts show a friendly message, and you've decided what happens to the order or sign-up then. ### Abuse - [ ] Your send endpoint has a per-IP / per-session limit. - [ ] Public forms have a CAPTCHA or similar. - [ ] Someone watches the balance (low-balance warning on the dashboard) and the activity log. ### Language and layout - [ ] Arabic pages are right to left; number and code inputs are `dir="ltr"`. - [ ] `locale` matches the customer's language. - [ ] The code input has `autocomplete="one-time-code"` and a numeric keyboard. ### Finally - [ ] One real send to your own Jawwal and Ooredoo numbers with the live key. --- # Frequently asked questions > Short answers to common questions about OTP.ps. **Which numbers can receive codes?** Palestinian mobiles on Jawwal (059) and Ooredoo (056). See [Phone numbers](/docs/phone-numbers). **What does the message look like?** Your business's name, then for example "رمز التحقق 4821، صالح 5 دقائق، لا تشاركه." or "Your verification code is 4821. Valid for 5 min. Don't share it." The wording depends on `purpose` and `locale`. **Can messages come from my own name?** By default they come from OTP.ps's sender name and start with your business's name. You can ask for your own sender name on the dashboard (Settings); OTP.ps registers it with the gateway, which can take days. **How much does it cost?** You pay per text message from a prepaid balance; test keys are free. One code is one message. Contact OTP.ps for package prices. **Am I charged if the message fails?** No. If the gateway refuses it, the credit is returned at once. **Can I resend a code?** Yes: send again after 30 seconds. The new code replaces the old one. **Can I choose the code or its length?** OTP.ps generates the code. You choose 4 or 6 digits and how long it is valid (1–15 minutes) in Settings. **Do you tell me when a message is delivered?** No, only whether the gateway accepted it. **Can I call the API from my website's JavaScript or my mobile app?** No. Call it from your server; your site or app talks to your server. The API doesn't allow browser calls (no CORS). **Is there a sandbox?** Yes: test keys, plus [sandbox numbers](/docs/sandbox) that simulate each outcome. **Can an AI coding assistant integrate OTP.ps for me?** Yes: point it at this documentation, [`/llms.txt`](/llms.txt) or the [OpenAPI document](/openapi.json), and have it test with a test key first. **I lost my API key.** Keys are shown once. Revoke it and create a new one on the dashboard. --- # Integrate with AI > Use an AI coding assistant to integrate OTP.ps: a ready prompt, the official Agent Skill, the MCP server, llms.txt and OpenAPI. OTP.ps is built so an AI coding assistant can integrate it for you: read the docs, write a secure server-side integration in your stack, test it in the sandbox, and give you a production checklist. Everything here is free; you only pay for real text messages. ## The prompt Open your project in your AI coding assistant and paste: > Integrate OTP.ps into my application to verify Palestinian mobile numbers using SMS verification codes. Inspect my existing technology stack, follow the official OTP.ps documentation, implement a secure server-side integration, and test it using the sandbox environment before enabling production messaging. Add your use case at the end, for example *"…to confirm cash-on-delivery orders at checkout"*. Then give the assistant one of the tools below, so it doesn't work from memory. ## The Agent Skill A folder of instructions, references, tested examples and scripts in the open [Agent Skills](https://agentskills.io) format. It teaches the assistant the whole workflow: inspect the app, choose the architecture, keep the key on the server, normalize numbers, build the send/check endpoints and the form (Arabic RTL and English), handle every error, test with the sandbox numbers, and hand over the checklist. Its scripts check a test key against the sandbox (refusing live keys) and scan the project for leaked keys. **Claude Code**, for one project (run in the project's folder): ```bash mkdir -p .claude/skills && curl -fsSL https://otp.ps/skills/otp-integration.tar.gz | tar -xz -C .claude/skills ``` or for all your projects: ```bash mkdir -p ~/.claude/skills && curl -fsSL https://otp.ps/skills/otp-integration.tar.gz | tar -xz -C ~/.claude/skills ``` Claude Code then uses it whenever you ask for OTP.ps or phone verification. **Other assistants:** if your tool supports Agent Skills, put the same `otp-integration` folder where it loads skills from (see its documentation). If it doesn't, [download the folder](https://otp.ps/skills/otp-integration.tar.gz) into your project and tell the assistant to follow `otp-integration/SKILL.md`, or tell it to read `https://otp.ps/llms.txt`. ## The MCP server `https://otp.ps/mcp` (Streamable HTTP, no account needed). It lets the assistant look things up and **try the API in the sandbox** while it works: | Tool | What it does | |---|---| | `get_integration_guide` | A guide for a use case (cash on delivery, registration, passwordless login, phone verification, delivery, appointments) or topic | | `get_code_example` | Tested code for cURL, TypeScript, Node.js, React, Next.js, PHP, Laravel, Python, WooCommerce, Shopify | | `get_api_reference` | The API reference, or the OpenAPI document | | `get_error_reference` | What an error code means and what to do | | `normalize_phone` | Validates and normalizes a number exactly like the API | | `get_supported_networks` | Networks, accepted formats, sandbox numbers | | `send_test_otp`, `verify_test_otp` | Send and check a code in the sandbox: no message is sent, nothing is charged | | `get_integration_checklist` | The production checklist and security practices | It also offers every docs page, the OpenAPI document and the Agent Skill as resources, and an `integrate_otp_ps` prompt. **Claude Code:** ```bash claude mcp add --transport http otp-ps https://otp.ps/mcp ``` **Other clients** that support remote MCP servers over HTTP use the same address. For example, a `mcp.json`-style configuration: ```json { "mcpServers": { "otp-ps": { "url": "https://otp.ps/mcp" } } } ``` and VS Code's `.vscode/mcp.json`: ```json { "servers": { "otp-ps": { "type": "http", "url": "https://otp.ps/mcp" } } } ``` Without an account, `send_test_otp` works on the [sandbox numbers](/docs/sandbox) only, in a private sandbox for your connection. To use any number in **your own** sandbox, add your **test** key to the connection, e.g. `claude mcp add --transport http otp-ps https://otp.ps/mcp --header "Authorization: Bearer otp_test_…"`. The MCP server refuses live keys: it can't send real messages or touch your balance. Your production integration never depends on the MCP server or an AI: it calls the REST API directly. ### Account tools (not available yet) A second address, `https://otp.ps/mcp/account`, will let an AI tool work on **your own account** after you approve it: | Tool | Permission | |---|---| | `send_otp` (real messages in live mode; requires an idempotency key) | Send codes | | `verify_otp` | Check codes | | `get_balance`, `get_usage`, `get_account_limits` | Read balance, usage and limits | The tool signs in with OAuth. You approve it on OTP.ps while signed in to your dashboard, and choose: - which permissions it gets; - test or live mode; - a daily message limit, which is required for live sending. Everything it does appears in your **Activity log**, where you can disconnect it at any time. This is built and tested but **switched off** until OTP.ps finishes its security review. Until then, that address answers "not found". ## Plain documentation for any AI - [`/llms.txt`](https://otp.ps/llms.txt): what OTP.ps is, the key facts, and an index of every page. - [`/llms-full.txt`](https://otp.ps/llms-full.txt): all the documentation in one file. - Any docs page as Markdown: add `.md` to its address, e.g. `https://otp.ps/docs/quickstart.md`. - [`/openapi.json`](https://otp.ps/openapi.json): the OpenAPI 3.1 contract, built from the API's code. ## What has been tested | | | |---|---| | MCP server | With the official MCP client over HTTP (every tool, resource and prompt), and Claude Code connects to it (`claude mcp list` reports it connected). | | Account tools (switched off) | The official MCP client completes the whole OAuth sign-in and uses every account tool; Claude Code recognises that `/mcp/account` needs sign-in. | | Agent Skill | Its scripts and every example are run or syntax-checked against the API on every change; its references are regenerated from these docs. The folder follows the Agent Skills format checked by the tests. | | Other assistants | Cursor, VS Code, Codex, Windsurf, Lovable and Replit haven't been tested by OTP.ps yet. The configurations above follow their published formats for remote MCP servers. |