Skip to Content
StagePayDocs v2

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>
FileDescription
/sdk/stagepay.jsReadable source (UMD, global StagePay)
/sdk/stagepay.min.jsMinified (about 14 KB, about 6 KB gzipped)
/sdk/stagepay.d.tsTypeScript declarations
/sdk/example.htmlWorking 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,
});
OptionDefaultDescription
appId—App ID (required)
payUrlhttps://pay.stagepay.ioPay server. https only (http allowed for localhost)
language—ko, en, ja, zh-CN, zh-TW, th, id, es, ms …
debugfalseConsole logging
inappfalseTreat this page as an in-app WebView (see modes)
timeout30 minTIMEOUT when no result arrives in this time (0 = never)
closeOnResulttrueClose the popup/layer when the result arrives
fallbacklayerWhen 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 picker

Modes

By default (mode: 'auto') the SDK picks a mode from the environment. You can force one per call with mode.

ModeWhen (auto)BehaviourResult delivery
popupPCCentered popup windowwindow.opener.postMessage → Promise
layerPopup blockedFull-screen iframe layer (close button, ESC, focus trap, scroll lock, aria-modal)window.parent.postMessage → Promise
redirectMobile webNavigates the current window to the checkoutPromise settles at once with { status: 'redirected' }
webviewIn-app WebViewNavigates the current windowNative bridge (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).

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.

  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 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.
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.
  • failed also resolves the Promise. It rejects only when the window is closed or the call is invalid.
error.codeMeaning
USER_CLOSEDThe customer closed the popup/layer (ESC, close button, close on the result screen)
ALREADY_IN_PROGRESSA checkout is already open (one at a time; the open window is focused)
POPUP_BLOCKEDThe popup was blocked and fallback: 'none'
TIMEOUTNo result within timeout
CANCELLEDYour code called StagePay.close()
INVALID_PARAMS / INVALID_CONFIG / NOT_INITIALIZEDInvalid call or configuration
CHECKOUT_URL_FAILEDThe Promise passed to openCheckout failed

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
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>;
}
Vue 3
<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

SymptomCause · fix
A layer opens instead of a popup / POPUP_BLOCKEDrequestPayment() 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 SafariiOS opens windows only inside a user gesture (tap). Call from the click/touchend handler, not after setTimeout or a Promise.
USER_CLOSED right after openingA COOP header on your page (see above) or a browser extension closed the window. Check with debug: true.
ALREADY_IN_PROGRESSA checkout is already open. Disable the button, or call StagePay.close() first.
Card / easy-pay apps don't open in a WebViewThe native WebView must hand schemes such as intent:// and kakaotalk:// to the OS → WebView tips.
Result is success but no itemFulfilment 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).

On this page