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

# Quick Start Guide

> Send your first WhatsApp message in under 5 minutes with the WhatsApp Client SDK

<Info>
  **Prerequisites**: Make sure you've completed the [Installation & Setup](/installation) guide and have your WhatsApp Business API credentials ready.
</Info>

## Step 1: Initialize the Client

Create a new file and initialize the WhatsApp client with your credentials:

<CodeGroup>
  ```typescript send-message.ts theme={null}
  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();
  ```

  ```javascript send-message.js theme={null}
  const { WhatsAppClient } = require('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();
  ```
</CodeGroup>

## Step 2: Send Your First Text Message

Add this code to send a simple text message:

```typescript theme={null}
// 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:

```typescript theme={null}
// 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:

```typescript theme={null}
// 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`:

```typescript theme={null}
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

```typescript theme={null}
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'));
```

<Info>
  **Configure in Meta Dashboard**:

  1. Go to [Meta Developer Console](https://developers.facebook.com)
  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
</Info>

## Step 5: Send Media Content

Send an image with a caption:

```typescript theme={null}
// 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:

<CodeGroup>
  ```typescript complete-example.ts theme={null}
  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 };
  ```

  ```javascript complete-example.js theme={null}
  const { WhatsAppClient } = require('whatsapp-client-sdk');
  require('dotenv').config(); // Load environment variables

  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
  module.exports = { webhookProcessor };
  ```
</CodeGroup>

## Run Your Code

Execute your quick start script:

<Tabs>
  <Tab title="TypeScript">
    ```bash theme={null}
    # Compile and run TypeScript
    npx ts-node send-message.ts

    # Or compile first, then run
    npx tsc send-message.ts
    node send-message.js
    ```
  </Tab>

  <Tab title="JavaScript">
    ```bash theme={null}
    node send-message.js
    ```
  </Tab>
</Tabs>

## Expected Output

You should see output similar to this:

```bash theme={null}
🔗 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:

```bash theme={null}
📩 Received: Hello from +1234567890
✅ Text message sent: wamid.HBgLM...
```

## Troubleshooting

<AccordionGroup>
  <Accordion title="Connection failed">
    * Verify your access token and phone number ID are correct
    * Check that your Meta Developer account is active
    * Ensure you have internet connectivity
  </Accordion>

  <Accordion title="Message not received">
    * 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
  </Accordion>

  <Accordion title="Environment variables not loaded">
    * 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
  </Accordion>

  <Accordion title="TypeScript errors">
    * 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
  </Accordion>

  <Accordion title="Webhook not receiving messages">
    * 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
  </Accordion>

  <Accordion title="Webhook verification failed">
    * 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
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Explore Message Types" icon="message" href="/messages/overview">
    Learn about all 11 supported message types including lists, templates, and media
  </Card>

  <Card title="Set Up Webhooks" icon="webhook" href="/webhooks/overview">
    Receive and respond to incoming messages with webhooks
  </Card>

  <Card title="Advanced Configuration" icon="cog" href="/configuration">
    Configure timeouts, retry logic, and other advanced options
  </Card>
</CardGroup>

## Common Patterns

### Error Handling Pattern

```typescript theme={null}
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

```typescript theme={null}
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,
});
```

<Tip>
  **Pro tip**: Start with the basic configuration and add advanced options as needed. The SDK provides sensible defaults for most use cases.
</Tip>
