# SMS Receiving Platform · API Integration Guide v2.0

> This document is the complete integration guide for the receiving-platform API v2, covering authentication, protocols, quick start, full endpoint definitions, state machine, and billing rules.
> Last updated: 2026-11-20
> Source of truth: OpenController.php + KeywordService.php

---

## Table of Contents

- [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.
