Skip to main content

Overview

This example demonstrates how to send personalized cards using the CardClan Integration API. We’ll walk through the complete flow from authentication to card delivery with real-world scenarios.

Basic Send Card Example

Here’s a simple example that sends a welcome card to a new user:
const axios = require('axios');

async function sendWelcomeCard(recipient) {
  const apiKey = process.env.CARDCLAN_API_KEY;
  const baseUrl = 'https://api.cardclan.com/api/integration';
  
  const headers = {
    'Authorization': `Bearer ${apiKey}`,
    'Content-Type': 'application/json'
  };

  try {
    // Send the card
    const response = await axios.post(`${baseUrl}/send-card`, {
      card: '60f7b2b5b8f4a20015a4f5a5',           // Your card ID
      emailAccount: 'CardClan',                    // Use default email
      integrationId: '60f7b2b5b8f4a20015a4f5a7', // Your integration config ID
      mergeTags: [
        {
          name: recipient.name,
          email: recipient.email,
          company: recipient.company,
          position: recipient.position
        }
      ]
    }, { headers });

    console.log('Card sent successfully!');
    console.log('Recipient ID:', response.data.recipient_id);
    console.log('Tracking URL:', response.data.tracking_url);
    
    return response.data;
    
  } catch (error) {
    console.error('Failed to send card:', error.response?.data?.message || error.message);
    throw error;
  }
}

// Usage
const newUser = {
  name: 'Sarah Johnson',
  email: '[email protected]',
  company: 'TechStartup Inc',
  position: 'Marketing Director'
};

sendWelcomeCard(newUser)
  .then(result => {
    console.log('Welcome card sent:', result.message);
  })
  .catch(error => {
    console.error('Error:', error.message);
  });
Expected Response:
{
  "message": "Card successfully sent to recipient: [email protected]",
  "status": true,
  "recipient_id": "60f7b2b5b8f4a20015a4f5a8",
  "tracking_url": "https://cardclan.com/api/analytics/fetchImage/60f7b2b5b8f4a20015a4f5a8"
}

Complete Integration Example

This example shows the full workflow including dynamic card and workspace selection:
const axios = require('axios');

class CardClanClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.cardclan.com/api/integration';
    this.headers = {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    };
  }

  async getWorkspaces() {
    const response = await axios.get(`${this.baseUrl}/workspaces`, { 
      headers: this.headers 
    });
    return response.data[0]?.choices || [];
  }

  async getCards(workspaceId) {
    const response = await axios.post(`${this.baseUrl}/cards?workspace=${workspaceId}`, 
      {}, 
      { headers: this.headers }
    );
    return response.data[0]?.choices || [];
  }

  async createIntegrationConfig(userId, workspaceId, cardId) {
    try {
      const response = await axios.post(`${this.baseUrl}/config`, {
        userId,
        workspaceId,
        cardId
      }, { headers: this.headers });
      
      return response.data.data._id;
    } catch (error) {
      if (error.response?.status === 400 && 
          error.response.data.message.includes('already created')) {
        // Config exists, get it
        const existingConfig = await this.getIntegrationConfigByCard(cardId);
        return existingConfig._id;
      }
      throw error;
    }
  }

  async getIntegrationConfigByCard(cardId) {
    const response = await axios.get(
      `${this.baseUrl}/config/by-card?cardId=${cardId}`,
      { headers: this.headers }
    );
    return response.data.data;
  }

  async sendCard(cardId, integrationId, mergeTags, emailAccount = 'CardClan') {
    const response = await axios.post(`${this.baseUrl}/send-card`, {
      card: cardId,
      emailAccount,
      integrationId,
      mergeTags: [mergeTags]
    }, { headers: this.headers });

    return response.data;
  }
}

// Usage example
async function sendPersonalizedCard() {
  const client = new CardClanClient(process.env.CARDCLAN_API_KEY);
  
  try {
    // 1. Get available workspaces
    console.log('Fetching workspaces...');
    const workspaces = await client.getWorkspaces();
    const workspace = workspaces[0]; // Use first workspace
    
    console.log(`Using workspace: ${workspace.name}`);
    
    // 2. Get available cards
    console.log('Fetching cards...');
    const cards = await client.getCards(workspace.id);
    const card = cards.find(c => c.title.includes('Welcome')) || cards[0];
    
    console.log(`Using card: ${card.title}`);
    
    // 3. Create or get integration configuration
    console.log('Setting up integration configuration...');
    const integrationId = await client.createIntegrationConfig(
      'your-user-id',
      workspace.id,
      card.id
    );
    
    // 4. Send the card
    console.log('Sending card...');
    const result = await client.sendCard(card.id, integrationId, {
      name: 'Alex Thompson',
      email: '[email protected]',
      company: 'Innovation Labs',
      position: 'Product Manager',
      joinDate: new Date().toLocaleDateString()
    });
    
    console.log('✅ Success!');
    console.log(`Card sent to: ${result.message}`);
    console.log(`Tracking URL: ${result.tracking_url}`);
    
    return result;
    
  } catch (error) {
    console.error('❌ Error sending card:', error.message);
    if (error.response) {
      console.error('API Response:', error.response.data);
    }
    throw error;
  }
}

// Run the example
sendPersonalizedCard()
  .then(() => console.log('Done!'))
  .catch(error => console.error('Failed:', error.message));