@getspot/spot-widget

中文文档
4.8.0发布于 2026/10/30TypeScriptESM + CJS零依赖近 30 天下载 8193

Core JavaScript/ TypeScript 库,用于将 Spot 的退款担保部件集成到您的应用程序中 .

中文使用文档
文档目录31 节
  1. 安装
  2. 快速启动
  3. 类型脚本支持
  4. 配置
  5. SpotWidget 选项
  6. 图像配置
  7. 引用请求数据
  8. 部件方法
  9. 更新引文( 新引文请求数据)
  10. 获取选择( C)
  11. 校验选中项( C)
  12. 销毁()
  13. 回电
  14. optIn( 数据: 选择数据)
  15. optOut( 数据: 选择数据)
  16. 引文使用过时参数coauthors (帮助)
  17. 错误( 错误: 错误数据)
  18. 无匹配引文( 数据)
  19. 样式
  20. 处理错误
  21. 环境
  22. 沙盒( 开发)
  23. 生产
  24. API 参考
  25. 接口
  26. 数字
  27. 类型异名
  28. 框架整合
  29. 浏览器支持
  30. 许可证
  31. 支助

@ getspot/ spot- widget (英语)

Core JavaScript/ TypeScript 库,用于将 Spot 的退款担保部件集成到您的应用程序中 .

安装

npm install @getspot/spot-widget

快速启动

import SpotWidget from '@getspot/spot-widget';

// Create widget instance
const widget = new SpotWidget({
  location: '#spot-widget-container', // CSS selector or DOM element
  apiConfig: {
    environment: 'production', // 'sandbox' for testing
    partnerId: 'your-partner-id'
  },
  quoteRequestData: {
    startDate: '2024-01-01T00:00:00Z',
    endDate: '2024-01-07T23:59:59Z',
    currencyCode: 'USD',
    eventType: 'Ski Trip',
    productType: 'Trip',
    productDuration: 'Trip',
    productPrice: 500,
    productId: 'ski-trip-2024',
    cartId: 'cart-123',
    productName: 'Aspen Ski Trip 2024'
  },
  callbacks: {
    onOptIn: (data) => {
      console.log('User opted in:', data);
      // Handle opt-in logic
    },
    onOptOut: (data) => {
      console.log('User opted out:', data);
      // Handle opt-out logic
    },
    onQuoteRetrieved: (quote) => {
      console.log('Quote retrieved:', quote);
    },
    onError: (error) => {
      console.error('Widget error:', error);
    }
  }
});

类型脚本支持

此软件包以 TypeScript 写成,包含完整类型定义.

import SpotWidget, { SpotWidgetOptions, SelectionData, Quote } from '@getspot/spot-widget';

const options: SpotWidgetOptions = {
  // ... your configuration
};

const widget = new SpotWidget(options);

配置

SpotWidget 选项

选项类型需求默认说明
locationstring | HTMLElement没有"body"部件的目标元素
apiConfigApiConfig对- 说吧API 配置
quoteRequestDataQuoteRequestData对- 说吧引用请求信息
showTableboolean没有true是否显示支付表
selectionSelectionEnum没有SelectionEnum.UNSELECTED部件的初始选择状态
themeTheme没有- 说吧自定义样式
callbacksCallbacks没有{}事件召回
statestring没有- 说吧客户的2个字母的美国州号(例如. "TX") (中文(简体) ). 仅适用于通行证/Trip报盘——未登记。 提供时,会隐藏州选取器,并将数值传递给下游呼叫. 在省略时,选择器会自动显示.

图像配置

{
  environment: 'production' | 'sandbox' | 'local';
  partnerId: string;
  customEndpoint?: string; // Optional custom API endpoint
}

引用请求数据

单一产品引文

