@appboxo/web-sdk

中文文档
1.4.4发布于 2026/02/26MITTypeScriptCommonJS近 30 天下载 3215

Boxo Desktop Host App SDK for handling miniapp events

原始使用文档
文档目录14 节
  1. Quick Start
  2. Installation
  3. Configuration
  4. Authentication
  5. Payment Processing
  6. Locale/Language
  7. Theme/Dark Mode
  8. Logout
  9. Methods
  10. Events
  11. Examples
  12. React Example
  13. Using mount helper
  14. License

Appboxo Web SDK

Embed miniapps into your desktop application using iframe communication.

Quick Start

import { AppboxoWebSDK } from "@appboxo/web-sdk";

const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id"
});

// Get auth code from your backend
const authCode = await fetch('/api/auth-code').then(r => r.json());
sdk.setAuthCode(authCode);

// Mount miniapp (SDK will automatically fetch URL from API)
await sdk.mount({
  container: document.getElementById("miniapp")
});

Installation

npm install @appboxo/web-sdk
# or
pnpm install @appboxo/web-sdk

Configuration

const sdk = new AppboxoWebSDK({
  clientId: string;      // Required
  appId: string;         // Required
  userId?: string;       // Optional, user reference identifier
  baseUrl?: string;      // Optional, default: "https://dashboard.boxo.io/api/v1"
  sandboxMode?: boolean;  // Optional, default: false
  debug?: boolean;       // Optional, default: false. When true, enables all console logs for debugging. When false, no console logs are output.
  locale?: string;       // Optional, locale/language code (e.g., 'en', 'en-US', 'ru', 'zh-CN')
  theme?: 'dark' | 'light' | 'system'; // Optional, theme/color scheme preference (default: 'system')
  onGetAuthCode?: () => Promise<string>; // Optional, for automatic auth code retrieval
  onGetAuthTokens?: () => Promise<LoginResponse>; // Optional, for direct auth tokens
  onPaymentRequest?: (params: PaymentRequest) => Promise<PaymentResponse>; // Optional, for handling payment requests
});

Authentication

OAuth flow:

sdk.setAuthCode(authCode);

Or provide a callback:

const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id",
  onGetAuthCode: async () => {
    const res = await fetch('/api/generate-auth-code');
    return (await res.json()).auth_code;
  }
});

Direct auth flow:

sdk.onAuth(async () => {
  const response = await fetch('/api/get-miniapp-tokens');
  const tokens = await response.json();
  sdk.setAuthTokens(tokens.access_token, tokens.refresh_token);
});

Or use callback:

const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id",
  onGetAuthTokens: async () => {
    const res = await fetch('/api/get-miniapp-tokens');
    const result = await res.json();
    return {
      token: result.access_token,
      refresh_token: result.refresh_token
    };
  }
});

Or set tokens directly:

const tokens = await getTokensFromBackend();
sdk.setAuthTokens(tokens.access_token, tokens.refresh_token);

The SDK will try these in order:

  1. Pre-set tokens (setAuthTokens)
  2. Direct auth callback (onGetAuthTokens)
  3. OAuth auth code (setAuthCode or onGetAuthCode callback)

Payment Processing

When a miniapp calls appboxo.pay(), the SDK will call your onPaymentRequest callback. Process the payment and return the result.

Payment status values: 'success', 'failed', or 'cancelled'.

const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id",
  onPaymentRequest: async (paymentData) => {
    // Process payment with your backend
    const response = await fetch('/api/payments/process', {
      method: 'POST',
      body: JSON.stringify(paymentData)
    });
    const result = await response.json();
    
    return {
      ...paymentData,
      status: result.status, // 'success', 'failed', or 'cancelled'
      hostappOrderId: result.orderId,
      transactionId: result.transactionId, // optional
    };
  },
});

// Optional: listen for payment completion
sdk.onPaymentComplete((success, data) => {
  if (success) {
    console.log('Payment succeeded:', data);
  }
});

Important Notes:

  • When onPaymentRequest is set, the SDK automatically tells the miniapp it supports AppBoxoWebAppPay, so it can call appboxo.pay().
  • If onPaymentRequest is not configured, payment requests will fail. Enable debug: true to see error messages.
  • About debug mode:
    • debug: false (default): No console logs are output. Suitable for production.
    • debug: true: All SDK operations are logged to console. Useful for development and troubleshooting.
    • The debug option does not affect SDK functionality - it only controls console logging.

Locale/Language

Set the locale/language code to pass to the miniapp. The locale will be included in the InitData response.

// Set locale during initialization
const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id",
  locale: "en-US"  // or 'ru', 'zh-CN', etc.
});

// Or set locale dynamically
sdk.setLocale("ru");

The locale is passed to the miniapp via InitData.data.locale on the next AppBoxoWebAppGetInitData request.

Important Notes:

  • If you call setLocale() after the miniapp has already loaded, the locale will be included in the next InitData request. The miniapp may need to reload or request InitData again to receive the updated locale.
  • To ensure the locale is available immediately, set it during SDK initialization or before calling mount().

Theme/Dark Mode

Set the theme/color scheme preference to pass to the miniapp. The theme will be included in the InitData response.

// Set theme during initialization
const sdk = new AppboxoWebSDK({
  clientId: "your-client-id",
  appId: "your-app-id",
  theme: "dark"  // or 'light', 'system'
});

// Or set theme dynamically
sdk.setTheme("light");

The theme is passed to the miniapp via InitData.data.theme on the next AppBoxoWebAppGetInitData request.

Theme values:

  • 'dark': Force dark mode
  • 'light': Force light mode
  • 'system': Use system preference (default)

