JavaScript 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 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.
The result is for the UI only
Use the value returned by requestPayment() only for UI handling — closing the checkout, showing "Confirming payment". Always grant items based on the signed callback received by your server. Browser-side values can be forged.
Install
<script src="https://pay.stagepay.io/sdk/stagepay.js"></script>| 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
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
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 (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
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 for the available PG, method and directPay values. A price override (price) needs priceTs/priceSig generated by your server → Price override.
Server-created payments (checkoutUrl)
Open a checkoutUrl from the payment creation API 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.
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
StagePay.openMethodPicker({ productId: 'gem_100', currency: 'KRW', userId: 'user_42' });
StagePay.openMethodPicker({ productId: 'gem_100', currency: 'KRW', userId: 'user_42', payment: 'card' }); // skip the pickerModes
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) |
Decision order:
- An explicit
modewins. inapp: true, a native bridge (ReactNativeWebView, iOSwebkit.messageHandlers.GamePotStagePay, AndroidGamePotStagePay), or a WebView / in-app browser UA (Android; wv), iOS without theSafari/token, KakaoTalk, Naver, LINE, Facebook, Instagram …) →webview.- Mobile or tablet UA (including iPadOS) →
redirect. - Otherwise →
popup(thenfallbackif blocked).
Getting the result on mobile web
In redirect mode the customer lands on the StagePay /return result screen. Pass returnUrl and that screen shows a Back to merchant button (below). 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)
For setup, rules and errors, see the Return to merchant guide.
- 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 forlocalhost/127.0.0.1. - App deep link:
mygame://— the scheme only (to come back to the app after paying in an external browser).
- Web:
- Pass
returnUrlin 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).returnUrlin the Create payment API follows the same rule (INVALID_RETURN_URL). - The button goes to
returnUrlwithstagepay_tidandstagepay_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.
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');stagepay_status is for display only
Anyone can change query values. Decide fulfilment only from the signed callback or a server-side transaction lookup.
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
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.failedalso 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
- It accepts
messageevents only when the origin equals thepayUrlorigin,data.typeisSTAGEPAY_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).
openCheckoutnever opens a URL from another origin thanpayUrl, andpayUrlmust be https.
React / Vue
import { useCallback, useState } from 'react';
import type { StagePaySDK } from './stagepay'; // /sdk/stagepay.d.ts
declare const StagePay: StagePaySDK; // loaded with <script src="https://pay.stagepay.io/sdk/stagepay.js">
StagePay.init({ appId: process.env.NEXT_PUBLIC_STAGEPAY_APP_ID!, language: 'en' });
export function BuyButton({ userId }: { userId: string }) {
const [state, setState] = useState<'idle' | 'paying' | 'checking'>('idle');
const onClick = useCallback(() => {
setState('paying');
// call right away, before any await (popup blocker)
StagePay.requestPayment({ pg: 'TOSS', directPay: 'TOSSPAY', productId: 'gem_100', currency: 'KRW', userId })
.then(() => setState('checking')) // ask your server for the order state
.catch(() => setState('idle'));
}, [userId]);
return <button onClick={onClick} disabled={state !== 'idle'}>Buy</button>;
}<script setup lang="ts">
const props = defineProps<{ userId: string }>();
const pay = () =>
window.StagePay.requestPayment({ pg: 'KCP', method: 'card', productId: 'gem_100', currency: 'KRW', userId: props.userId })
.then((r) => console.log(r.status, r.transactionId))
.catch((e) => console.log(e.code));
</script>
<template><button @click="pay">Buy</button></template>Call StagePay.init() once per app (calling it again replaces the settings). With SSR, call it in the browser only.
CSP
If your page sends a Content-Security-Policy, allow:
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 <style> elements or style attributes, so style-src needs no 'unsafe-inline'. PG pages inside the layer are documents opened by pay.stagepay.io and are not subject to your CSP.
If your page sends Cross-Origin-Opener-Policy: same-origin, the link to the popup is cut and no result arrives (USER_CLOSED right away). On pages with a pay button, send no COOP or use same-origin-allow-popups.
Troubleshooting
| Symptom | Cause · fix |
|---|---|
A layer opens instead of a popup / POPUP_BLOCKED | requestPayment() was not called synchronously inside the click handler. Calling it after await fetch(...) gets blocked. If you need a server value, use openCheckout(promise). |
| Nothing happens in iOS Safari | iOS opens windows only inside a user gesture (tap). Call from the click/touchend handler, not after setTimeout or a Promise. |
USER_CLOSED right after opening | A COOP header on your page (see above) or a browser extension closed the window. Check with debug: true. |
ALREADY_IN_PROGRESS | A checkout is already open. Disable the button, or call StagePay.close() first. |
| Card / easy-pay apps don't open in a WebView | The native WebView must hand schemes such as intent:// and kakaotalk:// to the OS → WebView tips. |
| Result is success but no item | Fulfilment follows the callback. Check webhook/callback delivery and signature verification. |
Try every button at https://pay.stagepay.io/sdk/example.html (beta-pay for beta).
Server-to-Server Payment Creation
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.
Return to merchant (returnUrl)
Send customers back to your page or app after payment — register addresses in the console, pass returnUrl, and handle the return page.