DCART API Documentation

Overview

The Discount API provides a comprehensive system for managing discount codes and gift cards in your Shopify store. This API allows you to programmatically apply discounts, calculate savings, and integrate discount functionality into your storefront.

Getting Started

Basic Setup

The Discount API is automatically initialized when your app loads. You can start using it immediately through the global dcartAPI object.

// Wait for the API to be ready 
window.addEventListener('DCART:appApi.initialized', function() {
  // API is now ready to use
  console.log('Discount API ready');
});

Core Functionality

Applying Discount Codes

Use the apply() method to activate discount codes for customers.

Apply a single discount code:

dcartAPI.apply('SAVE20')
  .then(() => { 
      console.log('Discount applied successfully'); 
  }) 
  .catch((error) => { 
      console.error('Failed to apply discount:', error); 
  });

Apply multiple discount codes:

dcartAPI.apply(['SAVE20', 'FREESHIP'])
  .then(() => {
    console.log('All discounts applied successfully');
  });

> Note: Discount codes are automatically converted to lowercase and trimmed of whitespace.

Removing Discount Codes

Remove active discount codes using the remove() method.

Remove a specific discount code:

dcartAPI.remove('SAVE20')
  .then(() => {
    console.log('Discount removed successfully');
  });

Remove all active discount codes:

dcartAPI.remove()
  .then(() => {
    console.log('All discounts removed');
  });

Managing Gift Cards

Remove applied gift cards using their unique identifier.

dcartAPI.removeGiftCard('giftcard_id_here')
  .then(() => {
    console.log('Gift card removed successfully');
  });

Calculating Discounts

Preview discount calculations without applying them to the cart.

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

Event System

The Discount API provides a comprehensive event system for tracking discount activities and integrating with your custom code.

Subscribing to Events

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

Available Events

dcartAPI.Events.Discount.Calculated

Triggered when discount calculations are completed or recalculated.

dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Calculated, function(discountData) {
  console.log('Discount calculated:', discountData);
  // Update UI with new totals
  updateCartTotals(discountData);
});

Use cases: - Update custom total displays - Refresh cart summaries - Trigger analytics events

dcartAPI.Events.Discount.Apply

Triggered when the apply button is clicked, before the discount is processed.

dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Apply, function(data) {
  console.log('User clicked apply button');
  // Show loading indicator
  showLoadingSpinner();
});

Use cases: - Show loading states - Validate discount codes before submission - Track user interactions

dcartAPI.Events.Discount.Applied

Triggered when a discount code is successfully applied to the cart.

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

Use cases: - Display success messages - Update cart displays - Track successful discount applications - Trigger promotional workflows

dcartAPI.Events.Discount.Removed

Triggered when a discount code is removed from the cart.

dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Removed, function(data) {
  console.log('Discount removed:', data);
  // Update UI to reflect removal
  removeDiscountFromDisplay(data.code);
});

Use cases: - Update cart displays - Remove promotional messages - Track discount removals - Reset promotional states

Complete Event Integration Example

(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 = '';
});

}); })(); ```

Error Handling

Always implement proper error handling for discount operations:

// 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.');
    }
});

Best Practices

Performance Considerations

  • Batch Operations: When applying multiple codes, use a single apply() call with an array
  • Event Throttling: Debounce rapid discount calculations to prevent performance issues
  • Error Recovery: Implement retry logic for network failures

User Experience

  • Loading States: Always show loading indicators during discount operations
  • Clear Feedback: Provide immediate feedback when discounts are applied or removed
  • Validation: Validate discount codes client-side when possible to reduce server requests

Integration Guidelines

  • Event Ordering: Subscribe to events after the API is initialized
  • Memory Management: Unsubscribe from events when components are destroyed
  • Fallback Handling: Implement fallbacks for when the API is unavailable

Common Use Cases

Auto-Apply URL Discounts

// 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);
  });
}

Promotional Countdown Integration

dcartAPI.eventBus.subscribe(dcartAPI.Events.Discount.Applied, function(data) {
  // Start countdown timer for time-sensitive discounts
  if (data.expiresAt) {
    startCountdownTimer(data.expiresAt);
  }
});

A/B Testing Integration

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 Reference

Methods

apply(codes: string | string[]): Promise

Applies one or more discount codes to the cart.

Parameters: - codes - A single discount code string or array of discount codes

Returns: Promise that resolves when codes are applied

remove(code?: string): Promise

Removes a specific discount code or all codes if no code specified.

Parameters: - code (optional) - The discount code to remove. If omitted, removes all codes

Returns: Promise that resolves when code(s) are removed

removeGiftCard(id: string): Promise

Removes a gift card from the cart.

Parameters: - id - The gift card ID to remove

Returns: Promise that resolves when gift card is removed

calculate(codes: string[], items: any[]): Promise

Calculates discount amounts without applying them.

Parameters: - codes - Array of discount codes to calculate - items - Array of cart items to calculate against

Returns: Promise that resolves with discount calculation data

setCustomConfig(config: Record): void

Sets custom configuration options.

Parameters: - config - Configuration object with custom settings

cloneAndInjectInfo(targetSelector: string): void

Clones discount information to a target element.

Parameters: - targetSelector - CSS selector for the target element

Events

Event Description
Discount.Calculated Discount calculations completed
Discount.Apply Apply button clicked
Discount.Applied Discount successfully applied
Discount.Removed Discount removed from cart

Troubleshooting

Common Issues

Discounts Not Applying - Verify the discount code is valid and active - Check that the cart meets minimum requirements - Ensure the API is properly initialized

Events Not Firing - Confirm event subscriptions happen after API initialization - Check for JavaScript errors in the console - Verify event names are spelled correctly

Totals Not Updating - Check that total selectors are configured correctly - Verify custom configuration doesn't exclude necessary elements - Ensure the page elements exist when totals are calculated


Need Help? Contact our support team or check the developer documentation for additional technical details and advanced integration options.