Skip to main content
Prerequisites: Make sure you’ve completed the Installation & Setup guide and have your WhatsApp Business API credentials ready.

Step 1: Initialize the Client

Create a new file and initialize the WhatsApp client with your credentials:
import { WhatsAppClient } from 'whatsapp-client-sdk';

// Initialize the client
const client = new WhatsAppClient({
  accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
  phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
});

// Your phone number (include country code, e.g., +1234567890)
const recipientNumber = '+1234567890';

async function main() {
  try {
    // Test connection first
    const isConnected = await client.testConnection();
    
    if (!isConnected) {
      throw new Error('Failed to connect to WhatsApp API');
    }
    
    console.log('✅ Connected to WhatsApp API');
    
    // Continue to Step 2...
  } catch (error) {
    console.error('❌ Error:', error.message);
  }
}

main();

Step 2: Send Your First Text Message

Add this code to send a simple text message:
// Add this inside the main() function after the connection test

// Send a simple text message
const textResponse = await client.sendText(
  recipientNumber,
  '🎉 Hello from WhatsApp Client SDK! This is my first message.'
);

console.log('📱 Text message sent:', textResponse.messages[0].id);

Step 3: Send a Message with Interactive Buttons

Let’s make it more interesting with interactive buttons:
// Send an interactive message with buttons
const buttonResponse = await client.sendButtons(
  recipientNumber,
  'Welcome to the WhatsApp Client SDK! What would you like to explore?',
  [
    { id: 'docs', title: '📚 Documentation' },
    { id: 'examples', title: '💡 Examples' },
    { id: 'support', title: '🛟 Support' }
  ],
  {
    header: { type: 'text', text: '🚀 Getting Started' },
    footer: 'Choose an option to continue'
  }
);

console.log('🔘 Button message sent:', buttonResponse.messages[0].id);

Step 4: Setup Webhook to Receive Messages

Configure webhook to receive incoming messages from Meta:
// Create webhook processor
const webhookProcessor = client.createWebhookProcessor({
  onTextMessage: async (message) => {
    console.log(`📩 Received: ${message.text} from ${message.from}`);

    // Auto-reply
    await client.sendText(message.from, `Echo: ${message.text}`);

    // Mark as read
    await client.markMessageAsRead(message.id);
  },

  onError: async (error) => {
    console.error('Webhook error:', error);
  }
});

Next.js Webhook Route

Create app/api/webhook/route.ts:
import { NextRequest, NextResponse } from 'next/server';

// GET - Webhook verification
export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const result = await webhookProcessor.processWebhook(
    {} as any,
    Object.fromEntries(searchParams)
  );
  return new NextResponse(String(result.response), { status: result.status });
}

// POST - Receive messages
export async function POST(request: NextRequest) {
  const body = await request.json();
  const result = await webhookProcessor.processWebhook(body, {});
  return new NextResponse('OK', { status: result.status });
}

Express.js Webhook Route

import express from 'express';
const app = express();

app.use(express.json());

// Webhook endpoint
app.all('/webhook', async (req, res) => {
  const result = await webhookProcessor.processWebhook(req.body, req.query);
  res.status(result.status).send(result.response);
});

app.listen(3000, () => console.log('Webhook running on port 3000'));
Configure in Meta Dashboard:
  1. Go to Meta Developer Console
  2. Select your app → WhatsApp → Configuration
  3. Add webhook URL: https://your-domain.com/webhook
  4. Use your WHATSAPP_WEBHOOK_TOKEN for verification
  5. Subscribe to messages events

Step 5: Send Media Content

Send an image with a caption:
// Send an image message
const imageResponse = await client.sendImage(
  recipientNumber,
  {
    link: 'https://via.placeholder.com/400x300/25D366/FFFFFF?text=WhatsApp+SDK',
    caption: '📸 This image was sent using the WhatsApp Client SDK!'
  }
);

console.log('🖼️ Image message sent:', imageResponse.messages[0].id);

Complete Example

Here’s the complete working example with webhook:
import { WhatsAppClient } from 'whatsapp-client-sdk';

const client = new WhatsAppClient({
  accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
  phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
  webhookVerifyToken: process.env.WHATSAPP_WEBHOOK_TOKEN!,
});

const recipientNumber = '+1234567890'; // Replace with your number

// Setup webhook processor
const webhookProcessor = client.createWebhookProcessor({
  onTextMessage: async (message) => {
    console.log(`📩 Received: ${message.text} from ${message.from}`);

    // Echo back the message
    await client.sendText(message.from, `You said: "${message.text}"`);
    await client.markMessageAsRead(message.id);
  },

  onButtonClick: async (message) => {
    console.log(`🔘 Button clicked: ${message.interactive.button_id}`);
    await client.sendText(message.from, `Button received: ${message.interactive.button_id}`);
  },

  onError: async (error) => {
    console.error('❌ Webhook error:', error);
  }
});