{
  startDate: string;        // ISO 8601 date
  endDate: string;          // ISO 8601 date
  currencyCode: 'USD' | 'CAD' | 'AUD' | 'NZD' | 'EUR' | 'MXN' | 'AED' | 'GBP' | 'MAD' | 'SAR' | 'BGN' | 'BRL' | 'CHF' | 'DKK' | 'INR' | 'JPY' | 'MYR' | 'NOK' | 'PLN' | 'SEK' | 'SGD' | 'THB' | 'ZAR';
  eventType: string;        // Event description
  productType: 'Pass' | 'Trip' | 'Registration';
  productDuration: 'Daily' | 'Seasonal' | 'Trip' | 'Event';
  productPrice: number;     // Price in specified currency
  productId: string;        // Unique product identifier
  cartId: string;           // Shopping cart identifier
  productName: string;      // Human-readable product name
  participantDescription?: string; // Optional participant info
}

批量引文(多产品)

{
  cartId: string;
  cartName: string;
  currencyCode: 'USD' | 'CAD' | 'AUD' | 'NZD' | 'EUR' | 'MXN' | 'AED' | 'GBP' | 'MAD' | 'SAR' | 'BGN' | 'BRL' | 'CHF' | 'DKK' | 'INR' | 'JPY' | 'MYR' | 'NOK' | 'PLN' | 'SEK' | 'SGD' | 'THB' | 'ZAR';
  items: Array<{
    // All single product fields except cartId and currencyCode
    cartItemId?: string; // Optional item identifier
  }>;
}

部件方法

更新引文( 新引文请求数据)

用新引号数据更新部件 .

const success = await widget.updateQuote({
  // new quote request data
});
console.log('Update successful:', success);

回返情况: Promise<boolean>

获取选择( C)

获取当前用户选择 .

const selection = widget.getSelection();
console.log('User selection:', selection);

回返情况: SelectionData | null

校验选中项( C)

检查用户是否进行了选择 .

const isValid = widget.validateSelection();
if (!isValid) {
  console.log('Please make a selection');
}

回返情况: boolean

销毁()

清理部件实例 .

widget.destroy();

回电

optIn( 数据: 选择数据)

用户选择加入退款担保时调用 .

{
  onOptIn: (data) => {
    console.log('Opt-in data:', data);
    // data.status === 'QUOTE_ACCEPTED'
    // data.quoteId - unique quote identifier
    // data.spotPrice - refund guarantee price
  }
}

optOut( 数据: 选择数据)

用户选择退出退款担保时调用 .

{
  onOptOut: (data) => {
    console.log('Opt-out data:', data);
    // data.status === 'QUOTE_DECLINED'
    // data.quoteId - unique quote identifier
  }
}

引文使用过时参数coauthors (帮助)

成功取回引号时调用 .

{
  onQuoteRetrieved: (quote) => {
    console.log('Quote:', quote);
    // quote.id - quote identifier
    // quote.spotPrice - refund guarantee price
    // quote.communication - display text and labels
  }
}

错误( 错误: 错误数据)

发生错误时调用 .

{
  onError: (error) => {
    console.error('Error:', error);
    // error.message - error description
    // error.status - HTTP status code (if applicable)
    // error.responseBody - API response (if applicable)
  }
}

无匹配引文( 数据)

请求中无引文时调用.

{
  noMatchingQuote: (data) => {
    console.log('No quote available:', data);
    // Handle case where product isn't eligible
  }
}

样式

使用 theme 选项 :

const widget = new SpotWidget({
  // ... other options
  theme: {
    primaryColor: '#007bff',
    secondaryColor: '#6c757d',
    borderRadius: '8px',
    fontFamily: 'Arial, sans-serif',
    fontSize: '14px'
    // Any CSS custom properties (without -- prefix)
  }
});

处理错误

总是进行全面的错误处理 :

const widget = new SpotWidget({
  // ... configuration
  callbacks: {
    onError: (error) => {
      // Log for debugging
      console.error('Spot Widget Error:', error);
      
      // Handle different error types
      if (error.status === 404) {
        console.log('Product not eligible for refund guarantee');
      } else if (error.status >= 500) {
        console.log('Service temporarily unavailable');
      }
      
      // Track in analytics
      if (window.analytics) {
        window.analytics.track('spot_widget_error', {
          message: error.message,
          status: error.status
        });
      }
    },
    noMatchingQuote: (data) => {
      console.log('No refund guarantee available');
      // Hide widget or show alternative messaging
    }
  }
});

