WebXCOM SDK — Frontend Guide

— BROWSER SDK —

A frontend SDK guide for integrating WebXCOM OAuth popup login in browser environments. 브라우저 환경에서 WebXCOM OAuth 팝업 로그인을 연동하는 프론트엔드 SDK 가이드입니다.

🚀 Quick Start

Integrate the WebXCOM frontend SDK in 4 steps. 4단계로 WebXCOM 프론트엔드 SDK를 연동하세요.

1
Install
Install SDK via npm npm으로 SDK 설치
2
Initialize
Create a WebXCOM instance WebXCOM 인스턴스 생성
3
Login
Run popup login 팝업 로그인 실행
4
Use Token
Authenticate backend with JWT JWT로 백엔드 인증

Install Installation 설치

Install the SDK using npm. npm을 사용하여 SDK를 설치합니다.

npm install @webxcom/sdk

Choose your import method: Import 방법을 선택하세요:

import WebXCOM from '@webxcom/sdk';
const WebXCOM = require('@webxcom/sdk');

Initialize Initialization 초기화

Create a WebXCOM instance using the client credentials issued from the developer center. WebXCOM 인스턴스를 생성합니다. 개발자 센터에서 발급받은 클라이언트 정보를 사용하세요.

ParameterTypeRequiredDescription
webxcomUrl string Required WebXCOM server base URL WebXCOM 서버 base URL
clientId string Required Client ID issued from the developer center 개발자센터에서 발급받은 클라이언트 ID
redirectUri string Required URI to redirect to after OAuth authorization OAuth 인가 후 리다이렉트될 URI
responseType string Optional OAuth response type (default: 'code') OAuth response type (default: 'code')
popupWidth number Optional Popup width (default: 600) 팝업 너비 (default: 600)
popupHeight number Optional Popup height (default: 500) 팝업 높이 (default: 500)
const sdk = new WebXCOM({
  webxcomUrl:  'https://your-webxcom.com',
  clientId:    'your-client-id',
  redirectUri: 'https://your-app.com/callback',
});

Login Login 로그인

sdk.login(options?)Opens an OAuth popup and returns the login result as a Promise. OAuth 팝업을 열고 로그인 결과를 Promise로 반환합니다.

postMessage Protocol postMessage 프로토콜
When login completes in the popup, a postMessage of format { from: "webxcom", type: "success"|"fail", data: JWT|ERROR_MSG } is sent to the parent window. The SDK handles this automatically. 팝업 창에서 로그인이 완료되면 { from: "webxcom", type: "success"|"fail", data: JWT|ERROR_MSG } 형식의 postMessage를 부모 창으로 전송합니다. SDK가 이를 자동으로 처리합니다.
ParameterTypeRequiredDescription
state string Optional CSRF state value (auto-generated if omitted) CSRF 방지용 state 값 (미입력 시 자동 생성)
timeout number Optional Login timeout in ms (default: 120000) 로그인 타임아웃 ms (default: 120000)
try {
  const { jwt } = await sdk.login({ state: String(Date.now()) });
  console.log('JWT:', jwt);
  // JWT를 게임 백엔드로 전달
  await fetch('/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ jwt }),
  });
} catch (err) {
  console.error('Login failed:', err.message);
}

Manage Logout & Token Management 로그아웃 & 토큰 관리

Manage tokens and handle logout after login. 로그인 후 토큰을 관리하고 로그아웃을 처리합니다.

MethodReturnsDescription
sdk.logout(options?) Promise<void> Deactivates De-OAuth server JWT + clears localStorage De-OAuth 서버 JWT 비활성화 + localStorage 정리
sdk.getToken() string | null Returns stored access_token 저장된 access_token 반환
sdk.getRefreshToken() string | null Returns stored refresh_token 저장된 refresh_token 반환
sdk.getCode() string | null Returns stored OAuth code 저장된 OAuth code 반환
sdk.isLoggedIn() boolean Whether access_token exists access_token 존재 여부
sdk.refresh(options) Promise<{...}> Refresh token (clientSecret required) 토큰 갱신 (clientSecret 필수)
// 로그아웃
await sdk.logout();

// 토큰 확인
if (sdk.isLoggedIn()) {
  const token = sdk.getToken();
  console.log('Token:', token);
}
⚠️ refresh() Security Warning ⚠️ refresh() 보안 경고
clientSecret is exposed in the browser when used on the frontend. For security-sensitive operations, use it only on the backend. Calling refresh() on the frontend includes clientSecret in the JavaScript bundle, visible to anyone. 은 프론트엔드에서 사용 시 브라우저에 노출됩니다. 보안이 필요한 경우 백엔드에서만 사용하세요. 프론트엔드에서 refresh()를 호출하면 clientSecret이 JavaScript 번들에 포함되어 누구나 확인할 수 있습니다.
// ⚠️ 프론트엔드에서 refresh() 사용 시 clientSecret 노출 주의
const result = await sdk.refresh({
  clientSecret: 'your-client-secret', // 브라우저에 노출됨!
});
console.log('New token:', result.accessToken);

Errors Error Handling 에러 처리

Error messages and their causes from the SDK. SDK에서 발생할 수 있는 에러 메시지와 원인입니다.

Error MessageCause
Popup blocked Browser popup blocked 브라우저 팝업 차단 설정
User closed the login window User closed the popup window 사용자가 팝업 창을 닫음
Login failed: {reason} Error during login processing 로그인 처리 중 오류 발생
Login timeout No response within timeout (default 120s) timeout 시간 내 응답 없음 (default 120초)
try {
  const { jwt } = await sdk.login();
} catch (err) {
  if (err.message.includes('Popup blocked')) {
    alert('팝업을 허용해주세요.');
  } else if (err.message.includes('User closed')) {
    console.log('사용자가 로그인을 취소했습니다.');
  } else if (err.message.includes('timeout')) {
    console.error('로그인 시간이 초과되었습니다.');
  } else {
    console.error('로그인 오류:', err.message);
  }
}