@ 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 选项
| 选项 | 类型 | 需求 | 默认 | 说明 |
|---|---|---|---|---|
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报盘——未登记。 提供时,会隐藏州选取器,并将数值传递给下游呼叫. 在省略时,选择器会自动显示. |
图像配置
{
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[];
框架整合
这是核心图书馆。 对于特定框架的包装:
- 反应数字 : @ getspot/ spot- widget- react
- 第3组数字 : @ getspot/ spot- widget- veue
- 备选案文2数字 : @ getspot/ spot- widget- vue2
浏览器支持
- 现代浏览器(ES2020+)
- 克罗姆80+
- Firefox 74+ (英语)
- 萨法里13+
- 边80+
许可证
许可证信息见主包.
支助
支助请联系 支持@ getspot.com。 。 。 .