# StagePay Developer Docs > StagePay is a live global payment gateway for games and apps. Merchants open the StagePay checkout (`https://pay.stagepay.io/request.php`) or create a payment server-to-server (`POST /api/v1/payments`), and receive an HMAC-SHA256 signed callback when the payment succeeds. Key facts: - Payment gateways (PG codes): KCP, TOSS, KAKAOPAY and NAVERPAY (direct KakaoPay / Naver Pay integrations without a PG, KRW only), STRIPE, MYCARD, ENJOYPAY, WEBPAY, EBANX, ONEONE, and USDT (stablecoin). - USDT networks: TRC20 (Tron), ERC20 (Ethereum), BEP20 (BNB Smart Chain), POLYGON (Polygon PoS). StagePay never holds private keys; customers send USDT to the merchant's receiving address and StagePay confirms the transfer on-chain using a unique amount per order. - Merchant callback signature: header `X-StagePay-Signature: v1=`, header `X-StagePay-Timestamp` (unix seconds, reject if older than 300 s), idempotency key `X-StagePay-Delivery`. - Callback retries: 1m, 5m, 15m, 1h, 3h, 6h, 12h, 24h (up to 8 retries, 10 s timeout, any 2xx is success). - REST API v1 authentication: `Authorization: Bearer :`, 600 requests per minute per key, optional IP allowlist and request signing. - Amounts are integers in minor units (`amountMinor`): KRW/JPY/IDR/VND/TWD use 0 decimals, USD/EUR/SGD/MYR/THB/PHP use 2, USDT uses 6. - Transaction states: pending → success | failed | cancelled | expired; success → partial_refunded | refunded. - Settlement v2: per app and currency, fee in basis points + fixed fee + VAT on fee, DAILY/WEEKLY/MONTHLY cycles with T+N hold, minimum payout with carry-forward, dual verification and SHA-256 checksum. - Environments: beta (`https://beta-pay.stagepay.io`) for testing, real (`https://pay.stagepay.io`) for live payments. Languages: [한국어](https://docs.stagepay.io/ko/llms.txt), [English](https://docs.stagepay.io/en/llms.txt), [日本語](https://docs.stagepay.io/ja/llms.txt), [简体中文](https://docs.stagepay.io/zh-CN/llms.txt), [繁體中文](https://docs.stagepay.io/zh-TW/llms.txt). Full text: https://docs.stagepay.io/llms-full.txt (English + Korean), or `//llms-full.txt` per language. Every page is also available as Markdown by appending `.md` to its URL. # Pagination and Errors URL: https://docs.stagepay.io/en/api/conventions > The REST API v1 response formats, pagination parameters, conventions for amounts and dates, and the common error response format. ## Amounts and dates [#amounts-and-dates] | Item | Rule | |---|---| | Amounts | `*Minor` fields are **integers** in the currency's smallest unit. Where values can get large, such as in the settlement API, they are sent as **strings** (`"12000"`). In JavaScript, read them with `BigInt` | | Display amounts | `amount` is a display (major unit) number. Do not use it in calculations | | Currency | Uppercase ISO 4217 or `USDT`. For decimal places, see the [currency table](/en/payments/methods#currencies-and-decimal-places) | | Dates | ISO 8601 (UTC as `Z` or `+00:00`). Query parameters are also sent in ISO 8601 | | Periods | A settlement period is the half-open interval `[periodStart, periodEnd)` | ## Response formats [#response-formats] There are two formats, depending on the endpoint group. ```json title="Transactions, products, apps (v1 format)" { "success": true, "data": [ { "...": "..." } ], "pagination": { "page": 1, "limit": 20, "total": 134, "totalPages": 7 } } ``` ```json title="Settlement (v2 format)" { "data": [ { "...": "..." } ], "total": 12 } ``` ## Pagination [#pagination] | Group | Parameters | Default | Maximum | |---|---|---|---| | Transactions, products, apps | `page` (starting at 1), `limit` | `page=1`, `limit=20` | — | | Settlement batch list | `skip`, `limit` | `skip=0`, `limit=50` | `limit=500` | | Settlement lines | `skip`, `limit` | `skip=0`, `limit=200` | `limit=5000` | An out-of-range `limit` is clamped to a minimum of 1 and the maximum value. Lists are sorted in a stable order (settlement: period start descending → batch number; lines: type → `tid`), so you can read to the end by increasing `skip`. ```js title="Reading all settlement lines" async function* allLines(batchNo, auth) { const limit = 1000; for (let skip = 0; ; skip += limit) { const res = await fetch( `https://api.stagepay.io/api/v1/settlements/${batchNo}/lines?skip=${skip}&limit=${limit}`, { headers: { Authorization: auth } }, ); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const { data, total } = await res.json(); yield* data; if (skip + data.length >= total || data.length === 0) return; } } ``` ## Error format [#error-format] All REST errors use the same JSON format. Stack traces are never included in responses. ```json { "statusCode": 404, "error": "Not Found", "message": "정산 배치를 찾을 수 없습니다.", "requestId": "9b2f0c1e-6c1a-4d3e-9f20-3b1f0a8e7d11", "path": "/api/v1/settlements/STL-20260101-6650f0c2a1b2c3d4e5f60718-KRW-0001", "timestamp": "2026-01-02T03:00:00.000Z" } ``` | Field | Description | |---|---| | `statusCode` | HTTP status code | | `error` | Status name (`Bad Request`, `Unauthorized` …) | | `message` | Human-readable message. For input validation errors, this may be an **array of strings** | | `requestId` | Request correlation ID. Include it when you contact support | | `path` / `timestamp` | Request path (excluding the query) / time of the error | ## Status codes [#status-codes] | HTTP | Meaning | Retry | |---|---|---| | 200 / 201 | Success | — | | 400 | Input error, business rule violation | No — fix the request | | 401 | Authentication failed | No — check your key | | 403 | Insufficient scope, IP not allowed | No | | 404 | Not found, or a resource of another app | No | | 409 | Concurrent modification conflict | Yes — after a short wait | | 429 | Rate limit | Yes — after `Retry-After` | | 5xx | Server error | Yes — with exponential backoff | When retrying a create request (e.g. [creating a payment](/en/payments/create-payment)), send a unique value such as a UUID in the `Idempotency-Key` header. Supporting endpoints process retries with the same key only once. Whether an endpoint supports this is defined by the [Endpoint reference](/en/api/reference); for endpoints that do not support it, first check with a lookup API whether the request was already processed before retrying. # REST API Authentication URL: https://docs.stagepay.io/en/api/overview > The StagePay REST API v1 base URL, issuing API keys and the Bearer authentication format, scopes, the IP allowlist, and rate limits. REST API v1 is used by the **merchant server** to query StagePay data (transactions, products, apps, settlement) and to create payments. | Item | Value | |---|---| | Base URL | `https://api.stagepay.io/api/v1` | | Format | JSON (UTF-8). Settlement lines also support CSV | | Authentication | `Authorization: Bearer :` | | Specification | OpenAPI 3.1 — `https://api.stagepay.io/api/v1/openapi.json` | ## Issuing API keys [#issuing-api-keys] 1. In the console **API keys** menu, create a **New key**. 2. Specify a name, the target app, scopes, and (optionally) an expiry date and allowed IPs. 3. Save the **key ID** (`sk_` + 32 hexadecimal characters) and the **secret** shown right after creation. The secret cannot be viewed again (reissue the key if lost). A key can only access data for the app it was issued for. Requesting another app's resources returns `404`. ## Authentication header [#authentication-header] ```http GET /api/v1/settlements HTTP/1.1 Host: api.stagepay.io Authorization: Bearer sk_1f2e3d4c5b6a79880123456789abcdef:3b9f0c...e1 X-Request-Id: 9b2f0c1e-6c1a-4d3e-9f20-3b1f0a8e7d11 ``` - After `Bearer `, join `keyID:secret` with a colon. - If you send `X-Request-Id` (optional), the same value appears in the response headers and server logs, making it easier to trace when you contact support. If you don't send it, the server generates one and returns it in the response header. - If you need stronger integrity, also use [request signing](/en/api/request-signing). ```bash curl https://api.stagepay.io/api/v1/settlements \ -H "Authorization: Bearer $STAGEPAY_KEY_ID:$STAGEPAY_KEY_SECRET" ``` ## Scopes [#scopes] | Scope | Allows | |---|---| | `read:transactions` | Listing and viewing transactions | | `write:transactions` | [Creating payments](/en/payments/create-payment) | | `read:products` | Viewing products (active products only) | | `write:products` | Creating and updating products | | `read:apps` | Viewing app information | | `read:users` | Viewing user information | | `settlement:read` | [Querying settlement batches and lines](/en/settlement/query) | | `refunds:write` | Calling the [Refund API](/en/refunds/refund-api) with a REST key (not included in `read:all`) | | `read:all` | All `read:*` scopes (excluding settlement) | Grant only the scopes you need. If a scope is missing, `403` is returned. ## Security settings [#security-settings] | Setting | Description | |---|---| | Allowed IPs | If set, only requests from those IPs are allowed. Always set this for production keys | | Expiry date | After it passes, the key status becomes `expired` and `401` is returned | | Rotation | **Rotating** a key in the console issues a new key with the same settings. Disable the old key after deploying | | Usage records | Every call is recorded in the API log (time, endpoint, status code, response time, IP) and can be viewed in the console | ## Rate limits [#rate-limits] The number of requests per minute is limited per key (600 requests/minute by default, adjustable by contract). If exceeded, `429 Too Many Requests` is returned with a `Retry-After` header; some v1 endpoints return `403 Rate limit exceeded` instead. Check the remaining count with the `X-RateLimit-Limit` and `X-RateLimit-Remaining` response headers. ## Authentication errors [#authentication-errors] | HTTP | Message | Cause | |---|---|---| | 401 | `Missing or invalid authorization header` | No header, or the `Bearer ` prefix is missing | | 401 | `Invalid API key format` | Not in `keyID:secret` format | | 401 | `Invalid or expired API key` | Key/secret mismatch, inactive, or expired | | 403 | `Insufficient permissions` | Insufficient scope | | 403 / 429 | `Rate limit exceeded` | Rate limit exceeded | # Endpoint Reference URL: https://docs.stagepay.io/en/api/reference > The StagePay REST API v1 endpoint list — paths, scopes, parameters, and response fields for payment creation, transactions, products, apps, and settlement queries. The base URL for all paths is `https://api.stagepay.io`, and [API key authentication](/en/api/overview) is required. A machine-readable specification is available at `GET /api/v1/openapi.json` (OpenAPI 3.1). | Method | Path | Scope | Description | |---|---|---|---| | `POST` | `/api/v1/payments` | `write:transactions` | [Create a payment](/en/payments/create-payment) | | `GET` | `/api/v1/transactions` | `read:transactions` | List transactions | | `GET` | `/api/v1/transactions/{id}` | `read:transactions` | Transaction details | | `GET` | `/api/v1/products` | `read:products` | List products (active only) | | `GET` | `/api/v1/products/{id}` | `read:products` | Product details | | `GET` | `/api/v1/apps` | `read:apps` | List apps | | `GET` | `/api/v1/apps/{id}` | `read:apps` | App details | | `GET` | `/api/v1/settlements` | `settlement:read` | List settlement batches | | `GET` | `/api/v1/settlements/{batchNo}` | `settlement:read` | Settlement batch details | | `GET` | `/api/v1/settlements/{batchNo}/lines` | `settlement:read` | Settlement lines (JSON or CSV) | The `read:all` scope allows all transaction, product, and app queries (excluding settlement). ## Transactions [#transactions] ### `GET /api/v1/transactions` [#get-apiv1transactions] | Query | Description | |---|---| | `page`, `limit` | Page (default 1, 20) | | `appId` | App filter | | `status` | `pending`, `success`, `failed`, `cancelled`, `expired`, `partial_refunded`, `refunded` | | `startDate`, `endDate` | Creation time range (ISO 8601) | ### Key fields of the transaction object [#key-fields-of-the-transaction-object] | Field | Description | |---|---| | `tid` | StagePay transaction ID | | `appId`, `userId`, `serverId`, `playerId` | Values passed in the request | | `productId`, `productName` | Product | | `status` | Transaction status | | `amount` / `amountMinor` / `currency` | Display amount / settlement amount (minor) / currency | | `refundedAmountMinor`, `refunds[]` | Cumulative refunded amount, refund history `{refundId, amountMinor, reason, at}` | | `pgCode`, `method`, `pgTid` | PG, payment method, PG transaction ID (e.g. `tno` for the refund API) | | `paidAt`, `createdAt` | Payment confirmation time, creation time | | `callback` | Callback status `{status, attempts, lastAttemptAt, lastStatusCode, nextAttemptAt}` | | `crypto` | USDT payment information ([USDT](/en/usdt/overview)) | | `userdata`, `etc`, `uniqueId` | Free-form merchant data | ## Products [#products] ### `GET /api/v1/products` [#get-apiv1products] | Query | Description | |---|---| | `page`, `limit` | Page (default 1, 20) | | `appId` | App filter | The response includes only products with `status=active`. For the checkout's `productId`, use the product ID (the value shown in the console). ## Apps [#apps] ### `GET /api/v1/apps` [#get-apiv1apps] The list of apps the key can access. App secrets (`webhookSecret`, `apiKey`) are not included in the response. ## Settlement [#settlement] Paths, parameters, response fields, and the CSV format are documented in the [Settlement query API](/en/settlement/query). ```bash curl "https://api.stagepay.io/api/v1/settlements?status=APPROVED&from=2026-01-01T00:00:00%2B09:00" \ -H "Authorization: Bearer $STAGEPAY_KEY_ID:$STAGEPAY_KEY_SECRET" ``` The OpenAPI specification (`/api/v1/openapi.json`), generated by the API server, is the authoritative document. If this page differs from it, follow the specification and let us know about the documentation error. # Request Signing (Optional) URL: https://docs.stagepay.io/en/api/request-signing > The optional X-StagePay-Signature request signing specification for preventing REST API body tampering and replay attacks, with Node.js, PHP, and Python examples. In addition to API key authentication, you can attach an HMAC signature to each request to prevent **body tampering** and **replay**. The signature specification is the same HMAC-SHA256 scheme as [callback signatures](/en/webhooks/signature), just in the opposite direction (merchant → StagePay). Request signing is optional. Requests without signature headers are still processed with the API key alone. We recommend it for requests that send sensitive fields, such as a price override (`price`). To make signatures **mandatory**, discuss the key settings with the operations team. ## Specification [#specification] ```text signed_payload = X-StagePay-Timestamp + "." + rawBody X-StagePay-Signature = "v1=" + hex( HMAC-SHA256( key = API key secret, message = signed_payload ) ) ``` | Item | Value | |---|---| | Key | The API key's **secret** (the part after `:` in the Bearer token), UTF-8 | | `rawBody` | The body bytes actually sent. An empty string if there is no body, as with `GET` | | `X-StagePay-Timestamp` | Unix seconds. Must be within 300 seconds of the server time | | Result | 64 lowercase hexadecimal characters, with the `v1=` prefix | You must send **exactly the same bytes** as the string you signed. Send the JSON as a string so that your HTTP client does not re-serialize it after signing. ## Examples [#examples] ```js import crypto from 'node:crypto'; const keyId = process.env.STAGEPAY_KEY_ID; const secret = process.env.STAGEPAY_KEY_SECRET; export async function stagepayPost(path, payload) { const body = JSON.stringify(payload); const ts = Math.floor(Date.now() / 1000).toString(); const sig = 'v1=' + crypto.createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex'); const res = await fetch(`https://api.stagepay.io${path}`, { method: 'POST', headers: { Authorization: `Bearer ${keyId}:${secret}`, 'Content-Type': 'application/json', 'X-StagePay-Timestamp': ts, 'X-StagePay-Signature': sig, }, body, // Exactly the string that was signed }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); return res.json(); } ``` ```php true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $body, CURLOPT_HTTPHEADER => [ "Authorization: Bearer {$keyId}:{$secret}", 'Content-Type: application/json', "X-StagePay-Timestamp: {$ts}", "X-StagePay-Signature: {$sig}", ], ]); $res = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status >= 300) { throw new RuntimeException("StagePay {$status}: {$res}"); } return json_decode($res, true); } ``` ```python import hashlib import hmac import json import os import time import requests KEY_ID = os.environ["STAGEPAY_KEY_ID"] SECRET = os.environ["STAGEPAY_KEY_SECRET"] def stagepay_post(path: str, payload: dict) -> dict: body = json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8") ts = str(int(time.time())) sig = "v1=" + hmac.new(SECRET.encode(), ts.encode() + b"." + body, hashlib.sha256).hexdigest() res = requests.post( f"https://api.stagepay.io{path}", data=body, # Using json= re-serializes the body and breaks the signature headers={ "Authorization": f"Bearer {KEY_ID}:{SECRET}", "Content-Type": "application/json", "X-StagePay-Timestamp": ts, "X-StagePay-Signature": sig, }, timeout=10, ) res.raise_for_status() return res.json() ``` ## Errors [#errors] | HTTP | Cause | |---|---| | 401 | Signature mismatch, missing or malformed timestamp, outside the allowed window (300 seconds) | If your server clock drifts, all signed requests will be rejected. Synchronize the clock with NTP. # Admin Console URL: https://docs.stagepay.io/en/console/admin > Operating procedures in the admin console for StagePay operators — managing merchants, apps, and PGs, resending callbacks, USDT review, and running settlement policies and batches. The admin console is for StagePay operators only. Every change is recorded in the audit log (`audit_logs`) with the actor and the before and after values. ## Merchants and apps [#merchants-and-apps] - Merchant accounts, app creation, and connecting per-app PG credentials (`metas`) - `allowCustomPrice` (allow price overrides), `webhookType` (`GAMEPOT`, etc.), GamePot region and project settings - Reissuing webhook secrets (in response to leaks) ## Transactions and callbacks [#transactions-and-callbacks] - Transaction search and details, state transition history, raw PG logs - Resending failed callbacks (resent with the same `X-StagePay-Delivery` after resetting the attempt count) - Recording the results of refunds that can only be made in the PG console (TOSS, MYCARD, etc.) ## USDT review [#usdt-review] - Lists of `underpaid`, `overpaid`, and `late` transactions and **unmatched deposits** - Manual confirmation (common confirmation path → `payment.succeeded` callback sent once), manual matching, recording returns → [USDT exception handling](/en/usdt/exceptions) ## Settlement operations [#settlement-operations] ### Register policies [#register-policies] Register a [policy](/en/settlement/policy) per app × currency. `effectiveFrom` is required on first registration. Changing a policy increments its version and does not affect batches already created. ### Preview and create [#preview-and-create] Specify a period, check the lines, totals, and warnings with **Preview**, then **Create** (by default, the batch is verified automatically right after creation). When the scheduler (`SETTLEMENT_SCHEDULER=on`) is enabled, batches for the previous period are created and verified automatically every day at 03:00 KST. You can also run the scheduler manually from the admin screen. ### Check the verification result [#check-the-verification-result] If the batch is not `VERIFIED`, check `verification.mismatches`. A mismatch means transaction or refund data changed after the batch was created, so investigate the cause and, if necessary, cancel the batch and create it again. ### Approve (by another admin) [#approve-by-another-admin] An admin other than the creator approves the batch (four-eyes). Verification runs again automatically right before approval. ### Process the payout [#process-the-payout] After the transfer, enter the payout reference number to change the batch to `PAID`. Send the settlement statement CSV to the merchant, or guide the merchant to download it directly from the console or via REST. For detailed status rules, see [Batch status, verification, and approval](/en/settlement/verification). `PAID` batches cannot be reverted. Handle differences found after payout as refund adjustments in the next batch or as a separate settlement. # Merchant Console URL: https://docs.stagepay.io/en/console/merchant > How to manage app settings, webhook secrets, products, API keys, transaction and callback history, logs, and settlement in the merchant console. In the merchant console (`https://stagepay.io/dashboard`), you can view and manage only your own company's apps. Other merchants' apps, transactions, and settlements are not visible. ## Menus [#menus] | Menu | What you can do | |---|---| | **Apps** | View the app ID, callback URLs (`purchaseTestUrl`, `purchaseRealUrl`, `callbackUrl`), custom callback headers, test whitelist (IP, userId) | | **Apps → Webhook secret** | Create and rotate the `whsec_` secret. The full value is shown only once, right after it is created | | **Apps → Payment methods** | View the PGs and payment methods connected to the app, and USDT settings | | **Products** | Product IDs, per-currency prices, purchase restrictions (one-time only, limited period, etc.), active status | | **API keys** | Issue, rotate, and disable REST API keys; set scopes, allowed IPs, and expiry dates; view usage records | | **Transactions** | Search transactions (tid, userId, status, period); view details (PG information, refund history, USDT chain information) | | **Transaction details → Callbacks** | Callback delivery history (request/response, status code, duration); **resend** failed callbacks | | **Logs** | Search payment request rejection reasons, PG communication, and callback logs by `requestId` or `tid` | | **Settlement** | Settlement batch list and details, line queries, **CSV download** | ## Settlement screen [#settlement-screen] - You can see batches of your apps in every status, including `DRAFT` and `CANCELLED` (the REST API excludes internal states). - In the batch details, review the policy snapshot, totals, verification results, status history, and the per-line calculation basis (`formula`). - The **CSV download** button downloads a file in the same format as REST's `Accept: text/csv` → [CSV format](/en/settlement/query#csv-download). - Only StagePay operators can change policies or create, approve, and process payouts for batches. If you have a dispute, contact us with the batch number. ## Recommended practices [#recommended-practices] - Store webhook secrets and API keys only in your server's secret store (environment variables, Secret Manager). - When the person in charge changes, rotate the API keys and disable the old ones. - When you receive a callback failure alert, check the response code and body under **Transaction details → Callbacks**, fix the cause, and resend → [Troubleshooting](/en/help/troubleshooting). # Core Concepts URL: https://docs.stagepay.io/en/getting-started/concepts > The concepts you need to integrate StagePay, including apps (merchants), the tid transaction ID, the transaction state machine, minor-unit amounts, and beta/real environments. ## Apps (merchants) [#apps-merchants] In StagePay, the unit that accepts payments is an **app**. Usually one game or one service is one app. Each app has its own settings: | Item | Description | |---|---| | `appId` | App identifier (a 24-character hexadecimal string, e.g. `6650f0c2a1b2c3d4e5f60718`). Used when opening the checkout | | Products | Price per `productId` (per currency). **The payment amount is always determined by the product price registered on the server** | | PG connections | The PGs and payment methods the app uses, plus PG credentials | | Callback URLs | The merchant server addresses that receive payment completion notices — `purchaseRealUrl` (production), `purchaseTestUrl` (test), `callbackUrl` (shared fallback) | | `webhookSecret` | HMAC key for callback signatures (`whsec_` + 64 hexadecimal characters). Created and reissued in the console | | `apiKey` | App API key for v1 compatibility. Used in the callback's `Authorization: Bearer` header and in the refund API's `X-Api-Key` | | REST API keys | Keys for REST API v1 (`sk_...` key ID + secret). Supports scopes, IP allowlist, and expiry | | `allowCustomPrice` | Whether price overrides are allowed (default `false`) | `webhookSecret` (callback signature verification), the app `apiKey` (refund API, v1 compatibility), and REST API keys (`keyId:secret`) serve different purposes. Keep all of them on the server only, and never put them in a client (game client, app, or browser). ## Transactions and transaction IDs (tid) [#transactions-and-transaction-ids-tid] Each payment request is one **transaction**, identified by a unique ID issued by StagePay, the **`tid`**. - Example format: `KCP-20260101090000123456-a1b2c3-9f8e7d6c` — a string that starts with the PG code. The format may change, so store it as an **opaque string** (we recommend allowing up to 128 characters). - Starting with v2, a transaction is **created first in the `pending` state at the time of the payment request**. You can also look up incomplete transactions in the console and the REST API. - The ID issued by the PG is stored separately as `pgTid` (e.g. KCP `tno`, Stripe PaymentIntent ID). You may need it when calling the refund API. - The v1 callback field `orderId` has the same value as `tid`. ## Transaction state machine [#transaction-state-machine] ```text ┌──────────► failed │ pending ───┼──────────► cancelled │ ├──────────► expired │ └──────────► success ──┬──► partial_refunded ──► refunded └──────────────────────► refunded ``` | State | Meaning | Callback | |---|---|---| | `pending` | Payment request created, waiting for the customer to pay | — | | `success` | PG server verification complete, payment confirmed | `payment.succeeded` | | `failed` | Payment failed (declined, error) | — | | `cancelled` | Cancelled by the customer | — | | `expired` | Payment validity period elapsed (USDT, etc.) | — | | `partial_refunded` | Partially refunded | `payment.refunded` | | `refunded` | Fully refunded | `payment.refunded` | A state transition succeeds **atomically, exactly once** in the database (even if `pending → success` is attempted twice concurrently, it is applied only once). Callbacks are sent only when a transition actually occurs, so a re-sent or forged-and-replayed PG webhook never produces a duplicate grant callback. ## Amounts: minor units [#amounts-minor-units] The amount StagePay uses for settlement and aggregation is `amountMinor`, an **integer in the smallest currency unit (minor unit)**. This eliminates floating-point calculation errors. | Currency | Decimal places (exponent) | Display amount → `amountMinor` | |---|---|---| | KRW, JPY, IDR, VND, TWD, CLP | 0 | ₩12,000 → `12000` | | USD, EUR, SGD, MYR, THB, PHP, BRL, MXN, etc. | 2 | $9.99 → `999` | | USDT | 6 | 10.5 USDT → `10500000` | - `amount` is the major-unit value for display (e.g. `9.99`) and is sent alongside for v1 compatibility. **Use `amountMinor` and `currency` for comparing and storing amounts.** - TWD has 2 decimal places under ISO 4217, but StagePay treats it as 0 decimal places in line with PG practice. - Never add amounts in different currencies. Aggregation and settlement are always done per currency. ```ts title="Example major ↔ minor conversion (TypeScript)" const EXPONENT: Record = { KRW: 0, JPY: 0, TWD: 0, USD: 2, EUR: 2, USDT: 6 }; // Convert via strings to avoid float errors export function toMinor(amount: string, currency: string): bigint { const exp = EXPONENT[currency] ?? 2; const [int, frac = ''] = amount.split('.'); return BigInt(int + frac.padEnd(exp, '0').slice(0, exp)); } toMinor('9.99', 'USD'); // 999n toMinor('12000', 'KRW'); // 12000n ``` ## Environments: beta and real [#environments-beta-and-real] | Environment | Checkout | Purpose | |---|---|---| | **beta** | `https://beta-pay.stagepay.io` | Integration development and testing. Uses PG test (sandbox) credentials | | **real** | `https://pay.stagepay.io` | Production. Real payments | The callback URL is chosen based on the environment. - Default: `purchaseTestUrl` in the test environment, `purchaseRealUrl` in production (falling back to `callbackUrl` if not set). - If you register a **test whitelist** (IP or userId) for an app, payment callbacks for those users go to `purchaseTestUrl` even in production. In that case, `environment` in the callback body is `test`. Use this for QA in production. ## Request tracing: requestId [#request-tracing-requestid] Every request carries a correlation ID, `requestId`. If you send the `X-Request-Id` request header, that value is used; otherwise StagePay generates one and returns it in the `X-Request-Id` response header. The same value is propagated to PG calls and merchant callbacks, so including both the `tid` and the `requestId` when you contact support lets us trace the issue quickly. For details, see [Debugging with logs and requestId](/en/operations/logging). # Introduction URL: https://docs.stagepay.io/en/getting-started/introduction > What StagePay is, the problems it solves, its components, and what it supports. ## What is StagePay? [#what-is-stagepay] StagePay is a **global payment gateway** for game and app businesses. A single integration lets you accept payments through country-specific PGs (payment gateways) as well as USDT stablecoin payments, and payment results are delivered to the merchant server as **signed callbacks**. What StagePay handles for you: - **Absorbing differences between PG integrations** — StagePay adapts to each PG's checkout, signature, and webhook specifications, including KCP, Toss, Stripe, MyCard, and EBANX. Merchants implement only the StagePay specification. - **Verifying payment confirmation** — A result sent by a PG is confirmed as successful only after PG server verification (signature check or re-confirmation via the PG's lookup API). A payment is never marked successful based on browser redirect values alone. - **Preventing duplicate grants** — A transaction state transition happens atomically, exactly once, and a merchant callback is sent only when a transition actually occurs. Even if a PG sends its webhook multiple times, there is only one callback (with the same Delivery ID on retries). - **Confirming USDT deposits** — Without holding private keys on the server, StagePay confirms deposits to the merchant's receiving address on-chain and matches them to orders. - **Settlement** — StagePay creates settlement batches according to fee policies per app and currency, and verifies them with double calculation and checksums. ## Components [#components] | Component | Address | Role | |---|---|---| | Checkout (pay) | `https://pay.stagepay.io` | Payment request (`/request`), payment method selection (`/inapp`), result page (`/return`), refunds (`/refund`) | | Checkout beta | `https://beta-pay.stagepay.io` | Test environment | | REST API v1 | `https://api.stagepay.io/api/v1` | Server-to-server payment creation; transaction, product, and settlement queries | | Merchant console | `https://stagepay.io/dashboard` | App settings, API keys, webhook secrets, transaction and log queries, settlement reports | | Developer docs | `https://docs.stagepay.io` | These docs | ## Supported PGs and payment methods [#supported-pgs-and-payment-methods] | PG code | Main regions | Key payment methods | |---|---|---| | `KCP` | South Korea | Credit card, bank transfer, virtual account, mobile phone billing, easy pay | | `TOSS` | South Korea | Card, quick bank transfer, easy pay (Toss Pay, etc.), mobile phone billing, virtual account | | `STRIPE` | Global | Card, wallets such as Apple Pay / Google Pay | | `MYCARD` | Taiwan, Hong Kong, Southeast Asia | MyCard points, local payment methods | | `ENJOYPAY` | Brazil and other global markets | PIX, card, bank transfer, e-wallets | | `WEBPAY` | Global | Card | | `EBANX` | Latin America | Card, PIX, Boleto, OXXO, and other local payment methods | | `ONEONE` | Southeast Asia | Local payment methods | | `USDT` | Global | USDT — `TRC20`, `ERC20`, `BEP20`, `POLYGON` | See [Payment methods and country support](/en/payments/methods) for payment method codes and currencies per PG. The payment methods actually available depend on the PG contracts connected to your app. ## Next steps [#next-steps] # Quickstart (5-Minute Integration) URL: https://docs.stagepay.io/en/getting-started/quickstart > Follow five steps for a minimal integration — issue an API key and webhook secret, open the checkout, verify the callback signature, and test in the beta environment. By the end of this guide, you will have completed one payment in the beta environment and received a signature-verified callback on your merchant server. ### Check your app and issue keys [#check-your-app-and-issue-keys] Sign in to the [merchant console](https://stagepay.io/dashboard) and open the app you want to integrate from the **Apps** menu. 1. Copy the **App ID** (`appId`). 2. Create a secret on the **Webhook secret** tab. The full `whsec_` value is shown only once, right after it is created, so store it in your server's secret store. 3. Enter your merchant server address in **Callback URL**. You can start by filling in only `purchaseTestUrl` (test). Example: `https://game.example.com/stagepay/callback` 4. In the **Products** menu, check the `productId` and per-currency prices of the products you will sell. 5. (Optional) To use the server-to-server API, issue a REST API key from the **API keys** menu. ### Open the checkout [#open-the-checkout] The simplest approach is to open the checkout URL. When the user taps the buy button, build the URL on your **merchant server** and send it to the client. ```text https://beta-pay.stagepay.io/request?appId=6650f0c2a1b2c3d4e5f60718&pg=KCP&method=card&productId=gem_100¤cy=KRW&userId=user_42&serverId=s1&playerId=hero42&language=ko ``` ```ts title="server.ts — Building the checkout URL (Node.js)" const PAY_BASE = process.env.STAGEPAY_PAY_URL ?? 'https://beta-pay.stagepay.io'; export function checkoutUrl(params: { productId: string; userId: string; pg?: string; method?: string; currency: string; serverId?: string; playerId?: string; }) { const url = new URL('/request', PAY_BASE); url.searchParams.set('appId', process.env.STAGEPAY_APP_ID!); for (const [k, v] of Object.entries(params)) if (v) url.searchParams.set(k, v); return url.toString(); } ``` If you omit `pg` and `method` and open `/inapp`, StagePay shows a payment method selection screen. For the full list of parameters, see [Opening the checkout](/en/payments/checkout). ### Receive the callback and verify the signature [#receive-the-callback-and-verify-the-signature] When a payment is confirmed, StagePay sends a `POST` request to your callback URL. Verify the signature against the **raw body**, then grant the item and respond with `200`. ```js title="callback.mjs (Node.js + Express)" import crypto from 'node:crypto'; import express from 'express'; const app = express(); const SECRET = process.env.STAGEPAY_WEBHOOK_SECRET; // whsec_... app.post('/stagepay/callback', express.raw({ type: 'application/json' }), async (req, res) => { const raw = req.body.toString('utf8'); const ts = req.get('X-StagePay-Timestamp') ?? ''; const sig = req.get('X-StagePay-Signature') ?? ''; const expected = 'v1=' + crypto.createHmac('sha256', SECRET).update(`${ts}.${raw}`).digest('hex'); const fresh = Math.abs(Date.now() / 1000 - Number(ts)) <= 300; const valid = fresh && sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected)); if (!valid) return res.status(401).send('invalid signature'); const event = JSON.parse(raw); const deliveryId = req.get('X-StagePay-Delivery'); // TODO: check for duplicates by deliveryId or tid, then grant (idempotent handling) console.log(event.event, event.tid, event.amountMinor, event.currency, deliveryId); res.status(200).send('ok'); }); app.listen(3000); ``` Examples in other languages (PHP, Python, Go, Java) and test vectors are in [Signature verification](/en/webhooks/signature). ### Test in the beta environment [#test-in-the-beta-environment] 1. Open the beta checkout URL from step 2 in a browser. 2. Pay with a PG test payment method (e.g. the Stripe test card `4242 4242 4242 4242`). For PG-specific testing instructions, see [Testing](/en/payments/testing). 3. Confirm that the `payment.succeeded` callback appears in your merchant server logs. 4. In the console **Transactions** menu, confirm that the transaction status is `success` and the callback status is `delivered`. Callbacks can only be sent to an HTTPS address reachable from the internet. During local development, use a tunneling tool (e.g. Cloudflare Tunnel, ngrok) to create a temporary public address and register it as `purchaseTestUrl`. ### Go live [#go-live] When testing is complete, follow the [Go-live checklist](/en/operations/go-live) to register `purchaseRealUrl`, connect production PG credentials, and change the checkout address to `https://pay.stagepay.io`. ## What to read next [#what-to-read-next] - [Webhook events and payloads](/en/webhooks/overview) — All callback fields - [Retries and idempotency](/en/webhooks/retries) — Preventing duplicate grants - [In-app/WebView integration](/en/payments/in-app-webview) — Showing the checkout in a mobile game # Changes from v1 to v2 URL: https://docs.stagepay.io/en/help/changelog > What changed in StagePay v2 — callback signatures, transaction states, amount fields, removed PGs, USDT, settlement v2, and the REST API — and how to migrate. ## Summary [#summary] | Area | v1 | v2 | |---|---|---| | Callback verification | `Authorization: Bearer ` | **HMAC signature** `X-StagePay-Signature` + timestamp (Bearer kept as deprecated) | | Callback events | Payment completion only | `payment.succeeded`, `payment.refunded` | | Callback retries | Limited | Up to 8 times at intervals from 1 minute to 24 hours + manual resend, fixed Delivery ID | | Callback transaction status | `status` (`completed`) | `transactionStatus` (`success`, `partial_refunded`, `refunded`) added. `status` keeps its v1 value | | Amounts | `amount` (floating point) | `amountMinor` (integer minor unit) added, used for settlement | | Transaction creation | Saved only on success | Created first as `pending` at the time of the payment request | | Payment creation | Checkout URL only | Server-to-server `POST /api/v1/payments` added | | Price override | `price` parameter | `allowCustomPrice` + signature (`priceSig`) required | | PGs | Included KAKAO, GASH, XSOLLA, GOC, RAZER, UNIPIN, PAYPAL | Those PGs removed, **USDT** added | | Settlement | Simple aggregation | Policy snapshots, transaction locking, three-way verification, four-eyes approval, carry-forward, refund adjustments, REST and CSV | | Payment URLs | `/request.php`, `/webhook.php` … | Extensionless paths `/request`, `/checkout`, `/webhook` … (old `.php` URLs keep working) | | REST API | Scopes only partially enforced | Scopes, IP allowlist, rate limits, and ownership checks enforced; `settlement:read` added | | Logs | Scattered | Unified logs based on `requestId`, with secret masking | ## Migration [#migration] ### Add callback signature verification [#add-callback-signature-verification] Issue a webhook secret in the console and implement [signature verification](/en/webhooks/signature). Once verification is deployed, you can remove the existing Bearer check. ### Evaluate events and status [#evaluate-events-and-status] Existing `status === 'completed'` checks keep working (`status` in `payment.succeeded` is still `"completed"`). However, in v2 refund callbacks (`payment.refunded`) also arrive at the same URL, so change your code to tell events apart with `event` and read the transaction status from `transactionStatus`. If you will not handle `payment.refunded`, just respond with `200` (if you do not respond, it will be retried). ### Use amountMinor [#use-amountminor] Use `amountMinor` (integer) for amount comparisons and accounting. The uppercase aliases (`userID`, `orderID`, etc.) are still provided, but new code should use the camelCase fields. ### Idempotency [#idempotency] Store `X-StagePay-Delivery` as an idempotency key → [Retries and idempotency](/en/webhooks/retries). ### Replace removed PGs [#replace-removed-pgs] Apps that used removed PGs should switch to KCP/TOSS (including Korean easy pay methods), STRIPE, MYCARD, EBANX, and so on → [Payment method support table](/en/payments/methods). ## What remains compatible [#what-remains-compatible] - The URL parameters of the `request.php` / `inapp.php` checkout are unchanged. - The v1 fields in the callback body (`orderId`, `userId`, `productName`, `status`, etc.) are still included. However, `originalPayload` now contains sanitized payment method details with secrets excluded, instead of the PG's original result. - The `return.php` message format and the iOS/Android bridge name (`GamePotStagePay`) are the same. - The request format of the refund API (`refund.php`) is the same. # Troubleshooting URL: https://docs.stagepay.io/en/help/troubleshooting > Causes and fixes for common problems, including missing callbacks, signature mismatches, checkout errors, unconfirmed USDT payments, REST API 401/403 errors, and settlement amount discrepancies. ## Callbacks [#callbacks] 1. Check the delivery history in the console under **Transaction details → Callbacks**. If there is no history, the transaction is not yet `success` (no callbacks are sent for failures, cancellations, or expirations). 2. If the status is `failed` and the error is `callback url not configured`, the app's callback URL is empty or is not `http(s)`. 3. If there is a response code, your merchant server sent a non-2xx response. 3xx redirects are not followed. 4. If there is no response code and it timed out, your server did not respond within 10 seconds. Process the grant asynchronously and respond with `200` first. 5. Payments matching the test whitelist go to `purchaseTestUrl`. - Make sure you are not signing JSON that you parsed and re-serialized. You must use the **raw bytes**. - The key is the **full** string, including the `whsec_` prefix. - The signed string is `timestamp + "." + body`. Make sure you have not left out the `.` separator. - The header value includes the `v1=` prefix. - If you rotated the secret, confirm that the new secret has been deployed to your server. - Validate your implementation against the [test vectors](/en/webhooks/signature#test-vectors) first. Your merchant server clock has most likely drifted. Check your NTP synchronization. Resent callbacks are also signed with a new timestamp at send time. This is normal (retries, resends, lost responses). Ignore duplicates using `X-StagePay-Delivery` → [Retries and idempotency](/en/webhooks/retries). ## Checkout [#checkout] The `productId` does not exist, or the product has no price in the requested `currency`. Check the per-currency prices under **Products** in the console. The PG is not connected to the app, or it was removed in v2 → [Payment method support table](/en/payments/methods). Implement your WebView URL handler so that external schemes such as `intent://` and `kakaotalk://` are passed to the OS → [WebView configuration tips](/en/payments/in-app-webview#webview-configuration-tips). Check that the `/return` message channel is correct (React Native, the iOS handler name `GamePotStagePay`, the Android interface name). Grants are based on the server callback anyway, so it is safer to have the client query your server for the order status. ## USDT [#usdt] Check that the amount is exact to 6 decimal places, that the network is correct, and that the funds were sent within the validity period. If it is waiting for confirmations, the status is `detected`. For anything else, see [USDT exception handling](/en/usdt/exceptions). ## REST API [#rest-api] Check that the header is in the format `Authorization: Bearer keyID:secret`, separated by a single colon. The key lacks a required scope. The settlement API requires `settlement:read` separately (it is not included in `read:all`). The batch is `DRAFT` or `CANCELLED`, or it belongs to an app not linked to the key. The console **Settlement** screen shows batches in every status. ## Settlement [#settlement] Check each line's `formula`. Common causes: period boundaries (`[start, end)` in the policy timezone), rounding (per line, half away from zero), refunds after the end of the period (adjustment lines in the next batch), inclusion of unsettled transactions from earlier periods, and carried-forward amounts (`carriedInMinor`) → [Settlement calculation](/en/settlement/calculation). The net amount was negative or below the minimum payout, so it was carried forward to the next batch. It will be reflected in the next batch's `carriedInMinor`. ## When contacting support [#when-contacting-support] Please include the following: app ID, `tid`, `requestId` (or `X-Request-Id`), time of occurrence (including timezone), `X-StagePay-Delivery` for callback issues, and the batch number for settlement issues. # StagePay Developer Docs URL: https://docs.stagepay.io/en > Integration guide for StagePay, the global payment gateway for games and apps. Covers opening the checkout, verifying signed callbacks, USDT payments, refunds, the REST API, and settlement. StagePay is a **global payment gateway** for games and apps. With a single checkout URL (or a single server-to-server API call), merchants can accept payments through multiple PGs such as KCP, Toss, Stripe, MyCard, and EBANX, as well as USDT (stablecoin) payments. When a payment is confirmed, the merchant receives an **HMAC-SHA256-signed callback** and grants the item. These docs cover StagePay v2 (signed callbacks, pending transactions, USDT, settlement v2). If you are migrating from v1, first review the **Summary** and **Migration** sections of the [Changelog](/en/help/changelog). ## Where to start [#where-to-start] ## Integration flow at a glance [#integration-flow-at-a-glance] ```text Customer (game/app) Merchant server StagePay PG / blockchain │ Buy button │ │ │ │────────────────────▶│ Build checkout URL │ │ │◀────────────────────│ (or POST /api/v1/payments) │ │ │ Open checkout ─────────────────────────────────▶│ Create pending transaction │ │ │ │──── Payment request ─────────▶│ │ Pay ◀──────────────────────────────────────────────────────────────────────────▶│ │ │ │◀─── Result / server check ────│ │ │◀── Signed callback (POST) ─│ Transition to success (once) │ │ │── 2xx response ───────────▶│ │ │ /return result ◀─────────────────────────────│ (sent to app via postMessage) │ │ │ Grant item │ │ ``` - **The callback (server-to-server) is the source of truth for payment confirmation.** Browser redirects and `/return` results are for display only and must not be used as the basis for granting items. - Callbacks are retried up to 8 times until a 2xx response is received. Callbacks for the same payment share the same `X-StagePay-Delivery` value, so you can prevent duplicate grants. ## Supported scope [#supported-scope] | Category | Details | |---|---| | PGs | KCP, TOSS, STRIPE, MYCARD, ENJOYPAY, WEBPAY, EBANX, ONEONE | | Cryptocurrency | USDT — TRC20, ERC20, BEP20, POLYGON | | Payment currencies | KRW, USD, JPY, TWD, EUR, BRL, MXN, and more (varies by PG; see [Payment methods and country support](/en/payments/methods)) | | Integration options | Checkout URL, server-to-server payment creation API, in-app WebView (React Native · iOS · Android · Unity) | | Operations tools | Merchant console (transactions, logs, API keys, webhook secrets), REST API v1, settlement reports (CSV) | ## Using these docs with AI agents [#using-these-docs-with-ai-agents] These docs are also available in LLM-friendly formats. - [`/llms.txt`](/llms.txt) — Table of contents for all docs plus a summary of key facts - [`/llms-full.txt`](/llms-full.txt) — Full text of all docs (English + Korean) - Append `.md` to any page URL to get the raw Markdown. Example: `/en/getting-started/quickstart.md` # Operational Alerts (NAVER WORKS) URL: https://docs.stagepay.io/en/operations/alerts > How to receive payment problems and server errors in a NAVER WORKS bot message room. Covers Developer Console setup, environment variables, the conditions that trigger alerts, severity and grouping rules, and how to test. When StagePay detects a situation where a payment may have gone wrong (amount mismatch, suspected forged webhook, final merchant callback failure, refund failure, settlement verification mismatch, server 5xx, and so on), it sends an alert to the operations message room through a **NAVER WORKS Bot**. - Alerts are first recorded in `alert_events` (outbox), and pay's `alert-worker` sends them to NAVER WORKS. Payment processing does not stop even if recording an alert fails. - The same problem is grouped into a single alert for a set period (10 minutes by default). When the window ends, one summary message ("최근 10분간 같은 문제 N건 추가" — "N more of the same problem in the last 10 minutes") is sent. - Alerts contain **identifiers only**, such as transaction number, app, PG, and amount. Card details, tokens, and secrets are never included, and email addresses keep only their first character. - Under **Payments → Payment alerts** in the console, you can view the connection status, last delivery, failure count, and alert log, and send a test alert. ## 1. Developer Console setup [#1-developer-console-setup] Perform these steps with an administrator account in the NAVER WORKS [Developer Console](https://dev.worksmobile.com/). ### Create an app [#create-an-app] Create an app under **API 2.0 → Add app** and note its **Client ID** and **Client Secret**. Add `bot` (or `bot.message`) to the OAuth Scopes. ### Service account and private key [#service-account-and-private-key] On the same app screen, issue a **Service Account** (in the form `xxxx.serviceaccount@domain`). Download the **Private Key**. The private key can be downloaded only once, so keep it in a secure secret store. ### Register a bot [#register-a-bot] Create a bot under **Bot → Register** and note its **Bot ID** (numeric). In the admin screen, add the bot to your company (domain). ### Invite the bot to the message room [#invite-the-bot-to-the-message-room] Invite the bot to the message room that will receive alerts. Copy the **Channel ID** from the message room's drawer menu. Messages are rejected if the bot is not in the room. To send alerts 1:1 to a single person instead of a message room, use a user ID instead of a channel ID. ## 2. Environment variables [#2-environment-variables] Set these on the pay container (alert worker). Always inject `NAVERWORKS_CLIENT_SECRET` and `NAVERWORKS_PRIVATE_KEY` as Secrets, and never commit them to the repository. | Variable | Description | Default | |---|---|---| | `ALERT_ENABLED` | Alerts are sent only when `true` | `false` | | `NAVERWORKS_CLIENT_ID` | App Client ID | | | `NAVERWORKS_CLIENT_SECRET` | App Client Secret (**secret**) | | | `NAVERWORKS_SERVICE_ACCOUNT` | Service account ID | | | `NAVERWORKS_PRIVATE_KEY` | Private key as raw PEM or base64(PEM) (**secret**). To provide it as a file, use `NAVERWORKS_PRIVATE_KEY_FILE` | | | `NAVERWORKS_BOT_ID` | Bot ID | | | `NAVERWORKS_CHANNEL_ID` | Message room channel ID (if absent, sends 1:1 to `NAVERWORKS_USER_ID`) | | | `NAVERWORKS_AUTH_URL` | Token issuance URL | `https://auth.worksmobile.com/oauth2/v2.0/token` | | `NAVERWORKS_API_URL` | API base URL | `https://www.worksapis.com/v1.0` | | `ALERT_MIN_SEVERITY` | Send only alerts at or above this severity (`info` / `warning` / `critical`) | `warning` | | `ALERT_THROTTLE_SECONDS` | Grouping window for the same problem (seconds). Set the same value on api as well | `600` | | `ALERT_CONSOLE_URL` | Console address for the "콘솔에서 보기" (View in console) button (e.g. `https://console.stagepay.io`). If absent, a plain text message without a button is sent | | If `ALERT_ENABLED` is off or a required value is missing, alerts are recorded as **Skipped** and the worker logs this only once. The service keeps running normally. Authentication uses the NAVER WORKS service account method. The worker signs a JWT (RS256, `iss` = Client ID, `sub` = service account, valid for 1 hour) with the private key to obtain an Access Token, and reuses it until 5 minutes before it expires. The token is stored encrypted with `APP_KEY`. ## 3. When alerts are sent [#3-when-alerts-are-sent] | Category | Situation | Severity | |---|---|---| | Payment | The amount or currency confirmed by the PG differs from the stored transaction (webhook verification or confirmation step) | Critical | | Payment | PG verification completed, but there is no transaction to confirm | Warning | | Webhook | Signature/hash mismatch, identifier mismatch, or a webhook arriving via a different PG's path (suspected forgery) | Warning | | PG | PG query or approval API failure, verification credentials not configured | Warning | | Merchant callback | Every attempt in the retry schedule (1 minute … 24 hours, 9 in total) failed, or there is no callback URL | Critical | | Refund | The PG rejected the refund, or the PG call failed | Warning | | Refund | The PG refunded, but updating the transaction failed (`REFUND_RECORD_FAILED`), or an exception occurred during refund processing | Critical | | Settlement | Three-way verification mismatch, VERIFIED → DRAFT on re-verification, automatic generation (scheduler) failure | Critical | | USDT | Deposit after expiry, underpayment, or overpayment (needs review), deposit cancelled by a chain reorganization, a spike in RPC communication errors, missing chain query configuration, stalled manual processing requests | Warning | | System | Unhandled exceptions/5xx in pay and api (grouped by path + exception type, including REST `POST /api/v1/payments`), and other error logs | Critical/Warning | USDT items and other error logs are found by the alert worker's **detectors**, which scan logs and DB state every 30 seconds. The same state is alerted only once. ## 4. Message format [#4-message-format] ```text [치명] 가맹점 콜백 최종 실패 가맹점 서버로 콜백(payment.succeeded)을 9회 보냈지만 모두 실패해 재시도를 멈췄습니다 (마지막 응답 HTTP 500). … · 거래: STAGEPAY-20261128082112-5fe83e-0e03fff4 · 앱: 데모 게임 (6b0a53f0c8612d11b0002af2) · PG: STRIPE · 금액: 9.99 USD · HTTP 상태: 500 · 전송 ID: c622b821-af88-4236-ae13-62cae3d64be1 · 발생: 2026-11-28 17:21:13 KST · 요청 ID: 1572c85b2fb5520a64bab463f70a8219 ``` - Bot messages are written in Korean. The example above is a final merchant callback failure alert listing the transaction, app, PG, amount, HTTP status, delivery ID, time of occurrence, and request ID. - The prefix depends on severity: `[치명]` / `[경고]` / `[정보]` (critical / warning / info). - If `ALERT_CONSOLE_URL` is set, a "콘솔에서 보기" (View in console) button is attached (the body of a button message is truncated to 1,000 characters, and a text message to 2,000 characters). - Amounts are shown with the number of decimal places of the transaction currency. ## 5. Severity and grouping [#5-severity-and-grouping] - Alerts below `ALERT_MIN_SEVERITY` (default `warning`) are not sent and are recorded as skipped. Test alerts are the exception. - For the same grouping key (e.g. `webhook.pg_mismatch:STRIPE`, `callback.exhausted:`), only the first alert is sent during `ALERT_THROTTLE_SECONDS`, and the rest are only counted. When the window ends, one summary is sent. - To stay within NAVER WORKS rate limits (60 calls per minute and 5 concurrent, free plan), at most 50 alerts per minute are sent. On a 429 response, the worker waits for `rateLimit-reset` seconds and then resends. On 5xx or network errors, it retries up to 8 times with a delay starting at 15 seconds and doubling each time (up to 30 minutes), then records the alert as failed. - The alert log is retained for 90 days. ## 6. Testing [#6-testing] In the console, go to **Payments → Payment alerts** and click **Send test alert**. A `[정보] 테스트 알림` ([Info] Test alert) message should arrive in the message room. After a few seconds, check that its status in the list is **Sent**. | Status on screen | What to check | |---|---| | Off | `ALERT_ENABLED=true` | | Setup required | The missing environment variables shown on the card | | Worker not responding | The `alert-worker` process in the pay container (`supervisorctl status`) | | Delivery failed `token_http_401` | That the Client ID/Secret, service account, and private key belong together | | Delivery failed `message_http_403` | Whether the bot has been invited to the message room, and the channel ID | You can also check via GraphQL (operators only): `alertStatus`, `alertEvents(filter, page, limit)`, `sendTestAlert`. # Go-Live Checklist URL: https://docs.stagepay.io/en/operations/go-live > A checklist of callback URLs, PG credentials, checkout addresses, security, and settlement items to verify when moving to production after beta testing. ## Before switching (verify in beta) [#before-switching-verify-in-beta] - [ ] All items in the [testing checklist](/en/payments/testing#checklist) pass - [ ] Signature verification passes the [test vectors](/en/webhooks/signature#test-vectors) - [ ] Resending the same callback does not cause duplicate grants - [ ] The callback server responds within 10 seconds (long-running grants are processed asynchronously) - [ ] The client UI is verified for payment cancellation, failure, and the `pending` state ## Configuration [#configuration] - [ ] Register `purchaseRealUrl` (production callback URL, HTTPS) under **Apps** in the console - [ ] Connect production PG credentials (request from the StagePay operations team) — make sure they are not mixed up with beta keys - [ ] Change the checkout address from `https://beta-pay.stagepay.io` → `https://pay.stagepay.io` - [ ] Issue new production webhook secrets and API keys, and deploy them only to production servers - [ ] Configure allowed IPs and minimal scopes for API keys - [ ] Keep only QA staff in the test whitelist (their payments are sent to `purchaseTestUrl`) - [ ] If using USDT: reconfirm the production receiving addresses (private keys held), networks, confirmations, and validity period → [USDT setup](/en/usdt/setup) - [ ] Operational alerts: in the NAVER WORKS Developer Console, create an app, service account, private key, and Bot, and invite the bot to the operations message room; then set `ALERT_ENABLED=true` and `NAVERWORKS_*` on pay (Client Secret and private key as Secrets), and confirm a test alert is received from **Payments → Payment alerts** in the console → [Operational alerts](/en/operations/alerts) ## Settlement [#settlement] - [ ] Confirm in the console that the settlement policy (fee rate, cycle, hold days, minimum payout, payout account) matches the contract - [ ] Confirm that the policy's `effectiveFrom` (settlement start time) matches the go-live time - [ ] Deploy a `settlement:read` key to your reconciliation server → [Settlement query API](/en/settlement/query) ## Right after switching [#right-after-switching] - [ ] One small real payment → callback received and item granted → verify through to a refund - [ ] Confirm status `success` and callback `delivered` under **Transactions** in the console - [ ] Assign an owner for callback failure alerts and share the [troubleshooting](/en/help/troubleshooting) procedure # Logging and Tracing URL: https://docs.stagepay.io/en/operations/logging > How to trace a payment from the request through PG communication, state transitions, merchant callbacks, and settlement using requestId, plus the log types StagePay keeps and its masking rules. ## requestId [#requestid] Every request carries a correlation ID, `requestId`. - If the request has an `X-Request-Id` header, that value is used; otherwise the server generates one. - It is returned in the `X-Request-Id` response header and in the `requestId` field of REST error bodies. - The `requestId` of a payment request is stored on the transaction and propagated to PG calls and merchant callbacks (the `X-Request-Id` header). Including both the `requestId` and the `tid` when you contact us is the fastest way for us to investigate. ## Log types [#log-types] | Category | Contents | |---|---| | `http_access` | All HTTP requests and responses (method, path, masked query, status, duration, IP, UA) | | `request_rejected` | Reasons checkout requests were rejected (4xx) | | `pg_io` | Raw requests sent to and responses from PGs | | `webhook_in` | Raw webhooks received from PGs (body + headers) | | `payment_state` | Transaction state transitions (previous → new, reason) | | `callback` | Merchant callback attempt results. Per-attempt details are in `webhook_deliveries` (request headers and body, first 4 KB of the response, duration) | | `chain_scan` / `chain_match` | USDT chain queries and deposit matching | | `settlement` | Settlement batch creation, verification, approval, payout, and cancellation (before and after values in `audit_logs`) | Logs are retained for 400 days by default. ## Masking [#masking] Values for the following key names are stored in logs as `***`. ```text password, secret, token, apiKey, api_key, key, authorization, integration_key, signature, card, cvc, cvv, account_number, private ``` Card number patterns (13–19 digits) are masked in the middle. The `originalPayload` in callback bodies is not the original PG result but sanitized payment method details with secrets excluded. ## Recommended merchant-side logging [#recommended-merchant-side-logging] If you record the following when receiving callbacks, you can cross-check them against StagePay logs. - `X-StagePay-Delivery`, `X-StagePay-Event`, `X-Request-Id`, `X-StagePay-Timestamp` - Signature verification result, the status code you responded with, processing time - Raw body (excluding secrets) # Security Guide URL: https://docs.stagepay.io/en/operations/security > Security rules for merchant integrations — managing secrets, verifying callbacks, verifying amounts, least privilege for API keys, and the WebView and client trust boundary. ## Secrets [#secrets] | Secret | Purpose | Where to store it | |---|---|---| | Webhook secret (`whsec_…`) | Callback signature verification, price override signatures | Merchant server | | REST API key (`sk_…:secret`) | REST API calls, request signing | Merchant server | | App API key | Refund API, v1-compatible callback `Authorization` | Merchant server | - Never put secrets in **app bundles, web frontends, or repositories (Git)**. Use environment variables or a Secret Manager. - If you suspect a leak, rotate the secret in the console immediately → [Rotating the secret](/en/webhooks/signature#rotating-the-secret). ## Callbacks [#callbacks] - [ ] Verify `X-StagePay-Signature` on every callback against the **raw body**, using a constant-time comparison - [ ] Check the timestamp is within ±300 seconds (replay attack prevention) - [ ] Handle idempotency using `X-StagePay-Delivery` and `tid` - [ ] Confirm that the callback's `productId`, `amountMinor`, `currency`, and `userId` match your order - [ ] Do not rely solely on the v1 `Authorization: Bearer ` check (deprecated) ## Amounts [#amounts] - The payment amount is determined by the product price registered on the server. Amounts sent from the client are ignored. - Enable `allowCustomPrice` only when you need dynamic pricing, and create `priceSig` **on the merchant server** → [Price override](/en/payments/checkout#price-override). - Use `amountMinor`, not `amount` (display only), when deciding on item grants. ## Client trust boundary [#client-trust-boundary] - The `/return` result message and checkout redirect parameters are **for UI handling only**. Do not use them as the basis for grants. - When receiving `postMessage` on the web, check that `event.origin` is a StagePay checkout domain → [In-app/WebView](/en/payments/in-app-webview). - Build checkout URLs and [payment creation API](/en/payments/create-payment) calls on the server so the client cannot insert an arbitrary `userId`. ## API keys [#api-keys] - Grant only the scopes you need (e.g. only `settlement:read` for a settlement reconciliation server). - Set **allowed IPs** and an expiry date on production keys, and rotate them regularly. - Check the console API logs for calls from unexpected IPs or to unexpected endpoints. ## Transport [#transport] - Use HTTPS only for callback URLs. Self-signed certificates may fail. - To restrict incoming callbacks by IP at your firewall, request the list of outbound IPs from the StagePay operations team. IP restrictions **do not replace** signature verification. # Opening the Checkout URL: https://docs.stagepay.io/en/payments/checkout > URL parameters for the /request / /inapp checkout, price override signatures, and error responses. The checkout is opened using URL parameters only. We recommend **building the checkout URL on the merchant server** and passing it to the client (to prevent tampering with user identifiers, to sign prices, and so on). | Endpoint | Description | |---|---| | `GET /request` | Starts the payment **immediately** with the specified PG (`pg`) and payment method (`method`). | | `GET /inapp` | Shows a payment method **selection screen**, then starts the payment. If you pass `pg` and `method`, or `payment`, the selection screen is skipped. | | Environment | Base address | |---|---| | beta | `https://beta-pay.stagepay.io` | | real | `https://pay.stagepay.io` | ## Example requests [#example-requests] ```text title="Start a KCP card payment immediately" https://pay.stagepay.io/request?appId=6650f0c2a1b2c3d4e5f60718&pg=KCP&method=card&productId=gem_100¤cy=KRW&userId=user_42&language=ko ``` ```text title="Payment method selection screen" https://pay.stagepay.io/inapp?appId=6650f0c2a1b2c3d4e5f60718&productId=gem_100¤cy=KRW&userId=user_42&language=ko ``` ## Parameters [#parameters] All values must be URL-encoded (we recommend `URLSearchParams`, `http_build_query`, or `urllib.parse.urlencode`). ### Required [#required] | Parameter | Type | Description | Example | |---|---|---|---| | `appId` | string | App ID | `6650f0c2a1b2c3d4e5f60718` | | `pg` | string | PG code. Required for `/request` | `KCP`, `STRIPE`, `USDT` | | `productId` | string | Product ID registered in the console | `gem_100` | | `currency` | string | Payment currency (ISO 4217 or `USDT`). The product must have a price in this currency | `KRW` | | `userId` | string | The merchant's user identifier. Passed through to the callback as is | `user_42` | ### Optional [#optional] | Parameter | Type | Description | Example | |---|---|---|---| | `method` | string | The PG's payment method code. If omitted, the PG's default checkout is used | `card`, `TRC20` | | `language` (`lang`) | string | Checkout language | `ko`, `en`, `ja`, `zh-CN`, `zh-TW`, `th`, `id`, `es`, `ms` | | `email` | string | Email address for the receipt (used only if the format is valid) | `user@example.com` | | `serverId` | string | Game server ID | `s1` | | `playerId` | string | Game character/player ID | `hero42` | | `userdata` | string | Free-form merchant data. Passed through to the callback as is (JSON string recommended, 2 KB or less recommended) | `{"orderNo":"A-1001"}` | | `etc` | string | Free-form merchant data (auxiliary) | `promo=summer` | | `uniqueId` | string | Merchant-side unique order value. Used to link the merchant's order number to the transaction | `A-1001` | | `returnUrl` | string | "Back to merchant" address on the result screen. Only origins (`https://…`) or app schemes (`mygame://`) registered under the app's **Return addresses after payment** are accepted. `stagepay_tid` and `stagepay_status` are appended | `https://shop.example.com/orders/A-1001` | | `directPay` | string | Opens an easy pay method directly (KCP, TOSS). TOSS requires API individual integration keys — see [Open easy pay directly](/en/payments/methods#open-easy-pay-directly-directpay) | `TOSSPAY`, `NAVERPAY`, `KAKAOPAY` | | `sessionToken` | string | StagePay member session token (only for apps that use it) | | | `region` / `projectId` | string | For GamePot-integrated apps only (GamePot region and project) | | | `price`, `priceTs`, `priceSig` | string | Price override — see [Price override](#price-override) below | | For `/inapp` only: | Parameter | Description | |---|---| | `payment` | Payment method ID or code. If provided, the selection screen is skipped | | `token` | GamePot JWT (used instead of `userId` in GamePot apps) | The payment amount is determined from the product price registered on the server, based on `productId` and `currency`. Amounts sent by the client are not trusted. ## Price override [#price-override] If you really need a dynamic price (e.g. a cart total), you can override the product price with `price`. In v2, it is applied only when **both** of the following conditions are met: 1. The app setting `allowCustomPrice = true` (request it from an operator via the console) 2. A valid signature `priceSig` created by the merchant server is sent along with it, and `priceTs` is within ±900 seconds of the current time ```text title="String to sign (canonical)" price:{appId}:{productId}:{CURRENCY}:{price}:{userId}:{priceTs} ``` - `priceSig = hex(HMAC-SHA256(webhookSecret, canonical))` — the key is the app's full `webhookSecret` string (`whsec_...`). - `{CURRENCY}` must be uppercase, and `{price}` must be **exactly the same** as the string actually sent in the URL (`5000` and `5000.00` are different values). - `priceTs` is in Unix seconds. ```ts title="Signing the price (Node.js)" import crypto from 'node:crypto'; export function signPrice(p: { appId: string; productId: string; currency: string; price: string; userId: string }) { const priceTs = Math.floor(Date.now() / 1000).toString(); const canonical = ['price', p.appId, p.productId, p.currency.toUpperCase(), p.price, p.userId, priceTs].join(':'); const priceSig = crypto.createHmac('sha256', process.env.STAGEPAY_WEBHOOK_SECRET!).update(canonical).digest('hex'); return { price: p.price, priceTs, priceSig }; } ``` If the signature is missing or invalid, `price` is ignored and the product price is used (or, if the product price is 0, the request is rejected). ## Responses and errors [#responses-and-errors] The checkout returns HTML. If the request is invalid, an error page is returned along with an HTTP status code, and the rejection reason is recorded as a `request_rejected` log that you can view under **Logs** in the console. | HTTP | Message | Cause | |---|---|---| | 400 | `PG code is required` | `pg` is missing | | 400 | `Currency is required` | `currency` is missing | | 400 | `Product ID is required` | `productId` is missing | | 400 | Purchase restriction message | The product's purchase conditions were violated (one-time only, limited period, etc.) | | 400 | `Unsupported payment method` | A PG the app cannot use | | 404 | `Payment company not found` | Unknown PG code | | 404 | `Payment method not found` | A payment method code that does not exist for that PG | | 404 | `Product information not found` | The product does not exist or has no price in that currency | | 500 | `Error processing payment` | Internal error such as a failed PG request — contact us with the `requestId` | ## After the payment [#after-the-payment] 1. When the customer completes the payment, the PG notifies StagePay of the result, and StagePay confirms the transaction as `success` after PG server verification. 2. A signed `payment.succeeded` callback is sent to the merchant callback URL → [Webhooks/callbacks](/en/webhooks/overview). 3. The customer's browser (or WebView) navigates to the `/return` result page, and the result is delivered to the app → [In-app/WebView integration](/en/payments/in-app-webview). # Server-to-Server Payment Creation URL: https://docs.stagepay.io/en/payments/create-payment > The v2 integration approach where your server creates the payment first with POST /api/v1/payments, receives a checkoutUrl, and opens it for the customer. In v2, instead of assembling the checkout URL yourself, **the merchant server can create the payment first via the REST API**. You can link the `tid` returned in the response to your order in advance, and user information is not exposed in the checkout URL. ```http POST https://api.stagepay.io/api/v1/payments Authorization: Bearer sk_1f2e3d4c5b6a79880123456789abcdef: Content-Type: application/json X-Request-Id: 9b2f0c1e-6c1a-4d3e-9f20-3b1f0a8e7d11 ``` - Authentication: REST API key (requires the `write:transactions` scope). See [Authentication](/en/api/overview). - The app is determined by the app linked to the API key. You cannot create payments for other apps. ## Request body [#request-body] | Field | Type | Required | Description | |---|---|---|---| | `productId` | string | Yes | Product ID | | `currency` | string | Yes | Payment currency (`KRW`, `USD`, `USDT` …) | | `userId` | string | Yes | Merchant user identifier | | `pg` | string | | PG code. If omitted, the customer chooses on the payment method selection screen | | `method` | string | | PG payment method code (e.g. `card`, `TRC20`) | | `email` | string | | Receipt email | | `serverId` / `playerId` | string | | Game server and player IDs | | `userdata` / `etc` | string | | Free-form merchant data (passed through to the callback as is) | | `uniqueId` | string | | Merchant order number | | `returnUrl` | string | | "Back to merchant" address on the result screen. Only origins or app schemes registered under the app's **Return addresses after payment** (returnOrigins); otherwise 400 `INVALID_RETURN_URL` → [JS SDK](/en/payments/js-sdk) | | `language` | string | | Checkout language | | `price` | string | | Price override. Allowed only for apps with `allowCustomPrice=true`; because the request itself is authenticated with an API key, no separate `priceSig` is required for this API. We recommend using [request signing](/en/api/request-signing) | ```json title="Example request" { "productId": "gem_100", "currency": "KRW", "userId": "user_42", "pg": "KCP", "method": "card", "serverId": "s1", "playerId": "hero42", "userdata": "{\"orderNo\":\"A-1001\"}", "uniqueId": "A-1001", "language": "ko" } ``` ## Response [#response] ```json title="201 Created" { "tid": "KCP-20260101090000123456-a1b2c3-9f8e7d6c", "checkoutUrl": "https://pay.stagepay.io/checkout?tid=KCP-20260101090000123456-a1b2c3-9f8e7d6c&token=...", "expiresAt": "2026-01-01T09:30:00+09:00" } ``` | Field | Description | |---|---| | `tid` | The created transaction ID. At this point, the transaction is in the `pending` state | | `checkoutUrl` | The checkout URL to open for the customer. It contains a one-time token, so use it as is | | `expiresAt` | Payment validity period. After this time, `checkoutUrl` expires and the transaction becomes `expired` | Open `checkoutUrl` in an [in-app WebView](/en/payments/in-app-webview) or a browser. You receive the payment result via [callback](/en/webhooks/overview), as before. ## Code examples [#code-examples] ```bash curl -X POST https://api.stagepay.io/api/v1/payments \ -H "Authorization: Bearer $STAGEPAY_KEY_ID:$STAGEPAY_KEY_SECRET" \ -H "Content-Type: application/json" \ -d '{"productId":"gem_100","currency":"KRW","userId":"user_42","pg":"KCP","method":"card"}' ``` ```js const res = await fetch('https://api.stagepay.io/api/v1/payments', { method: 'POST', headers: { Authorization: `Bearer ${process.env.STAGEPAY_KEY_ID}:${process.env.STAGEPAY_KEY_SECRET}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ productId: 'gem_100', currency: 'KRW', userId: 'user_42', pg: 'KCP', method: 'card' }), }); if (!res.ok) throw new Error(`StagePay ${res.status}: ${await res.text()}`); const { tid, checkoutUrl, expiresAt } = await res.json(); ``` ```php true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ 'Authorization: Bearer ' . getenv('STAGEPAY_KEY_ID') . ':' . getenv('STAGEPAY_KEY_SECRET'), 'Content-Type: application/json', ], CURLOPT_POSTFIELDS => json_encode([ 'productId' => 'gem_100', 'currency' => 'KRW', 'userId' => 'user_42', 'pg' => 'KCP', 'method' => 'card', ]), ]); $body = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); if ($status >= 300) { throw new RuntimeException("StagePay $status: $body"); } $payment = json_decode($body, true); // ['tid' => ..., 'checkoutUrl' => ..., 'expiresAt' => ...] ``` ```python import os import requests res = requests.post( "https://api.stagepay.io/api/v1/payments", headers={"Authorization": f"Bearer {os.environ['STAGEPAY_KEY_ID']}:{os.environ['STAGEPAY_KEY_SECRET']}"}, json={"productId": "gem_100", "currency": "KRW", "userId": "user_42", "pg": "KCP", "method": "card"}, timeout=10, ) res.raise_for_status() payment = res.json() # {"tid": ..., "checkoutUrl": ..., "expiresAt": ...} ``` ## Errors [#errors] | HTTP | Cause | |---|---| | 400 | Missing required field, unknown product or currency, purchase restriction violated, `price` not allowed | | 401 | API key missing, malformed, or expired | | 403 | Insufficient scope (`write:transactions`), IP not allowed | | 429 | Rate limit exceeded | For the error response format, see [Pagination and errors](/en/api/conventions). The final definition of request and response fields is the [Endpoint reference](/en/api/reference) (OpenAPI). If this page differs, follow the reference. # In-App / WebView Integration URL: https://docs.stagepay.io/en/payments/in-app-webview > How to open the checkout in a mobile game or app WebView and receive the payment result message sent by /return in React Native, iOS, Android, and the web (popup/iframe). When the payment is finished, the customer is taken to the StagePay result page, `/return`. As soon as this page loads, it **sends the payment result over multiple channels at once**, so your app only needs to implement the channel that suits it. Use the `/return` message only for **UI handling**, such as closing the checkout and showing a "Confirming payment" screen. Always grant items based on the [signed callback](/en/webhooks/overview) received by your server. Client messages can be forged. ## Result message format [#result-message-format] ```json { "type": "STAGEPAY_RESULT", "action": "payment_complete", "status": "success", "title": "결제 성공", "message": "결제가 성공적으로 완료되었습니다.", "transactionId": "KCP-20260101090000123456-a1b2c3-9f8e7d6c", "details": "Transaction ID: KCP-20260101090000123456-a1b2c3-9f8e7d6c", "timestamp": "2026-01-01T09:00:12+09:00" } ``` | Field | Value | |---|---| | `type` | Always `STAGEPAY_RESULT` (the close button message is `STAGEPAY_CLOSE` for popups and iframes) | | `action` | `payment_complete` (on page load) or `close` (close button) | | `status` | `success` · `pending` · `failed`. `pending` means the PG returned before final approval (e.g. some card or bank account payments); the final result is reflected via the callback | | `transactionId` | StagePay `tid` | | `title` / `message` | Display text in the browser language (ko/en/ja/zh) | ## Delivery channels [#delivery-channels] | Environment | Channel | |---|---| | React Native WebView | `window.ReactNativeWebView.postMessage(JSON.stringify(result))` | | iOS WKWebView | `window.webkit.messageHandlers.GamePotStagePay.postMessage(result)` | | Android WebView | `window.GamePotStagePay.onPaymentResult(JSON.stringify(result))` | | Popup (window.open) | `window.opener.postMessage(result, '*')` | | iframe | `window.parent.postMessage(result, '*')` | When the close button is pressed, React Native receives an `action: "close"` message, iOS receives `{ action: 'close' }`, and Android receives a `GamePotStagePay.close()` call. ## Platform examples [#platform-examples] ```tsx import { WebView } from 'react-native-webview'; export function CheckoutScreen({ checkoutUrl, onDone }: { checkoutUrl: string; onDone: (s: string) => void }) { return ( { let data: { type?: string; action?: string; status?: string; transactionId?: string }; try { data = JSON.parse(event.nativeEvent.data); } catch { return; } if (data.type !== 'STAGEPAY_RESULT') return; // Only update the UI; decide whether to grant by querying the server (callback) status onDone(data.status ?? 'failed'); }} /> ); } ``` ```swift import WebKit final class CheckoutViewController: UIViewController, WKScriptMessageHandler { private var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let controller = WKUserContentController() controller.add(self, name: "GamePotStagePay") // Handler name called by /return let config = WKWebViewConfiguration() config.userContentController = controller webView = WKWebView(frame: view.bounds, configuration: config) view.addSubview(webView) webView.load(URLRequest(url: URL(string: checkoutUrl)!)) } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { guard let body = message.body as? [String: Any] else { return } if body["action"] as? String == "close" { dismiss(animated: true) return } let status = body["status"] as? String ?? "failed" let tid = body["transactionId"] as? String ?? "" print("StagePay result:", status, tid) // Query the server for the grant status } var checkoutUrl = "" } ``` ```kotlin import android.webkit.JavascriptInterface import android.webkit.WebView import org.json.JSONObject class StagePayBridge(private val activity: CheckoutActivity) { @JavascriptInterface fun onPaymentResult(json: String) { val data = JSONObject(json) if (data.optString("type") != "STAGEPAY_RESULT") return val status = data.optString("status", "failed") val tid = data.optString("transactionId") activity.runOnUiThread { activity.onPaymentResult(status, tid) } } @JavascriptInterface fun close() { activity.runOnUiThread { activity.finish() } } } // Activity.onCreate fun setup(webView: WebView, checkoutUrl: String, activity: CheckoutActivity) { webView.settings.javaScriptEnabled = true webView.settings.domStorageEnabled = true webView.addJavascriptInterface(StagePayBridge(activity), "GamePotStagePay") webView.loadUrl(checkoutUrl) } ``` ```js const STAGEPAY_ORIGINS = ['https://pay.stagepay.io', 'https://beta-pay.stagepay.io']; const popup = window.open(checkoutUrl, 'stagepay', 'width=480,height=720'); window.addEventListener('message', (event) => { // Always verify the origin if (!STAGEPAY_ORIGINS.includes(event.origin)) return; const data = event.data; if (data?.type === 'STAGEPAY_RESULT') { console.log('결제 상태:', data.status, data.transactionId); // Query the server for the order status and update the UI } if (data?.type === 'STAGEPAY_CLOSE') popup?.close(); }); ``` ```csharp // Unity has no built-in WebView, so you usually use one of the following. // 1) Open in an external browser + poll your server Application.OpenURL(checkoutUrl); // 2) With a WebView plugin (e.g. gree/unity-webview), register the plugin's JS bridge // under the name "GamePotStagePay", or wire up a ReactNativeWebView-style callback. // Either way, grant items based on the server callback, and have the client query your server for the result. ``` ## Recommended flow [#recommended-flow] 1. The client sends a purchase request to the merchant server → the server calls the [payment creation API](/en/payments/create-payment) or builds a [checkout URL](/en/payments/checkout). 2. The client opens `checkoutUrl` in a WebView. 3. On receiving `STAGEPAY_RESULT`, close the WebView and show "Confirming payment". 4. The merchant server grants the item after receiving the callback. The client queries the merchant server for the order status (polling or push) and displays the result. 5. If `status` is `pending`, wait until the callback arrives (USDT, virtual accounts, and similar methods can take from several minutes to several hours). ## WebView configuration tips [#webview-configuration-tips] - JavaScript and DOM Storage must be enabled. - Some payment methods (card issuer apps, easy pay apps) open apps via external schemes such as `intent://` or `kakaotalk://`. In your WebView's URL loading handler, pass non-`http(s)` schemes to the OS so it launches the external app. - If third-party cookies are blocked, some PG authentication can fail. On Android, set `CookieManager.setAcceptThirdPartyCookies(webView, true)`. # JavaScript SDK URL: https://docs.stagepay.io/en/payments/js-sdk > Launch any PG, payment method or easy pay (Kakao Pay, Naver Pay, Toss Pay) from a merchant web page with one script tag and one call — on PC, mobile web and in-app WebViews. `stagepay.js` builds the [checkout URL](/en/payments/checkout) for you, opens it the right way for the environment, and returns the `STAGEPAY_RESULT` message sent by `/return` as a Promise. It has no dependencies (ES2017) and never handles secrets such as API keys. Use the value returned by `requestPayment()` only for **UI handling** — closing the checkout, showing "Confirming payment". Always grant items based on the [signed callback](/en/webhooks/overview) received by your server. Browser-side values can be forged. ## Install [#install] ```html ``` | File | Description | |---|---| | `/sdk/stagepay.js` | Readable source (UMD, global `StagePay`) | | `/sdk/stagepay.min.js` | Minified (about 14 KB, about 6 KB gzipped) | | `/sdk/stagepay.d.ts` | TypeScript declarations | | `/sdk/example.html` | Working example (one button per payment + result log) | For beta use `https://beta-pay.stagepay.io/sdk/stagepay.js` and set `payUrl` to the beta host. With a bundler you can also download the file and `import StagePay from './stagepay.js'` (CommonJS/AMD supported). ## Initialize [#initialize] ```js StagePay.init({ appId: '6650f0c2a1b2c3d4e5f60718', // App ID from the console language: 'en', // checkout language (defaults to the browser language) // payUrl: 'https://beta-pay.stagepay.io', // default https://pay.stagepay.io // debug: true, }); ``` | Option | Default | Description | |---|---|---| | `appId` | — | App ID (required) | | `payUrl` | `https://pay.stagepay.io` | Pay server. https only (http allowed for `localhost`) | | `language` | — | `ko`, `en`, `ja`, `zh-CN`, `zh-TW`, `th`, `id`, `es`, `ms` … | | `debug` | `false` | Console logging | | `inapp` | `false` | Treat this page as an in-app WebView (see modes) | | `timeout` | 30 min | `TIMEOUT` when no result arrives in this time (0 = never) | | `closeOnResult` | `true` | Close the popup/layer when the result arrives | | `fallback` | `layer` | When the popup is blocked: `layer`, `redirect` or `none` | ## Request a payment [#request-a-payment] ```js document.querySelector('#buy').addEventListener('click', async () => { try { const result = await StagePay.requestPayment({ pg: 'KCP', method: 'card', productId: 'gem_100', currency: 'KRW', userId: 'user_42', uniqueId: 'A-1001', // your order id userdata: { orderNo: 'A-1001' }, // objects are sent as JSON → echoed in the callback }); // result: { status: 'success' | 'pending' | 'failed', transactionId, pg, mode, ... } await refreshOrderFromMyServer('A-1001'); // decide fulfilment from your server state } catch (e) { if (e.code === 'USER_CLOSED') return; // the customer closed the window console.error(e.code, e.message); } }); ``` Parameters are the same as the [checkout parameters](/en/payments/checkout) (`pg`, `method`, `directPay`, `productId`, `currency`, `userId`/`token`, `email`, `serverId`, `playerId`, `userdata`, `etc`, `uniqueId`, `price`·`priceTs`·`priceSig`, `vaBank`, `language` …). Keys outside that list are not sent, and names such as `apiKey` or `secret` are rejected with an error. ### Examples per PG / easy pay [#examples-per-pg--easy-pay] ```js const base = { productId: 'gem_100', currency: 'KRW', userId: 'user_42' }; StagePay.requestPayment({ ...base, pg: 'KCP', method: 'card' }); // KCP card StagePay.requestPayment({ ...base, pg: 'KCP', method: 'VCNT' }); // KCP virtual account StagePay.requestPayment({ ...base, pg: 'TOSS', directPay: 'TOSSPAY' }); // Toss Pay, opened directly StagePay.requestPayment({ ...base, pg: 'TOSS', directPay: 'NAVERPAY' }); // Toss window → Naver Pay StagePay.requestPayment({ ...base, pg: 'KCP', directPay: 'KAKAOPAY' }); // KCP window → Kakao Pay StagePay.requestPayment({ ...base, pg: 'KAKAOPAY' }); // Kakao Pay direct integration StagePay.requestPayment({ ...base, pg: 'NAVERPAY' }); // Naver Pay direct integration StagePay.requestPayment({ ...base, pg: 'STRIPE', currency: 'USD' }); // Stripe StagePay.requestPayment({ ...base, pg: 'USDT', method: 'TRC20', currency: 'USD' }); // USDT (TRC20) StagePay.requestPayment({ ...base, pg: 'CRYPTO', method: 'BTC' }); // BTC StagePay.requestPayment(base); // no pg → method picker (/inapp) ``` See [Payment methods](/en/payments/methods) for the available PG, `method` and `directPay` values. A price override (`price`) needs `priceTs`/`priceSig` generated by your server → [Price override](/en/payments/checkout). ### Server-created payments (checkoutUrl) [#server-created-payments-checkouturl] Open a `checkoutUrl` from the [payment creation API](/en/payments/create-payment) with `openCheckout`. URLs from an origin other than `payUrl` are rejected. To avoid the popup blocker while you wait for your server, **pass the Promise itself**: the SDK opens the window during the click and navigates it once the URL arrives. ```js button.addEventListener('click', () => { const checkoutUrl = fetch('/api/orders', { method: 'POST', body: JSON.stringify({ sku: 'gem_100' }) }) .then((r) => r.json()) .then((j) => j.checkoutUrl); // value your server got from POST /api/v1/payments StagePay.openCheckout(checkoutUrl).then(onResult, onError); }); ``` ### Method picker [#method-picker] ```js StagePay.openMethodPicker({ productId: 'gem_100', currency: 'KRW', userId: 'user_42' }); StagePay.openMethodPicker({ productId: 'gem_100', currency: 'KRW', userId: 'user_42', payment: 'card' }); // skip the picker ``` ## Modes [#modes] By default (`mode: 'auto'`) the SDK picks a mode from the environment. You can force one per call with `mode`. | Mode | When (auto) | Behaviour | Result delivery | |---|---|---|---| | `popup` | PC | Centered popup window | `window.opener.postMessage` → Promise | | `layer` | Popup blocked | Full-screen iframe layer (close button, ESC, focus trap, scroll lock, `aria-modal`) | `window.parent.postMessage` → Promise | | `redirect` | Mobile web | Navigates the current window to the checkout | Promise settles at once with `{ status: 'redirected' }` | | `webview` | In-app WebView | Navigates the current window | Native bridge ([In-app / WebView](/en/payments/in-app-webview)) | Decision order: 1. An explicit `mode` wins. 2. `inapp: true`, a native bridge (`ReactNativeWebView`, iOS `webkit.messageHandlers.GamePotStagePay`, Android `GamePotStagePay`), or a WebView / in-app browser UA (Android `; wv)`, iOS without the `Safari/` token, KakaoTalk, Naver, LINE, Facebook, Instagram …) → `webview`. 3. Mobile or tablet UA (including iPadOS) → `redirect`. 4. Otherwise → `popup` (then `fallback` if blocked). In `redirect` mode the customer lands on the StagePay `/return` result screen. Pass `returnUrl` and that screen shows a **Back to merchant** button ([below](#returning-to-your-site-returnurl)). Always decide fulfilment on **your server (callback)**; on the page the customer returns to, use `StagePay.getReturnResult()` or `StagePay.getPendingRedirect()` (what was started: `{ startedAt, pg, productId, uniqueId }`) to ask your server for the order state. If you want the Promise result on mobile too, open with `mode: 'popup'` (a new tab). ### Returning to your site (returnUrl) [#returning-to-your-site-returnurl] For setup, rules and errors, see the [Return to merchant](/en/payments/return-url) guide. 1. In the console, register addresses under **Edit app → Return addresses after payment**, one per line (up to 10). - Web: `https://shop.example.com` — the origin only, no path. Register each port separately; http works only for `localhost`/`127.0.0.1`. - App deep link: `mygame://` — the scheme only (to come back to the app after paying in an external browser). 2. Pass `returnUrl` in the payment request. It is accepted only when it matches a registered origin **exactly** (subdomains are not implied); otherwise checkout does not open (`errors.invalid_return_url`). `returnUrl` in the [Create payment API](/en/payments/create-payment) follows the same rule (`INVALID_RETURN_URL`). 3. The button goes to `returnUrl` with `stagepay_tid` and `stagepay_status` (`success`, `pending`, `failed`) appended. In a popup, layer or app WebView bridge the result arrives as a message, so a Close button is shown instead. Removing the address in the console also removes the button from payments already created. ```js StagePay.requestPayment({ pg: 'KCP', method: 'card', productId: 'gem_100', currency: 'KRW', userId: 'user_42', uniqueId: 'A-1001', returnUrl: 'https://shop.example.com/orders/A-1001', }); // The page the customer returns to: /orders/A-1001?stagepay_tid=KCP-...&stagepay_status=success const back = StagePay.getReturnResult({ clean: true }); // { transactionId, status, verified: false } | null if (back) await refreshOrderFromMyServer('A-1001'); ``` Anyone can change query values. Decide fulfilment only from the signed callback or a server-side transaction lookup. ### About the layer (iframe) [#about-the-layer-iframe] The layer is a fallback for blocked popups. Some PG pages refuse to load inside an iframe (X-Frame-Options), and third-party cookie blocking can break authentication. Prefer calling from the click handler so a popup opens. The iframe gets `sandbox` (top navigation only on user click) and `allow="payment"`. ## Results and errors [#results-and-errors] ```ts type StagePayResult = { status: 'success' | 'pending' | 'failed' | 'expired' | 'redirected'; transactionId: string; // StagePay tid pg: string; mode: 'popup' | 'layer' | 'redirect' | 'webview'; title?: string; message?: string; timestamp?: string; }; ``` - `pending`: the PG returned before final approval (virtual account issued, some bank transfers …). The final result comes through the callback. - `failed` also **resolves** the Promise. It rejects only when the window is closed or the call is invalid. | `error.code` | Meaning | |---|---| | `USER_CLOSED` | The customer closed the popup/layer (ESC, close button, close on the result screen) | | `ALREADY_IN_PROGRESS` | A checkout is already open (one at a time; the open window is focused) | | `POPUP_BLOCKED` | The popup was blocked and `fallback: 'none'` | | `TIMEOUT` | No result within `timeout` | | `CANCELLED` | Your code called `StagePay.close()` | | `INVALID_PARAMS` / `INVALID_CONFIG` / `NOT_INITIALIZED` | Invalid call or configuration | | `CHECKOUT_URL_FAILED` | The Promise passed to `openCheckout` failed | ## What the SDK does for security [#what-the-sdk-does-for-security] - It accepts `message` events only when **the origin equals the `payUrl` origin**, `data.type` is `STAGEPAY_RESULT`/`STAGEPAY_CLOSE`, and the sender is the popup/iframe the SDK opened. Everything else is ignored. - It holds no secrets. It only builds checkout URLs from public parameters; the amount comes from the server-side product price (or a server-signed price). - `openCheckout` never opens a URL from another origin than `payUrl`, and `payUrl` must be https. ## React / Vue [#react--vue] ```tsx title="React" import { useCallback, useState } from 'react'; import type { StagePaySDK } from './stagepay'; // /sdk/stagepay.d.ts declare const StagePay: StagePaySDK; // loaded with ``` Call `StagePay.init()` once per app (calling it again replaces the settings). With SSR, call it in the browser only. ## CSP [#csp] If your page sends a Content-Security-Policy, allow: ```text script-src https://pay.stagepay.io; frame-src https://pay.stagepay.io; # layer (iframe) mode connect-src 'self'; # the SDK makes no fetch calls (query orders on your own server) ``` The SDK styles its layer through CSSOM, not `