环境

沙盒( 开发)

使用沙盒环境进行测试 :

{
  apiConfig: {
    environment: 'sandbox',
    partnerId: 'your-sandbox-partner-id'
  }
}

生产

利用生产环境进行现场应用:

{
  apiConfig: {
    environment: 'production',
    partnerId: 'your-production-partner-id'
  }
}

API 参考

此套件导出以下类型和接口 :

接口

图像配置

export interface ApiConfig {
  environment: "sandbox" | "production" | "local";
  partnerId: string;
  customEndpoint?: string;
}

引用元数据

export interface QuoteMetadata {
  segment?: string;
  operator?: string;
  channel?: string;
  consumerId?: string;
}

引文项目

export interface QuoteItem {
  productPrice: number;
  productType: "Pass" | "Trip" | "Registration";
  productDuration: "Daily" | "Seasonal" | "Trip" | "Event";
  productId: string;
  cartId: string;
  cartItemId?: string;
  cartName: string;
  productName: string;
  participantDescription?: string;
  eventType: string;
  eventId?: string;
  currencyCode:
    | "USD"
    | "CAD"
    | "AUD"
    | "NZD"
    | "EUR"
    | "MXN"
    | "AED"
    | "GBP"
    | "MAD"
    | "SAR"
    | "BGN"
    | "BRL"
    | "CHF"
    | "DKK"
    | "INR"
    | "JPY"
    | "MYR"
    | "NOK"
    | "PLN"
    | "SEK"
    | "SGD"
    | "THB"
    | "ZAR";
  startDate: string;
  endDate: string;
  partnerRiskEnd?: Date;
  metadata?: QuoteMetadata;
  isPartialPayment?: boolean;
  hostCountry?: string;
  hostCountryState?: string;
  destinations?: string[];
  dob?: string;
  roundTo?: number;
}

批次引用请求

export interface BatchQuoteRequest {
  cartId: string;
  cartName: string;
  currencyCode:
    | "USD"
    | "CAD"
    | "AUD"
    | "NZD"
    | "EUR"
    | "MXN"
    | "AED"
    | "GBP"
    | "MAD"
    | "SAR"
    | "BGN"
    | "BRL"
    | "CHF"
    | "DKK"
    | "INR"
    | "JPY"
    | "MYR"
    | "NOK"
    | "PLN"
    | "SEK"
    | "SGD"
    | "THB"
    | "ZAR";
  metadata?: QuoteMetadata;
  isPartialPayment?: boolean;
  roundTo?: number;
  items: BatchQuoteItem[];
}

认证Reason

export interface QualifyingReason {
  rank: number;
  name?: string;
  benefitType?: {
    name: string;
  };
}

附表项目

export interface PayoutScheduleItem {
  text: string;
  percent: string | number;
  amount: number;
}

通讯

export interface Communication {
  name: string;
  description: string;
  bulletPoints: string[];
  yesOptionText: string;
  noOptionText: string;
  legalDisclaimer: string;
  termsAndConditionsUrl: string;
  paymentTerms?: string;
}

引用

export interface Quote {
  id: string;
  cartItemId?: string;
  spotPrice: number;
  currencyCode: string;
  communication: Communication;
  payoutSchedule: PayoutScheduleItem[];
  qualifyingReasons?: QualifyingReason[];
  coveredItems?: string[];
  originalQuotes?: Quote[];
}

引文更新

export interface QuoteUpdates {
  spotPriceWithFees?: number;
}

回复

export interface ApiResponse {
  status: "QUOTE_AVAILABLE" | "QUOTES_AVAILABLE" | "NO_MATCHING_QUOTE";
  data?: Quote;
  quotes?: Quote[];
  totalSpotPrice?: number;
  spotPrice?: number;
  currencyCode?: string;
  communication?: Communication;
  payoutSchedule?: PayoutScheduleItem[];
  coveredItems?: string[];
}

