Ga naar inhoud

Dcart API

Overzicht

De Discount API biedt een uitgebreid systeem voor het beheren van kortingscodes en cadeaubonnen in je Shopify-winkel. Met deze API kun je programmatisch kortingen toepassen, besparingen berekenen en kortingsfunctionaliteit in je webshop integreren.

Aan de slag

Basisinstelling

De Discount API wordt automatisch geïnitialiseerd zodra je app laadt. Je kunt hem meteen gebruiken via het globale object 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');
});

Kernfunctionaliteit

Kortingscodes toepassen

Gebruik de methode apply() om kortingscodes voor klanten te activeren.

Een enkele kortingscode toepassen:

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

Meerdere kortingscodes toepassen:

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

Opmerking: Kortingscodes worden automatisch omgezet naar kleine letters en van witruimte ontdaan.

Kortingscodes verwijderen

Verwijder actieve kortingscodes met de methode remove().

Een specifieke kortingscode verwijderen:

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

Alle actieve kortingscodes verwijderen:

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

Cadeaubonnen beheren

Verwijder toegepaste cadeaubonnen met hun unieke identificatie.

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

Kortingen berekenen

Bekijk kortingsberekeningen zonder ze op de winkelwagen toe te passen.

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

Eventsysteem

De Discount API biedt een uitgebreid eventsysteem om kortingsactiviteiten bij te houden en te integreren met je eigen code.

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

Beschikbare events

dcartAPI.Events.Discount.Calculated

Wordt afgevuurd wanneer kortingsberekeningen zijn voltooid of opnieuw zijn uitgevoerd.

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

Gebruiksmogelijkheden:

  • Aangepaste totaalweergaven bijwerken
  • Winkelwagenoverzichten verversen
  • Analytics-events activeren

dcartAPI.Events.Discount.Apply

Wordt afgevuurd wanneer op de knop apply wordt geklikt, voordat de korting wordt verwerkt.

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

Gebruiksmogelijkheden:

  • Laadstatussen tonen
  • Kortingscodes valideren voordat ze worden verstuurd
  • Gebruikersinteracties bijhouden

dcartAPI.Events.Discount.Applied

Wordt afgevuurd wanneer een kortingscode met succes aan de winkelwagen is toegevoegd.

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

Gebruiksmogelijkheden:

  • Succesberichten tonen
  • Winkelwagenweergaven bijwerken
  • Succesvolle kortingstoepassingen bijhouden
  • Promotionele workflows activeren

dcartAPI.Events.Discount.Removed

Wordt afgevuurd wanneer een kortingscode uit de winkelwagen wordt verwijderd.

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

Gebruiksmogelijkheden:

  • Winkelwagenweergaven bijwerken
  • Promotieberichten verwijderen
  • Verwijderde kortingen bijhouden
  • Promotionele statussen resetten

Compleet voorbeeld van eventintegratie

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

Foutafhandeling

Implementeer altijd goede foutafhandeling voor kortingsoperaties:

// 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

Prestatieoverwegingen

  • Batch-bewerkingen : Gebruik bij het toepassen van meerdere codes één apply()-aanroep met een array
  • Eventthrottling : Debounce snelle kortingsberekeningen om prestatieproblemen te voorkomen
  • Foutherstel : Implementeer retrylogica voor netwerkfouten

Gebruikerservaring

  • Laadstatussen : Toon altijd laadindicatoren tijdens kortingsoperaties
  • Duidelijke feedback : Geef direct feedback wanneer kortingen worden toegepast of verwijderd
  • Validatie : Valideer kortingscodes aan de clientkant wanneer dat kan, zodat er minder serververzoeken nodig zijn

Integratierichtlijnen

  • Volgorde van events : Abonneer je op events nadat de API is geïnitialiseerd
  • Geheugenbeheer : Stop met luisteren naar events wanneer componenten worden verwijderd
  • Fallback-afhandeling : Implementeer fallbacks voor het geval de API niet beschikbaar is

Veelvoorkomende toepassingen

Kortingen uit de URL automatisch toepassen

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

Aftelling voor promoties

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

A/B-testintegratie

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-referentie

Methoden

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

Past een of meer kortingscodes toe op de winkelwagen.

Parameters:

  • codes: Een enkele kortingscode als string, of een array van kortingscodes

Retourneert: een Promise die resolvet wanneer de codes zijn toegepast

remove(code?: string): Promise

Verwijdert een specifieke kortingscode, of alle codes als er geen code is opgegeven.

Parameters:

  • code (optioneel): De te verwijderen kortingscode. Als je dit weglaat, worden alle codes verwijderd

Retourneert: een Promise die resolvet wanneer de code(s) zijn verwijderd

removeGiftCard(id: string): Promise

Verwijdert een cadeaubon uit de winkelwagen.

Parameters:

  • id: De ID van de te verwijderen cadeaubon

Retourneert: een Promise die resolvet wanneer de cadeaubon is verwijderd

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

Berekent kortingsbedragen zonder ze toe te passen.

Parameters:

  • codes: Array van kortingscodes om te berekenen
  • items: Array van winkelwagenartikelen om tegen te berekenen

Retourneert: een Promise die resolvet met de kortingsberekeningsgegevens

setCustomConfig(config: Record): void

Stelt aangepaste configuratieopties in.

Parameters:

  • config: Configuratieobject met aangepaste instellingen

cloneAndInjectInfo(targetSelector: string): void

Kloont kortingsinformatie naar een doelelement.

Parameters:

  • targetSelector: CSS-selector voor het doelelement

Events

Event Beschrijving
Discount.Calculated Kortingsberekeningen voltooid
Discount.Apply Knop apply geklikt
Discount.Applied Korting succesvol toegepast
Discount.Removed Korting uit de winkelwagen verwijderd

Problemen oplossen

Veelvoorkomende problemen

Kortingen worden niet toegepast

  • Controleer of de kortingscode geldig en actief is
  • Controleer of de winkelwagen aan de minimumeisen voldoet
  • Zorg dat de API correct is geïnitialiseerd

Events worden niet afgevuurd

  • Controleer of de event-abonnementen plaatsvinden nadat de API is geïnitialiseerd
  • Controleer de console op JavaScript-fouten
  • Controleer of de eventnamen correct zijn gespeld

Totalen worden niet bijgewerkt

  • Controleer of de totaalselectors correct zijn geconfigureerd
  • Controleer of de aangepaste configuratie geen noodzakelijke elementen uitsluit
  • Zorg dat de paginaelementen bestaan wanneer de totalen worden berekend

Hulp nodig? Schrijf naar support@syncu.be.