> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cardclan.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Send Card Example

> Complete examples of sending personalized cards using the CardClan Integration API

## 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:

<CodeGroup>
  ```javascript Node.js theme={null}
  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: 'sarah@techstartup.com',
    company: 'TechStartup Inc',
    position: 'Marketing Director'
  };

  sendWelcomeCard(newUser)
    .then(result => {
      console.log('Welcome card sent:', result.message);
    })
    .catch(error => {
      console.error('Error:', error.message);
    });
  ```

  ```python Python theme={null}
  import requests
  import os

  def send_welcome_card(recipient):
      api_key = os.getenv('CARDCLAN_API_KEY')
      base_url = 'https://api.cardclan.com/api/integration'
      
      headers = {
          'Authorization': f'Bearer {api_key}',
          'Content-Type': 'application/json'
      }
      
      payload = {
          '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']
              }
          ]
      }
      
      try:
          response = requests.post(f'{base_url}/send-card', 
                                 json=payload, 
                                 headers=headers)
          response.raise_for_status()
          
          result = response.json()
          print('Card sent successfully!')
          print(f'Recipient ID: {result["recipient_id"]}')
          print(f'Tracking URL: {result["tracking_url"]}')
          
          return result
          
      except requests.exceptions.RequestException as error:
          print(f'Failed to send card: {error}')
          if hasattr(error, 'response') and error.response:
              print(f'Error details: {error.response.json()}')
          raise

  # Usage
  new_user = {
      'name': 'Sarah Johnson',
      'email': 'sarah@techstartup.com',
      'company': 'TechStartup Inc',
      'position': 'Marketing Director'
  }

  try:
      result = send_welcome_card(new_user)
      print(f'Welcome card sent: {result["message"]}')
  except Exception as error:
      print(f'Error: {error}')
  ```

  ```bash cURL theme={null}
  #!/bin/bash

  # Set your API key
  API_KEY="your-integration-key-here"
  BASE_URL="https://api.cardclan.com/api/integration"

  # Send card function
  send_welcome_card() {
    local name="$1"
    local email="$2"
    local company="$3"
    local position="$4"
    
    curl -X POST "${BASE_URL}/send-card" \
      -H "Authorization: Bearer ${API_KEY}" \
      -H "Content-Type: application/json" \
      -d "{
        \"card\": \"60f7b2b5b8f4a20015a4f5a5\",
        \"emailAccount\": \"CardClan\",
        \"integrationId\": \"60f7b2b5b8f4a20015a4f5a7\",
        \"mergeTags\": [
          {
            \"name\": \"${name}\",
            \"email\": \"${email}\",
            \"company\": \"${company}\",
            \"position\": \"${position}\"
          }
        ]
      }"
  }

  # Usage
  send_welcome_card "Sarah Johnson" "sarah@techstartup.com" "TechStartup Inc" "Marketing Director"
  ```
</CodeGroup>

**Expected Response:**

```json theme={null}
{
  "message": "Card successfully sent to recipient: sarah@techstartup.com",
  "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:

<CodeGroup>
  ```javascript Complete Integration theme={null}
  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: 'alex@example.com',
        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));
  ```
</CodeGroup>
