# SMS Receiving Platform · API Integration Guide v2.0

> New integrations must use `https://api.psyawqnx.beauty/v2/` (Haozhu-style, API account + API password). This guide covers the full integration flow, endpoint definitions, state machine and billing rules. The original `open/*` rules remain only for legacy systems and are not used by new software.
> Last updated: 2026-11-20
> Source of truth: `app/controllers/OpenController.php` + `app/core/KeywordService.php` (source paths are for reference only, not downloadable from the frontend)

---

## v2 Haozhu-compatible Access (for existing software)

v2 uses the Haozhu-style `api=action` protocol. Existing software only needs to switch the endpoint to `https://api.psyawqnx.beauty/v2/` and use this platform's username/password. Compared with the original protocol, this platform adds global countries, unified service search, keyword SMS, rentals and email; upstream provider identifiers and cost fields are never returned.

> The only public endpoint is `https://api.psyawqnx.beauty/v2/`; `/v2`, `/v2/` and `/v2/sms/` all work.

> **Security**: Third-party software must use the dedicated **API account / API password** from User Center. **Never use the website username and login password.** Dedicated credentials can be rotated at any time; legacy username + API key is kept only for backward compatibility; the website login password is never accepted by v2.

### Endpoint and authentication

| Item | Description |
|------|-------------|
| Login | `api=login&user=API_ACCOUNT&pass=API_PASSWORD` → `token`, `money` |
| Later requests | Send `token=TOKEN`; direct `user`+`pass`, `apikey` and `X-API-KEY` also work |
| Response | Flat top-level fields; `code=0` success, `code=-1` waiting for SMS, other codes are errors |

```bash
curl -s -G 'https://api.psyawqnx.beauty/v2/' \
  --data-urlencode 'api=login' \
  --data-urlencode 'user=YOUR_API_ACCOUNT' \
  --data-urlencode 'pass=YOUR_API_PASSWORD'

curl -s -G 'https://api.psyawqnx.beauty/v2/' \
  --data-urlencode 'api=getSummary' \
  --data-urlencode 'token=YOUR_TOKEN'
```

### Core Field Reference

All response fields are flat at the top level. Common country, service ID and order fields are listed below.

**Country fields (getCountries)**

| Field | Example | Description |
|-------|---------|-------------|
| id | `name:china` / `US` | Country code and unique identifier; can be used as `country` |
| name | `中国` | Display name in Chinese |
| code | `CN` | ISO 3166-1 alpha-2 code; may be empty for some countries |

```json
{"code":0,"msg":"success","list":[{"id":"name:china","name":"中国","code":"CN"}],"total":210}
```

**Service ID fields (getProjects)**

| Field | Example | Description |
|-------|---------|-------------|
| sid | `eyJ0Ijoic21zIi...` | Service ID for ordering; pass unchanged to `getPhone` / `rentPhone` |
| name | `Hostinger` | Service name |
| country | `哥伦比亚` | Country of the service |
| price | `0.22` | User-specific sale price (USD); cost is never returned |

```json
{"code":0,"msg":"success","list":[{"sid":"eyJ0Ijoic21zIi...","name":"Hostinger","country":"哥伦比亚","price":"0.22"}],"total":235}
```

**Order and SMS fields**

| API | Field | Example | Description |
|-----|-------|---------|-------------|
| getPhone | phone / number | `+639651150154` | Assigned phone number |
| getPhone | order_no | `O20261120172249330228` | Order number for polling and release |
| getMessage | yzm | `839217` | Verification code; `code=-1` while waiting |
| getMessage | sms | `【XX】验证码 839217` | Full SMS content |
| keywordPhone | order_no | `K20261120172212673647` | Keyword SMS order number |
| keywordMessage | yzm / sms | `839217` | Matched code and SMS content |
| cancelRecv / keywordRelease | order_no | `O...` / `K...` | Release an order; duplicate release is rejected |

**Common request fields**

