# @getspot/spot-widget 中文文档

规范地址：https://npmcn.com/package/%40getspot/spot-widget/

版本：4\.8\.0
npm 元数据更新时间：2026-11-05T16:01:11.126Z
中文译文更新时间：2026-11-16T06:50:42.523Z
软件包许可：未声明

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40getspot/spot-widget
原文对照：https://npmcn.com/package/%40getspot/spot-widget/?lang=original

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：185 kB，27 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2025-04-24T16:53:51.767Z
- 最新版本发布：2026-10-29T16:18:39.095Z
- 近 30 天下载量：8193（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：54（近 12 个月 31 个）

## 中文简介

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

## 安装

```sh
npm install @getspot/spot-widget
```

也可以使用：`pnpm add @getspot/spot-widget`、`yarn add @getspot/spot-widget`、`bun add @getspot/spot-widget`

## README

# @ getspot/ spot- widget (英语)

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

## 安装

```bash
npm install @getspot/spot-widget
```

## 快速启动

```javascript
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 写成,包含完整类型定义.

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

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

const widget = new SpotWidget(options);
```

## 配置

### SpotWidget 选项

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

### 图像配置

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

### 引用请求数据

#### 单一产品引文

```typescript
{
  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
}
```

#### 批量引文(多产品)

```typescript
{
  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
  }>;
}
```

## 部件方法

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

用新引号数据更新部件 .

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

**回返情况:** `Promise<boolean>`

### 获取选择( C)

获取当前用户选择 .

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

**回返情况:** `SelectionData | null`

### 校验选中项( C)

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

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

**回返情况:** `boolean`

### 销毁()

清理部件实例 .

```javascript
widget.destroy();
```

## 回电

### optIn( 数据: 选择数据)

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

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

### optOut( 数据: 选择数据)

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

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

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

成功取回引号时调用 .

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

### 错误( 错误: 错误数据)

发生错误时调用 .

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

### 无匹配引文( 数据)

请求中无引文时调用.

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

## 样式

使用 `theme` 选项 :

```javascript
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)
  }
});
```

## 处理错误

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

```javascript
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
    }
  }
});
```

## 环境

### 沙盒( 开发)

使用沙盒环境进行测试 :

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

### 生产

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

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

## API 参考

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

### 接口

#### 图像配置

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

#### 引用元数据

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

#### 引文项目

```typescript
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;
}
```

#### 批次引用请求

```typescript
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

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

#### 附表项目

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

#### 通讯

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

#### 引用

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

#### 引文更新

```typescript
export interface QuoteUpdates {
  spotPriceWithFees?: number;
}
```

#### 回复

```typescript
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[];
}
```

#### 选择数据

```typescript
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;
  }>;
}
```

#### 回电

```typescript
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;
}
```

#### 主题

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

#### SpotWidget 选项

```typescript
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;
}
```

#### 元素选项

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

### 数字

#### 选择

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

### 类型异名

#### 引用请求数据

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

## 框架整合

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

-   **反应**数字 : [@ getspot/ spot- widget- react](https://npmcn.com/package/%40getspot/react)
-   **第3组**数字 : [@ getspot/ spot- widget- veue](https://npmcn.com/package/%40getspot/vue)
-   **备选案文2**数字 : [@ getspot/ spot- widget- vue2](https://npmcn.com/package/%40getspot/vue2)

## 浏览器支持

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

## 许可证

许可证信息见主包.

## 支助

支助请联系 [支持@ getspot.com](mailto:support@getspot.com)。 。 。 .

## 常见问题

### @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 和提交记录判断。