async function quickStartDemo() {
  try {
    // Test connection
    console.log('🔗 Testing WhatsApp API connection...');
    const isConnected = await client.testConnection();

    if (!isConnected) {
      throw new Error('Failed to connect to WhatsApp API');
    }

    console.log('✅ Connected to WhatsApp API successfully!');

    // 1. Send text message
    console.log('📱 Sending text message...');
    const textResponse = await client.sendText(
      recipientNumber,
      '🎉 Hello from WhatsApp Client SDK! This is my first message.'
    );
    console.log(`✅ Text message sent: ${textResponse.messages[0].id}`);

    // 2. Send interactive buttons
    console.log('🔘 Sending interactive buttons...');
    const buttonResponse = await client.sendButtons(
      recipientNumber,
      'Welcome to the WhatsApp Client SDK! What would you like to explore?',
      [
        { id: 'docs', title: '📚 Documentation' },
        { id: 'examples', title: '💡 Examples' },
        { id: 'support', title: '🛟 Support' }
      ],
      {
        header: { type: 'text', text: '🚀 Getting Started' },
        footer: 'Choose an option to continue'
      }
    );
    console.log(`✅ Button message sent: ${buttonResponse.messages[0].id}`);

    // 3. Send image
    console.log('🖼️ Sending image...');
    const imageResponse = await client.sendImage(
      recipientNumber,
      {
        link: 'https://via.placeholder.com/400x300/25D366/FFFFFF?text=WhatsApp+SDK',
        caption: '📸 This image was sent using the WhatsApp Client SDK!'
      }
    );
    console.log(`✅ Image sent: ${imageResponse.messages[0].id}`);

    console.log('\n🎉 Quick start demo completed successfully!');
    console.log('🔗 Check your WhatsApp to see the messages.');
    console.log('\n📡 Webhook is ready to receive messages!');

  } catch (error) {
    console.error('❌ Error in quick start demo:', error.message);

    // Handle specific error types
    if (error.name === 'MessageValidationError') {
      console.error('📋 Field with error:', error.field);
    } else if (error.name === 'WhatsAppApiError') {
      console.error('🔗 API Error details:', error.details);
    }
  }
}

quickStartDemo();

// Export webhook processor for your server
export { webhookProcessor };

Run Your Code

Execute your quick start script:
# Compile and run TypeScript
npx ts-node send-message.ts

# Or compile first, then run
npx tsc send-message.ts
node send-message.js

Expected Output

You should see output similar to this:
🔗 Testing WhatsApp API connection...
 Connected to WhatsApp API successfully!
📱 Sending text message...
 Text message sent: wamid.HBgLM...
🔘 Sending interactive buttons...
 Button message sent: wamid.HBgLM...
🖼️ Sending image...
 Image sent: wamid.HBgLM...

🎉 Quick start demo completed successfully!
🔗 Check your WhatsApp to see the messages.

📡 Webhook is ready to receive messages!
When you receive a message, you’ll see:
📩 Received: Hello from +1234567890
 Text message sent: wamid.HBgLM...

Troubleshooting

  • Verify your access token and phone number ID are correct
  • Check that your Meta Developer account is active
  • Ensure you have internet connectivity
  • Make sure the recipient number is added to your WhatsApp Business account
  • Verify the phone number format includes the country code
  • Check the WhatsApp Business API status page
  • Install and configure dotenv: npm install dotenv
  • Add require('dotenv').config() at the top of your file
  • Verify your .env file is in the project root
  • Make sure TypeScript is installed: npm install -D typescript @types/node
  • Install ts-node for direct execution: npm install -D ts-node
  • Check your tsconfig.json configuration
  • Verify webhook URL is publicly accessible (not localhost)
  • Use ngrok for local testing: ngrok http 3000
  • Check webhook token matches in Meta Dashboard and .env
  • Verify you subscribed to messages events in Meta Dashboard
  • Check webhook endpoint returns 200 OK on verification
  • Ensure WHATSAPP_WEBHOOK_TOKEN is set correctly in .env
  • The verify token must match exactly in both places
  • Meta sends GET request for verification with hub.verify_token parameter
  • Your endpoint must return the hub.challenge value

Next Steps

Explore Message Types

Learn about all 11 supported message types including lists, templates, and media

Set Up Webhooks

Receive and respond to incoming messages with webhooks

Advanced Configuration

Configure timeouts, retry logic, and other advanced options

Common Patterns

Error Handling Pattern

import { WhatsAppApiError, MessageValidationError, RateLimitError } from 'whatsapp-client-sdk';

try {
  await client.sendText(recipientNumber, message);
} catch (error) {
  if (error instanceof WhatsAppApiError) {
    console.error('API Error:', error.details);
  } else if (error instanceof MessageValidationError) {
    console.error('Validation Error:', error.field);
  } else if (error instanceof RateLimitError) {
    console.error('Rate limited. Retry after:', error.retryAfter);
  }
}

Configuration Pattern

const client = new WhatsAppClient({
  accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
  phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
  
  // Optional: Advanced configuration
  timeout: 60000, // 60 second timeout
  apiVersion: 'v23.0',
  baseUrl: 'https://graph.facebook.com',
  webhookVerifyToken: process.env.WHATSAPP_WEBHOOK_TOKEN,
});
Pro tip: Start with the basic configuration and add advanced options as needed. The SDK provides sensible defaults for most use cases.