| Field | APIs | Description |
|-------|------|-------------|
| api | All | Action name |
| user / pass | login (or any API directly) | Dedicated API account/password from User Center, independent of the website login password |
| token | All except login | Token returned by login |
| sid | getPhone / rentPhone | Service ID |
| country | getProjects / keywordPhone | Country code or name |
| kw / service | getProjects | Service keyword, Chinese or English |
| keyword | keyword* | SMS keyword, required for keyword ordering |
| order_no | Poll / release / history | Order number |

### Actions

| Group | api | Main parameters |
|-------|-----|-----------------|
| Account | `login` / `getSummary` | `user`/`pass`; `token` |
| Global countries | `getCountries` | `force=1` |
| Unified services | `getProjects` | `kw`/`service`, `country`, `page`, `page_size` → `sid`/`name`/`country`/`price` |
| SMS | `getPhone` / `getMessage` / `cancelRecv` | `sid`; `order_no` |
| Keyword SMS | `keywordPhone` / `keywordMessage` / `keywordRelease` / `keywordNumbers` / `keywordHistory` | `keyword` required, `country` optional |
| Rentals | `rentOptions` / `rentPhone` / `rentMessage` / `rentRelease` / `rentOrders` | `sid`, `minutes` |
| Email | `emailOffers` / `emailBuy` / `emailSms` | `site`; `site`+`domain`; `order_no` |

### Differences from the open API

- Integration rule: `https://api.psyawqnx.beauty/v2/` is the only public integration endpoint; the original `open/*` rules remain only for legacy systems and are not used by new software.
- Global countries: `getCountries` aggregates and deduplicates without sources.
- Unified services: `getProjects` searches Chinese/English keywords with user pricing.
- Extended capabilities: keyword SMS, rentals and email are native in v2.
- Security: `provider`, `upstream_provider`, `cost`, `cny_cost` are never returned.

---

## Table of Contents

