Dcart API¶
概述¶
Discount API 提供了一套完整的系统,用于管理 Shopify 店铺中的折扣码和礼品卡。通过该 API,您可以以编程方式应用折扣、计算节省金额,并将折扣功能集成到您的店面中。
入门¶
基本设置¶
应用加载时会自动初始化 Discount API。您可以直接通过全局对象 dcartAPI 开始使用。
// Wait for the API to be ready
window.addEventListener('DCART:appApi.initialized', function() {
// API is now ready to use
console.log('Discount API ready');
});
核心功能¶
应用折扣码¶
使用 apply() 方法为客户激活折扣码。
应用单个折扣码:
dcartAPI.apply('SAVE20')
.then(() => {
console.log('Discount applied successfully');
})
.catch((error) => {
console.error('Failed to apply discount:', error);
});
应用多个折扣码:
dcartAPI.apply(['SAVE20', 'FREESHIP'])
.then(() => {
console.log('All discounts applied successfully');
});
注意: 折扣码会自动转换为小写,并去除首尾空白。
移除折扣码¶
使用 remove() 方法移除已生效的折扣码。
移除指定的折扣码:
dcartAPI.remove('SAVE20')
.then(() => {
console.log('Discount removed successfully');
});
移除所有已生效的折扣码:
dcartAPI.remove()
.then(() => {
console.log('All discounts removed');
});
管理礼品卡¶
使用已应用礼品卡的唯一标识符将其移除。
dcartAPI.removeGiftCard('giftcard_id_here')
.then(() => {
console.log('Gift card removed successfully');
});
计算折扣¶
在不将折扣应用到购物车的情况下预览折扣计算结果。
const discountCodes = ['SAVE20', 'FREESHIP'];
const cartItems = [
{ id: 123, quantity: 2, price: 2500 },
{ id: 456, quantity: 1, price: 1000 }
];
dcartAPI.calculate(discountCodes, cartItems)
.then((discountData) => {
console.log('Calculated savings:', discountData);
// discountData contains totals, savings, and applied discounts
});
事件系统¶
Discount API 提供了完整的事件系统,用于跟踪折扣相关活动,并与您的自定义代码集成。
订阅事件¶
window.addEventListener('DCART:appApi.initialized', function() {
// Subscribe to discount events
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Applied, function(data) {
console.log('Discount was applied:', data);
});
});
可用事件¶
dcartAPI.Events.Discount.Calculated¶
在折扣计算完成或重新计算时触发。
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Calculated, function(discountData) {
console.log('Discount calculated:', discountData);
// Update UI with new totals
updateCartTotals(discountData);
});
使用场景:
- 更新自定义总计显示
- 刷新购物车摘要
- 触发分析事件
dcartAPI.Events.Discount.Apply¶
在点击应用按钮时触发,早于折扣处理。
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Apply, function(data) {
console.log('User clicked apply button');
// Show loading indicator
showLoadingSpinner();
});
使用场景:
- 显示加载状态
- 提交前验证折扣码
- 跟踪用户交互
dcartAPI.Events.Discount.Applied¶
在折扣码成功应用到购物车时触发。
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Applied, function(data) {
console.log('Discount successfully applied:', data);
// Show success message
showSuccessMessage('Discount applied!');
// Track conversion
gtag('event', 'discount_applied', { discount_code: data.code });
});
使用场景:
- 显示成功消息
- 更新购物车显示
- 跟踪成功应用的折扣
- 触发促销工作流
dcartAPI.Events.Discount.Removed¶
在折扣码从购物车中移除时触发。
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Removed, function(data) {
console.log('Discount removed:', data);
// Update UI to reflect removal
removeDiscountFromDisplay(data.code);
});
使用场景:
- 更新购物车显示
- 移除促销消息
- 跟踪折扣移除情况
- 重置促销状态
完整事件集成示例¶
(function() {
window.addEventListener('DCART:appApi.initialized', function() {
// Track all discount interactions
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Apply, function() {
// User started applying discount
document.querySelector('.discount-form').classList.add('loading');
});
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Applied, function(data) {
// Discount successfully applied
document.querySelector('.discount-form').classList.remove('loading');
showNotification('Discount applied: ' + data.code, 'success');
// Track in analytics
if (typeof gtag !== 'undefined') {
gtag('event', 'discount_applied', {
discount_code: data.code,
discount_amount: data.amount
});
}
});
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Calculated, function(discountData) {
// Update custom total displays
const savings = discountData.originalTotal - discountData.total;
if (savings > 0) {
document.querySelector('.savings-display').textContent =
'You saved $' + (savings / 100).toFixed(2);
}
});
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Removed, function(data) {
// Handle discount removal
showNotification('Discount removed: ' + data.code, 'info');
document.querySelector('.savings-display').textContent = '';
});
});
})();
错误处理¶
对折扣操作务必实现适当的错误处理:
// Handle specific error types
dcartAPI.apply('INVALID_CODE') .then(() => { console.log('Success'); })
.catch((error) => {
console.error('Error applying discount:', error);
if (error.message.includes('expired')) {
showErrorMessage('This discount code has expired');
} else if (error.message.includes('invalid')) {
showErrorMessage('Invalid discount code');
} else {
showErrorMessage('Unable to apply discount. Please try again.');
}
});
最佳实践¶
性能注意事项¶
- 批量操作 :应用多个折扣码时,请传入数组,只调用一次
apply() - 事件节流 :对频繁触发的折扣计算进行防抖处理,以避免性能问题
- 错误恢复 :为网络故障实现重试逻辑
用户体验¶
- 加载状态 :折扣操作期间务必显示加载指示器
- 清晰的反馈 :折扣应用或移除后立即给出反馈
- 验证 :尽可能在客户端验证折扣码,以减少服务器请求
集成指南¶
- 事件顺序 :在 API 初始化完成后再订阅事件
- 内存管理 :组件销毁时取消订阅事件
- 降级处理 :为 API 不可用的情况实现降级方案
常见使用场景¶
自动应用 URL 中的折扣¶
// Check URL for discount parameters and auto-apply
const urlParams = new URLSearchParams(window.location.search);
const discountCode = urlParams.get('discount');
if (discountCode) {
window.addEventListener('DCART:appApi.initialized', function() {
dcartAPI.apply(discountCode);
});
}
促销倒计时集成¶
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Applied, function(data) {
// Start countdown timer for time-sensitive discounts
if (data.expiresAt) {
startCountdownTimer(data.expiresAt);
}
});
A/B 测试集成¶
dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Calculated, function(discountData) {
// Track discount effectiveness for A/B testing
analytics.track('discount_calculated', {
test_variant: getTestVariant(),
discount_amount: discountData.totalSavings,
cart_total: discountData.total
});
});
API 参考¶
方法¶
apply(codes: string | string[]): Promise¶
将一个或多个折扣码应用到购物车。
参数:
codes:单个折扣码字符串,或折扣码数组
返回值: 折扣码应用完成时解析的 Promise
remove(code?: string): Promise¶
移除指定的折扣码;若未指定,则移除所有折扣码。
参数:
code(可选):要移除的折扣码。若省略,则移除所有折扣码
返回值: 折扣码移除完成时解析的 Promise
removeGiftCard(id: string): Promise¶
从购物车中移除礼品卡。
参数:
id:要移除的礼品卡 ID
返回值: 礼品卡移除完成时解析的 Promise
calculate(codes: string[], items: any[]): Promise¶
计算折扣金额,但不予应用。
参数:
codes:要计算的折扣码数组items:用于计算的购物车商品数组
返回值: 解析为折扣计算数据的 Promise
setCustomConfig(config: Record): void¶
设置自定义配置选项。
参数:
config:包含自定义设置的配置对象
cloneAndInjectInfo(targetSelector: string): void¶
将折扣信息克隆到目标元素中。
参数:
targetSelector:目标元素的 CSS 选择器
事件¶
| 事件 | 说明 |
|---|---|
Discount.Calculated |
折扣计算完成 |
Discount.Apply |
点击了应用按钮 |
Discount.Applied |
折扣成功应用 |
Discount.Removed |
折扣从购物车中移除 |
故障排除¶
常见问题¶
折扣未生效
- 请确认折扣码有效且处于激活状态
- 检查购物车是否满足最低要求
- 确保 API 已正确初始化
事件未触发
- 确认事件订阅发生在 API 初始化之后
- 检查控制台中是否有 JavaScript 错误
- 确认事件名称拼写正确
总计未更新
- 检查总计选择器配置是否正确
- 确认自定义配置没有排除必要的元素
- 确保计算总计时页面元素已存在
需要帮助? 请发邮件至 support@syncu.be。