选择数据

export interface SelectionData {
  status: "QUOTE_ACCEPTED" | "QUOTE_DECLINED";
  spotPrice?: number;
  quoteId?: string;
  selection?: string;
  /**
   * Customer's US state code (e.g. "TX"). Set when:
   * - The partner passes a `state` prop (captured at their checkout), or
   * - The user selects a US state from the selector shown on Pass/Trip offers.
   * Undefined when neither applies.
   */
  state?: string;
  batchQuoteDetails?: Array<{
    quoteId: string;
    productPrice: number;
    cartItemId: string;
  }>;
}

回电

export interface Callbacks {
  onOptIn?: (data: SelectionData) => void;
  onOptOut?: (data: SelectionData) => void;
  onQuoteRetrieved?: (quote: Quote) => QuoteUpdates | void;
  onError?: (error: { message: string; status?: number; responseBody?: any }) => void;
  noMatchingQuote?: (data: { status: string; data: QuoteRequestData }) => void;
}

主题

export interface Theme {
  [key: string]: string;
}

SpotWidget 选项

export interface SpotWidgetOptions {
  location?: string | HTMLElement;
  showTable?: boolean;
  selection?: SelectionEnum;
  logoPosition?: "bottom-right" | "top-right";
  apiConfig: ApiConfig;
  quoteRequestData: QuoteRequestData;
  callbacks?: Callbacks;
  theme?: Theme;
  isPartialPayment?: boolean;
  useMockData?: boolean;
  mockData?: ApiResponse;
  // Response the widget should return from the residency re-fetch when useMockData is true.
  // Pass a function to vary the response by residency (e.g. return NO_MATCHING_QUOTE only when
  // isUSResident === false). Used by Storybook to exercise ST-5408 flows without a backend.
  // When omitted, re-fetch reuses `mockData`.
  // Accepts a Promise or an async function so Storybook can simulate a slow backend and show
  // the radios locking the instant the re-fetch starts (independent of when it resolves).
  mockRefetchData?:
    | ApiResponse
    | Promise<ApiResponse>
    | ((isUSResident: boolean | undefined) => ApiResponse | Promise<ApiResponse>);
  state?: string;
}

元素选项

export interface ElementOptions {
  text?: string;
  className?: string;
  parent?: HTMLElement;
  innerHTML?: string;
  href?: string;
  target?: string;
}

数字

选择

export enum SelectionEnum {
  YES = 'yes',
  NO = 'no',
  UNSELECTED = 'unselected',
}

类型异名

引用请求数据

export type QuoteRequestData = QuoteItem | BatchQuoteRequest | QuoteItem[];

框架整合

这是核心图书馆。 对于特定框架的包装:

浏览器支持

  • 现代浏览器(ES2020+)
  • 克罗姆80+
  • Firefox 74+ (英语)
  • 萨法里13+
  • 边80+

许可证

许可证信息见主包.

支助

支助请联系 支持@ getspot.com。 。 。 .

版本与发布记录

@getspot/spot-widget 共发布 54 个版本,首次发布于 2025/04/25;过去 12 个月发布了 31 个版本。

版本发布日期距今
4.8.0latest2026/10/3017 天前
4.7.02026/09/221 个月前
4.6.02026/08/123 个月前
4.5.02026/08/063 个月前
4.4.22026/08/053 个月前
4.4.12026/07/233 个月前

关于 @getspot/spot-widget 的常见问题

@getspot/spot-widget 是什么?

Core JavaScript/ TypeScript 库,用于将 Spot 的退款担保部件集成到您的应用程序中 .

如何安装 @getspot/spot-widget?

在项目目录运行 npm install @getspot/spot-widget,或使用 pnpm add / yarn add / bun add。

@getspot/spot-widget 支持 TypeScript 吗?

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

@getspot/spot-widget 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@getspot/spot-widget 可以商用吗?

@getspot/spot-widget 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@getspot/spot-widget 的下载量有多少?

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

@getspot/spot-widget 还在维护吗?

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