- [v2 Haozhu-compatible access](#v2-haozhu-compatible-access-for-existing-software)
  - [Core field reference](#core-field-reference)
- [0. Preparation](#0-preparation)
- [1. Protocol Specification](#1-protocol-specification)
- [2. Authentication](#2-authentication)
- [3. Quick Start (10 minutes)](#3-quick-start-10-minutes)
- [4. Rate Limiting](#4-rate-limiting)
- [5. Error Codes & Status Semantics](#5-error-codes--status-semantics)
- [6. Response Format](#6-response-format)
- [7. Full Endpoint Reference](#7-full-endpoint-reference)
- [8. Order State Machine](#8-order-state-machine)
- [9. Billing Rules](#9-billing-rules)
- [10. Multi-Language Examples](#10-multi-language-examples)
- [11. Changelog](#11-changelog)

---

## 0. Preparation

1. Register/login at https://www.psyawqnx.beauty
2. Go to **User Center → Account Settings** to view and copy your API Key (32 hex chars)
3. Ensure balance ≥ $0.05 (keyword SMS request fee: $0.02/time)

```bash
export API_KEY='YOUR_API_KEY'
export BASE='https://www.psyawqnx.beauty/web/index.php'
```

---

## 1. Protocol Specification

| Item | Value |
|------|-------|
| Base URL | `https://www.psyawqnx.beauty/web/index.php` |
| Route format | URL param `?r=<controller>/<action>` |
| Data format | JSON response; request params via GET query or POST form-urlencoded |
| Encoding | UTF-8 |
| Timestamps | Unix seconds (Asia/Shanghai) |
| Amounts | String decimal, 2 decimal places |
| HTTP timeout | 15 seconds; up to 30 seconds for upstream latency |
| Retry | Only for idempotent endpoints with `code=429` or 5xx; exponential backoff max 10s |

---

## 2. Authentication

Two methods (both present → `X-API-KEY` takes priority):

| Method | Location | Example |
|--------|----------|---------|
| URL param | `apikey` | `?r=open/balance&apikey=abc123...` |
| Header | `X-API-KEY` | `X-API-KEY: abc123...` |

**Public endpoints (no auth)**: `open/ping`, `open/status`

Auth failure responses:

| Scenario | code | msg |
|----------|------|-----|
| Missing apikey | 401 | Missing apikey (param or X-API-KEY header) |
| Invalid/inactive key | 401 | apikey invalid or deactivated |

---

## 3. Quick Start (10 minutes)

### Step 1: Check provider status (no key needed)

```bash
curl -s "$BASE?r=open/ping"
# {"code":0,"msg":"pong","timestamp":1795100948,"timezone":"Asia/Shanghai","version":"2.0.0"}

curl -s "$BASE?r=open/status"
```

### Step 2: Auth test + balance

```bash
curl -s "$BASE?r=open/balance&apikey=$API_KEY"
# Or via header:
curl -s -H "X-API-KEY: $API_KEY" "$BASE?r=open/balance"
```

### Step 3: Browse available numbers

```bash
# Unified country list (cross-provider dedup with ISO/stock/providers)
curl -s "$BASE?r=open/countries_v2&apikey=$API_KEY"

# Search by service
curl -s -G "$BASE?r=open/projects"   --data-urlencode "kw=WeChat"   --data-urlencode "page_size=10"   --data-urlencode "apikey=$API_KEY"

# Rent options
curl -s "$BASE?r=open/rent_options&apikey=$API_KEY"
```

> ⚠️ The returned `key` field is an HMAC-signed non-forgeable identifier. It must be passed back exactly as-is to `open/number` or `open/rent_number`. Keys expire after ~30 minutes.

### Step 4: Full receive-SMS chain

```bash
# 4.1 Request number
curl -s -X POST "$BASE?r=open/number"   -d "apikey=$API_KEY"   -d "key=REPLACE_WITH_PROJECTS_KEY"
# Returns: {"order_no":"O...","number":"...","amount":0.25,"expire_at":...}

# 4.2 Poll for SMS code (2~3s apart, max 30 times)
curl -s -X POST "$BASE?r=open/sms"   -d "apikey=$API_KEY"   -d "order_no=O..."
# status=wait  → not yet
# status=success → {"sms_code":"839217"}

# 4.3 Release with refund (min 2 min after request)
curl -s -X POST "$BASE?r=open/release"   -d "apikey=$API_KEY"   -d "order_no=O..."
```

### Step 5: Keyword SMS chain

```bash
# 5.1 Request number ($0.02 occupancy fee)
curl -s -X POST "$BASE?r=open/keyword_request"   -d "apikey=$API_KEY"   -d "keyword=verification"   -d "country=usa"   -d "provider=luban"

# 5.2 Pull SMS (keyword-matched, billed per message)
curl -s -X POST "$BASE?r=open/keyword_sms"   -d "apikey=$API_KEY"   -d "order_no=K..."
# status=wait     → no match yet, not billed
# status=success  → matched, billed
# status=blocked  → carrier-blocked, auto-refund

# 5.3 Release
curl -s -X POST "$BASE?r=open/keyword_release"   -d "apikey=$API_KEY"   -d "order_no=K..."
```

### Step 6: Rent chain

```bash
curl -s -X POST "$BASE?r=open/rent_number"   -d "apikey=$API_KEY" -d "key=..." -d "minutes=60"

curl -s -X POST "$BASE?r=open/rent_sms"   -d "apikey=$API_KEY" -d "order_no=RT..."

curl -s -X POST "$BASE?r=open/rent_release"   -d "apikey=$API_KEY" -d "order_no=RT..."
```

### Step 7: Rate limit & remote debug

```bash
curl -s "$BASE?r=open/rate_limit&apikey=$API_KEY"

curl -s -X POST "$BASE?r=open/test&apikey=$API_KEY"   -d "provider=luban" -d "endpoint=getBalance"
```

---

## 4. Rate Limiting

- Default **60 req/min/user** (configurable via `openapi_rate_limit`)
- Sliding window based on `api_logs` table
- **Health check endpoints** (ping/status) not counted
- Over-limit response: HTTP 200 + `code=429`
- Self-serve: `GET open/rate_limit`

---

## 5. Error Codes & Status Semantics

### Top-level code

| code | Meaning | Typical scenario |
|------|---------|------------------|
| 0    | Business success | Most responses |
| 1    | Business logic failure | Missing param, insufficient balance, order released, upstream unavailable |
| 400  | Invalid route | `r=` doesn't match any endpoint |
| 401  | Auth failure | Key missing or invalid |
| 429  | Rate-limit rejection | Over per-minute limit |

### SMS pull states (sms / keyword_sms)

| status | Meaning | Billed? |
|--------|---------|---------|
| `wait` | Upstream hasn't returned match | No |
| `success` | Valid SMS received | Yes |
| `blocked` | Carrier-blocked, platform auto-refunds occupancy fee | No |

### Normal receive-SMS orders (orders table)

| status | Meaning |
|--------|---------|
| 0 | In progress |
| 1 | Code received |
| 2 | Released with refund |
| 3 | Released no-refund (isms rule / upstream returned released) |

### Keyword SMS orders (keyword_orders table)

| status | Meaning |
|--------|---------|
| 0 | In progress (occupied) |
| 1 | Code received (billed per message) |
| 2 | Released |
| 3 | Blocked & refund-closed |

### Rent orders (rent_orders table)

| status | Meaning |
|--------|---------|
| 0 | Renting |
| 1 | Ended |

---

## 6. Response Format

Success:
```json
{"code": 0, "msg": "success", "data": { ... }}
```

Business failure:
```json
{"code": 1, "msg": "Insufficient balance, please recharge", "data": null}
```

Auth/rate-limit failure:
```json
{"code": 401, "msg": "apikey invalid or deactivated", "data": null}
```

---

## 7. Full Endpoint Reference

### Health & Status (no auth)

**GET `open/ping`** — Health probe for monitoring/load balancer.

| Field | Type | Notes |
|-------|------|-------|
| code | int | Always 0 |
| msg | string | Always `"pong"` |
| timestamp | int | Server epoch |
| timezone | string | Asia/Shanghai |
| version | string | API version |

**GET `open/status`** — System overview: providers, capabilities, FX rate, rate limit, refund threshold, keyword fee.

### Status & Capabilities (auth required)

**GET `open/balance`** → `{username, balance}`

**GET `open/providers`** — More detail than status, includes `config_fields` and `supports.multi_acct`.

**GET `open/rate_limit`** → `{limit, window_sec, used, remaining, reset_at}`

### Query

**GET `open/countries`** — Legacy; use `countries_v2`.

**GET `open/countries_v2`** — Unified, dedup, ISO codes, stock flag, provider list. Cached 10 min. Param: `force=1` to refresh.

Per item: `key, name, name_en, name_cn, code (ISO), has_stock, providers[]`

**GET `open/projects`** — Search with paging. Returns HMAC-signed `key` for ordering. Cached 60s. Auto-applies user discount, hides internal cost fields.

| Param | Req | Default | Notes |
|-------|-----|---------|-------|
| kw | No | - | Keyword |
| country | No | - | Exact match |
| page | No | 1 | Page number |
| page_size | No | 10 | Max 50 |
| force | No | - | `1` to bust cache |

**GET `open/rent_options`** — Rent regions & packages.

**GET `open/orders` / `open/rent_orders`** — Paginated order history. Params: `page`, `page_size` (default 20, max 50).

### Receive-SMS Chain

**POST `open/number`**

| Param | Req | Notes |
|-------|-----|-------|
| key | Yes | HMAC from `open/projects` |

Returns: `order_no(O prefix), number, request_id, service_name, amount, expire_at`

**POST `open/sms`**

| Param | Req | Notes |
|-------|-----|-------|
| order_no | Yes | From number response |

Returns: `order_no, status(success/wait), sms_code`

**POST `open/release`** — Release + refund.

| Param | Req | Notes |
|-------|-----|-------|
| order_no | Yes | From number response |

Returns: `order_no, refund, balance, auto(optional)`

**Prerequisites**: code not received + min 120s after request + not released + not isms provider.

### Rent Chain

**POST `open/rent_number`**

| Param | Req | Default | Notes |
|-------|-----|---------|-------|
| key | Yes | - | From rent_options |
| minutes | No | 60 | 30/60/360/720/1440 |

Returns: `order_no(RT), number, rent_id, minutes, amount, expire_at`

**POST `open/rent_sms`** → `{status, list[]}`

**POST `open/rent_release`** — Upstream releases; fee not refunded.

### Keyword SMS Chain

**POST `open/keyword_request`**

| Param | Req | Notes |
|-------|-----|-------|
| keyword | **Yes** | SMS keyword for filtering |
| provider | No | luban/hog/hero (auto-pick if empty) |
| country | No | Country name |
| province | No | Province/region |
| phone | No | Fixed phone (when limit_only=1) |
| limit_only | No | `1` only allow specified phone |
| dup_filter | No | `1` enable upstream dedup |
| card_type | No | Card type filter |

Returns: `order_no(K), phone, keyword, amount` (fixed $0.02)

**POST `open/keyword_sms`**

| Param | Req | Notes |
|-------|-----|-------|
| order_no | Yes | From keyword_request |

Returns: `status, sms_code, content, order_no, amount, billed, list, msg`

Behavior: First match → billed; later polls with same content → wait + billed=false; carrier-blocked → auto-refund.

**POST `open/keyword_release`** — No refund for occupancy fee (except blocked).

**GET `open/keyword_numbers` / `open/keyword_history`** — Active items (≤100) / history (latest 100).

### Batch

**POST `open/batch`**

| Param | Req | Notes |
|-------|-----|-------|
| action | Yes | `number` or `rent_number` |
| items | Yes | Array or JSON string; max 10; each has `key`, rent_number also needs `minutes` |

Returns: `total, success, failed, results[]` (each with `index, code, data/msg`).

### Online Test

**POST `open/test`** — Directly call upstream endpoint, returns raw response + latency.

| Param | Req | Notes |
|-------|-----|-------|
| provider | Yes | luban/hog/hero/smsman/isms |
| endpoint | Yes | Upstream interface name (invalid ones return list of available) |
| others | No | Forwarded to upstream |

Returns: `provider, endpoint, cost_ms, result` (upstream raw).

---

## 8. Order State Machine

### Normal receive-SMS orders

```
  ┌─────────────────────┐    sms_code has value    ┌─────────────────┐
  │  status=0  in-prog   │ ────────────────────────►│ status=1 received│
  └─────────────────────┘                            └─────────────────┘
          │
          │ release (min refund_min sec + sms_code empty)
          ▼
  ┌─────────────────────┐
  │  status=2 released   │
  └─────────────────────┘
          │
          │ isms rule / upstream returned released
          ▼
  ┌─────────────────────┐
  │ status=3 released    │
  │ no-refund            │
  └─────────────────────┘
```

### Keyword SMS orders

```
  ┌─────────────────────┐    keyword match         ┌─────────────────┐
  │ status=0 in-progress│ ────────────────────────►│ status=1 billed  │
  │ ($0.02 occupied)    │                            └─────────────────┘
  └─────────────────────┘
          │
          │ release (no valid code)
          ▼
  ┌─────────────────────┐
  │ status=2 released   │
  └─────────────────────┘  carrier-blocked → status=3 auto-refund
```

### Rent orders

```
  status=0 (renting) ─── release or expire_at ───► status=1 (ended)
```

---

## 9. Billing Rules

### Normal receive-SMS

| Scenario | Fee | Refund |
|----------|-----|--------|
| number success | Discounted price from projects | - |
| release success | - | Full amount (isms excluded) |
| Release threshold | Min 120s after request | - |
| Upstream auto-release | - | Auto-refunded by platform |

### Rent

| Scenario | Fee | Refund |
|----------|-----|--------|
| rent_number success | price × minutes | - |
| rent_release | - | **None** (upstream charged per minute) |

### Keyword SMS

| Scenario | Fee | Refund |
|----------|-----|--------|
| keyword_request | Fixed $0.02 occupancy | - |
| keyword_sms (first match) | Per-message, applied discount | - |
| keyword_sms (duplicate content) | Not billed | - |
| keyword_release | - | **None** (blocked exception: auto-refund) |
| Auto-expire (24h) | - | Auto-refund occupancy |

### Discount mechanism

Each user can have an independent discount rate. `projects`, `number`, `keyword_sms` all use unified `site_price()` for calculation — displayed and charged prices are guaranteed identical.

---

## 10. Multi-Language Examples

### PHP

```php
<?php
$base = 'https://www.psyawqnx.beauty/web/index.php';
$key  = 'YOUR_API_KEY';

$ch = curl_init("$base?r=open/balance&apikey=$key");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $data['data']['balance'];
```

### Python

```python
import requests, time, random

BASE = 'https://www.psyawqnx.beauty/web/index.php'
KEY  = 'YOUR_API_KEY'

def call(ep, method='GET', **kwargs):
    params = {'apikey': KEY}
    params.update(kwargs)
    if method == 'GET':
        r = requests.get(f"{BASE}?r={ep}", params=params, timeout=15)
    else:
        r = requests.post(f"{BASE}?r={ep}", data={**params, **kwargs}, timeout=15)
    body = r.json()
    if body['code'] != 0:
        raise Exception(f"[{r.status_code}] {body['msg']}")
    return body['data']

p = call('open/projects', kw='WeChat', page=1, page_size=5)['list'][0]
order = call('open/number', method='POST', key=p['key'])
for _ in range(30):
    sms = call('open/sms', method='POST', order_no=order['order_no'])
    if sms['status'] == 'success':
        print(f"Code: {sms['sms_code']}"); break
    time.sleep(2 + random.random())
else:
    call('open/release', method='POST', order_no=order['order_no'])
```

### Go

```go
package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "strings"
    "time"
)

const (
    base = "https://www.psyawqnx.beauty/web/index.php"
    key  = "YOUR_API_KEY"
)

func call(ep, method string, body url.Values) (string, error) {
    u := base + "?r=" + ep + "&apikey=" + key
    var req *http.Request
    var err error
    if method == "POST" {
        req, err = http.NewRequest("POST", u, strings.NewReader(body.Encode()))
        req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
    } else {
        req, err = http.NewRequest("GET", u, nil)
    }
    if err != nil { return "", err }
    client := &http.Client{Timeout: 15 * time.Second}
    resp, err := client.Do(req)
    if err != nil { return "", err }
    defer resp.Body.Close()
    b, _ := io.ReadAll(resp.Body)
    return string(b), nil
}

func main() {
    v := url.Values{}
    v.Set("keyword", "verification")
    v.Set("country", "usa")
    v.Set("provider", "luban")
    resp, _ := call("open/keyword_request", "POST", v)
    fmt.Println(resp)
}
```

---

## 11. Changelog

### v2.0.0 (current)

**New endpoints**:
- `open/ping` — no-auth health probe
- `open/status` — no-auth system overview
- `open/providers` — auth-required capability list
- `open/rate_limit` — auth-required rate-limit query
- `open/test` — auth-required direct upstream test

**Improvements**:
- `countries_v2` normalized by country, dedup, ISO/stock/provider
- `projects` returns HMAC-signed keys, hides cost fields, applies user discount
- `KeywordService` independent subsystem, shared billing/status logic with front-end
- Unified `serve()` entry: all endpoints share auth/rate-limit/logging/error handling
- Log params masked: apikey not recorded, key truncated to 24 chars

### v1.0 (legacy, deprecated)

Backend `ApiController` endpoints for internal use only. External integrators must migrate to v2.
