JavaScript SDK Installation

The Loyalty.lt JavaScript SDK provides a simple, powerful way to integrate loyalty features into your web applications. It supports both browser and Node.js environments with TypeScript definitions included.

Installation

npm install @loyalty-lt/javascript-sdk

Basic Setup

Initialize the SDK

import { LoyaltySDK } from '@loyalty-lt/javascript-sdk';

const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  environment: 'staging', // or 'production'
  locale: 'en' // or 'lt'
});

Configuration Options

apiKey
string
required
Your Loyalty.lt API key from the Partners Portal
apiSecret
string
required
Your Loyalty.lt API secret from the Partners Portal
environment
string
default:"staging"
API environment: staging or production
locale
string
default:"en"
Language for API responses: en (English) or lt (Lithuanian)
timeout
number
default:"10000"
Request timeout in milliseconds
retryAttempts
number
default:"3"
Number of retry attempts for failed requests
enableWebSocket
boolean
default:"false"
Enable real-time WebSocket connections

Quick Start Example

Here’s a complete example showing how to create a loyalty card and award points:
import { LoyaltySDK } from '@loyalty-lt/javascript-sdk';

const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  environment: 'staging'
});

async function createLoyaltyProgram() {
  try {
    // Create a new loyalty card
    const card = await sdk.loyaltyCards.create({
      customer_email: 'customer@example.com',
      customer_name: 'John Doe',
      initial_points: 100
    });
    
    console.log('Created card:', card.id);
    
    // Award additional points
    const transaction = await sdk.points.award({
      card_id: card.id,
      points: 50,
      reason: 'Welcome bonus'
    });
    
    console.log('Awarded points:', transaction.points_awarded);
    
    // Get updated card details
    const updatedCard = await sdk.loyaltyCards.get(card.id);
    console.log('New balance:', updatedCard.points_balance);
    
  } catch (error) {
    console.error('Error:', error.message);
  }
}

createLoyaltyProgram();

API Reference

Loyalty Cards

Points Management

Offers & Coupons

Error Handling

The SDK provides comprehensive error handling with typed error responses:
try {
  const card = await sdk.loyaltyCards.get('invalid_id');
} catch (error) {
  if (error.code === 'CARD_NOT_FOUND') {
    console.log('Card not found');
  } else if (error.code === 'UNAUTHORIZED') {
    console.log('Check your API credentials');
  } else {
    console.log('Unexpected error:', error.message);
  }
}

Common Error Codes

Real-time Features

Enable WebSocket connections for real-time updates:
const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  environment: 'staging',
  enableWebSocket: true
});

// Listen for real-time events
sdk.on('points.awarded', (event) => {
  console.log('Points awarded:', event.data.points);
  updateUI(event.data.card_id, event.data.new_balance);
});

sdk.on('offer.claimed', (event) => {
  console.log('Offer claimed:', event.data.offer_title);
  showNotification('Offer redeemed successfully!');
});

// Connect to real-time events
await sdk.connect();

Available Events

points.awarded

Triggered when points are awarded to a card

points.redeemed

Triggered when points are redeemed from a card

offer.claimed

Triggered when an offer is claimed by a customer

card.created

Triggered when a new loyalty card is created

Environment Variables

For security, store API credentials in environment variables:
LOYALTY_API_KEY=your_api_key_here
LOYALTY_API_SECRET=your_api_secret_here
LOYALTY_ENVIRONMENT=staging

Framework Integrations

React Integration

For React applications, consider using our dedicated React hooks:
npm install @loyalty-lt/react-sdk
import { LoyaltyProvider, useLoyaltyCard } from '@loyalty-lt/react-sdk';

function App() {
  return (
    <LoyaltyProvider apiKey="your_api_key">
      <LoyaltyCard customerId="customer_123" />
    </LoyaltyProvider>
  );
}

function LoyaltyCard({ customerId }) {
  const { card, loading, error, awardPoints } = useLoyaltyCard(customerId);
  
  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  
  return (
    <div>
      <h3>Points Balance: {card.points_balance}</h3>
      <button onClick={() => awardPoints(10)}>
        Award 10 Points
      </button>
    </div>
  );
}

Vue.js Integration

Use Vue composables for reactive loyalty features:
npm install @loyalty-lt/vue-sdk
<template>
  <div>
    <h3>Points: {{ card.points_balance }}</h3>
    <button @click="awardPoints(10)" :disabled="loading">
      Award Points
    </button>
  </div>
</template>

<script setup>
import { useLoyaltyCard } from '@loyalty-lt/vue-sdk';

const { card, loading, awardPoints } = useLoyaltyCard('customer_123');
</script>

Testing

Use the staging environment for development and testing:
import { LoyaltySDK } from '@loyalty-lt/javascript-sdk';

describe('Loyalty SDK', () => {
  let sdk;
  
  beforeAll(() => {
    sdk = new LoyaltySDK({
      apiKey: 'test_api_key',
      apiSecret: 'test_api_secret',
      environment: 'staging'
    });
  });
  
  test('should create loyalty card', async () => {
    const card = await sdk.loyaltyCards.create({
      customer_email: 'test@example.com',
      customer_name: 'Test User'
    });
    
    expect(card.customer_email).toBe('test@example.com');
    expect(card.points_balance).toBe(0);
  });
  
  test('should award points', async () => {
    const card = await sdk.loyaltyCards.create({
      customer_email: 'test2@example.com',
      customer_name: 'Test User 2'
    });
    
    const transaction = await sdk.points.award({
      card_id: card.id,
      points: 100,
      reason: 'Test points'
    });
    
    expect(transaction.points_awarded).toBe(100);
  });
});

Performance Optimization

Request Caching

// Enable automatic caching
const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  cache: {
    enabled: true,
    ttl: 300000 // 5 minutes
  }
});

Request Batching

// Batch multiple operations
const results = await sdk.batch([
  sdk.loyaltyCards.get('card_1'),
  sdk.loyaltyCards.get('card_2'),
  sdk.points.getHistory('card_1')
]);

Connection Pooling

// Optimize for high-traffic applications
const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  pool: {
    maxConnections: 10,
    keepAlive: true
  }
});

Retry Logic

// Custom retry configuration
const sdk = new LoyaltySDK({
  apiKey: 'your_api_key',
  apiSecret: 'your_api_secret',
  retry: {
    attempts: 3,
    backoff: 'exponential',
    maxDelay: 5000
  }
});

Migration Guide

From v1.x to v2.x

Next Steps

Support

Need help with the JavaScript SDK? Check out these resources:

Changelog

v2.1.0
Released December 2024

New Features

  • WebSocket support for real-time events
  • Request batching for improved performance
  • TypeScript definitions for better developer experience
  • Automatic retry logic with exponential backoff

Breaking Changes

  • Required apiSecret parameter in constructor
  • Reorganized API methods into namespaces
  • Updated error response format

Bug Fixes

  • Fixed memory leak in WebSocket connections
  • Improved error handling for network timeouts
  • Better handling of rate limit responses