Important Notes:

  • If you call setTheme() after the miniapp has already loaded, the theme will be included in the next InitData request. The miniapp may need to reload or request InitData again to receive the updated theme.
  • To ensure the theme is available immediately, set it during SDK initialization or before calling mount().

Logout

The logout() method clears the host app's storage and SDK's internal authentication data.

sdk.logout();

Important Notes:

  • This only clears the host app's localStorage and sessionStorage
  • Miniapp's storage is separate (different origin) and cannot be cleared from the host app due to browser security restrictions
  • The SDK will send a logout notification to the miniapp via postMessage using the standard appboxo-host-response format
  • Miniapp should listen for AppBoxoWebAppLogout handler to clear its own storage
  • SDK's internal authCode and authTokens are also cleared

Miniapp Integration:

To receive logout notifications in your miniapp, add a message listener:

useEffect(() => {
  const handleMessage = (event: MessageEvent) => {
    if (
      event.data?.type === "appboxo-host-response" &&
      event.data?.handler === "AppBoxoWebAppLogout" &&
      event.data?.data?.action === "logout"
    ) {
      // Clear miniapp's storage
      localStorage.clear();
      sessionStorage.clear();
    }
  };
  
  window.addEventListener("message", handleMessage);
  return () => window.removeEventListener("message", handleMessage);
}, []);

Methods

MethodDescription
setAuthCode(code)Set authentication code
setAuthTokens(token, refreshToken?)Set authentication tokens directly
setLocale(locale)Set locale/language code (e.g., 'en', 'en-US', 'ru', 'zh-CN')
setTheme(theme)Set theme/color scheme preference ('dark'
onAuth(callback)Register callback for authentication events
mount(config)Create iframe and initialize SDK
getMiniappUrl()Fetch miniapp URL from API settings endpoint
setIframe(iframe)Set iframe element manually
initialize()Start listening for events
onEvent(type, handler)Register custom event handler
onLoginComplete(callback)Login completion callback
onPaymentComplete(callback)Payment completion callback
logout()Clear host app's localStorage, sessionStorage, and SDK's internal auth data
destroy()Clean up resources

Events

SDK handles these miniapp events:

  • AppBoxoWebAppLogin - User authentication
  • AppBoxoWebAppPay - Payment processing
  • AppBoxoWebAppGetInitData - Initial data request
  • AppBoxoWebAppCustomEvent - Custom events

Examples

React Example

import { AppboxoWebSDK } from "@appboxo/web-sdk";
import type { PaymentRequest, PaymentResponse } from "@appboxo/web-sdk";

function App() {
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const [sdk, setSdk] = useState<AppboxoWebSDK | null>(null);

  useEffect(() => {
    const s = new AppboxoWebSDK({ 
      clientId: "your-client-id", 
      appId: "your-app-id",
      onPaymentRequest: async (paymentData: PaymentRequest): Promise<PaymentResponse> => {
        const response = await fetch('/api/payments/process', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(paymentData)
        });
        const result = await response.json();
        
        return {
          ...paymentData,
          status: result.status,
          hostappOrderId: result.hostappOrderId,
        };
      },
    });
    
    s.setAuthCode("your-auth-code");
    
    s.onLoginComplete((success, data) => {
      console.log('Login:', success ? 'success' : 'failed', data);
    });
    s.onPaymentComplete((success, data) => {
      console.log('Payment:', success ? 'success' : 'failed', data);
    });
    
    setSdk(s);
    return () => s.destroy();
  }, []);

  useEffect(() => {
    const fetchUrl = async () => {
      if (sdk && iframeRef.current) {
        const url = await sdk.getMiniappUrl();
        iframeRef.current.src = url;
      }
    };
    fetchUrl();
  }, [sdk]);

  const handleLoad = () => {
    if (sdk && iframeRef.current) {
      sdk.setIframe(iframeRef.current);
      sdk.initialize();
    }
  };

  return <iframe ref={iframeRef} onLoad={handleLoad} src="" />;
}

Using mount helper

// SDK will automatically fetch miniapp URL from API
await sdk.mount({
  container: '#miniapp-container',
  className: 'miniapp-iframe'
});

Styling is handled via CSS:

.miniapp-container {
  width: 100%;
  height: 500px;
}

.miniapp-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

License

Apache-2.0

版本与发布记录

@appboxo/web-sdk 共发布 32 个版本,首次发布于 2025/10/29;过去 12 个月发布了 9 个版本。

版本发布日期距今
1.4.4latest2026/02/268 个月前
1.4.32025/12/2810 个月前
1.4.22025/12/1710 个月前
1.4.12025/12/1710 个月前
1.4.02025/12/0111 个月前
1.3.32025/11/1911 个月前

关于 @appboxo/web-sdk 的常见问题

@appboxo/web-sdk 是什么?

Boxo Desktop Host App SDK for handling miniapp events

如何安装 @appboxo/web-sdk?

在项目目录运行 npm install @appboxo/web-sdk,或使用 pnpm add / yarn add / bun add。

@appboxo/web-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@appboxo/web-sdk 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@appboxo/web-sdk 可以商用吗?

@appboxo/web-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@appboxo/web-sdk 的下载量有多少?

根据 npm 官方下载统计,@appboxo/web-sdk 在 2026/10/07 – 2026/11/05 这 30 天内被下载 3,215 次,日均约 107 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@appboxo/web-sdk 还在维护吗?

最新版本 1.4.4 发布于 2026/02/26(8 个月前);至今共发布 32 个版本,其中过去 12 个月发布了 9 个;首次发布于 2025/10/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。