Guides & Tutorials

Step-by-step guides to help you master AmanahAgent API. From sending your first message to building complex automation workflows.

Send Your First Message

⚡ Quick Tutorial

Learn how to send your first WhatsApp message in under 5 minutes. Perfect for beginners getting started with the API.

Prerequisites: AmanahAgent account, API key, and basic programming knowledge

1

Set Up Your Environment

First, make sure you have your API key ready and install the required SDK for your programming language.

# Install the SDK (choose your language)
npm install @amanahagent/sdk
# or
pip install amanahagent
# or
composer require amanahagent/sdk

Don't have an API key yet? Visit your dashboard Settings → API Keys to generate one.

2

Write Your First Script

Create a simple script to send a text message. Here are examples in different languages:

JavaScript/Node.js

const AmanahAgent = require('@amanahagent/sdk');

const client = new AmanahAgent({
  apiKey: 'your-api-key-here'
});

async function sendMessage() {
  try {
    const response = await client.messages.send({
      to: '+1234567890',  // Replace with recipient's number
      type: 'text',
      message: 'Hello! This is my first message via AmanahAgent API 🚀'
    });
    
    console.log('Message sent successfully!');
    console.log('Message ID:', response.message_id);
    console.log('Status:', response.status);
  } catch (error) {
    console.error('Error sending message:', error.message);
  }
}

sendMessage();

Python

from amanahagent import AmanahAgent

client = AmanahAgent(api_key="your-api-key-here")

try:
    response = client.messages.send(
        to="+1234567890",  # Replace with recipient's number
        type="text",
        message="Hello! This is my first message via AmanahAgent API 🚀"
    )
    
    print("Message sent successfully!")
    print(f"Message ID: {response.message_id}")
    print(f"Status: {response.status}")
    
except Exception as error:
    print(f"Error sending message: {error}")

PHP

<?php
require_once 'vendor/autoload.php';

use AmanahAgent\AmanahAgent;

$client = new AmanahAgent('your-api-key-here');

try {
    $response = $client->messages->send([
        'to' => '+1234567890',  // Replace with recipient's number
        'type' => 'text',
        'message' => 'Hello! This is my first message via AmanahAgent API 🚀'
    ]);
    
    echo "Message sent successfully!\n";
    echo "Message ID: " . $response['message_id'] . "\n";
    echo "Status: " . $response['status'] . "\n";
    
} catch (Exception $error) {
    echo "Error sending message: " . $error->getMessage() . "\n";
}
?>
3

Test Your Message

Run your script and check the console output. You should see a success message with a message ID.

Expected Output:

Message sent successfully!
Message ID: msg_abc123xyz789
Status: sent

Verify Delivery

Check your recipient's phone to confirm the message was delivered. You can also use the message ID to check delivery status via the API.

Learn about Message Status →

Handle Media Files

📱 Media Guide

Learn how to send images, videos, documents, and audio files through WhatsApp. Includes file size limits and best practices.

Supported formats: Images (JPG, PNG, GIF), Videos (MP4, 3GP), Documents (PDF, DOC, XLS, PPT), Audio (MP3, OGG, AMR)

Upload Media Files

Before sending media messages, you need to upload the files to our secure storage. Here's how:

// JavaScript - Upload an image
const formData = new FormData();
formData.append('file', fileInput.files[0]);
formData.append('filename', 'product-showcase.jpg');

const uploadResponse = await fetch('https://api.amanahagent.cloud/v1/media', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  },
  body: formData
});

const mediaData = await uploadResponse.json();
console.log('Media uploaded:', mediaData.media_id);

File Size Limits: Maximum 16MB per file. For videos, keep under 5 minutes for best delivery rates.

Send Media Messages

Once uploaded, use the media_id to send the file in a message:

Send Image with Caption

const response = await client.messages.send({
  to: '+1234567890',
  type: 'image',
  media_id: 'media_xyz789abc123',
  caption: 'Check out our new product! 🎉'
});

Send Document

const response = await client.messages.send({
  to: '+1234567890',
  type: 'document',
  media_id: 'media_doc456xyz789',
  filename: 'product-catalog.pdf',
  caption: 'Here's our complete product catalog'
});

Send Video

const response = await client.messages.send({
  to: '+1234567890',
  type: 'video',
  media_id: 'media_video123abc',
  caption: 'Product demonstration video'
});

Best Practices for Media

✅ Do

  • Optimize image sizes (under 1MB recommended)
  • Use descriptive filenames
  • Add relevant captions
  • Test with different file formats
  • Keep videos under 2 minutes

❌ Don't

  • Upload files over 16MB
  • Use copyrighted content
  • Send media without context
  • Upload corrupted files
  • Ignore file format restrictions

Build a Chatbot Integration

🤖 Chatbot Guide

Create intelligent WhatsApp chatbots that can handle customer inquiries, process orders, and provide automated support 24/7.

Level: Intermediate - Requires webhook setup and basic AI/NLP knowledge

Architecture Overview

A typical chatbot integration consists of these components:

1

Webhook Endpoint

Receives incoming messages

2

Message Processor

Understands user intent

3

Response Generator

Sends appropriate replies

Step 1: Set Up Webhook

Create a webhook endpoint to receive incoming messages:

// Express.js webhook endpoint
const express = require('express');
const app = express();
app.use(express.json());

app.post('/webhook/amanahagent', (req, res) => {
  const { event, data } = req.body;
  
  if (event === 'message.received') {
    console.log('New message:', data);
    processIncomingMessage(data);
  }
  
  res.status(200).send('OK');
});

async function processIncomingMessage(messageData) {
  const { from, message, type } = messageData;
  
  // Process the message and generate response
  const response = await generateResponse(message, from);
  
  // Send reply
  await sendReply(from, response);
}

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});

Step 2: Implement Message Processing

Add logic to understand user intents and generate appropriate responses:

async function generateResponse(message, userPhone) {
  const intent = detectIntent(message.toLowerCase());
  
  switch (intent) {
    case 'greeting':
      return {
        type: 'text',
        message: 'Hello! How can I help you today? 😊\n\n' +
                '• Type "menu" to see our services\n' +
                '• Type "support" for customer support\n' +
                '• Type "hours" for business hours'
      };
      
    case 'menu':
      return {
        type: 'text',
        message: '📋 Our Services:\n\n' +
                '1️⃣ Product Information\n' +
                '2️⃣ Order Status\n' +
                '3️⃣ Technical Support\n' +
                '4️⃣ Billing Questions\n\n' +
                'Reply with a number to continue!'
      };
      
    case 'support':
      return {
        type: 'text',
        message: '🎧 Connecting you with support...\n\n' +
                'Please describe your issue and our team will respond shortly.'
      };
      
    case 'hours':
      return {
        type: 'text',
        message: '🕒 Business Hours:\n\n' +
                'Monday - Friday: 9AM - 6PM\n' +
                'Saturday: 10AM - 4PM\n' +
                'Sunday: Closed\n\n' +
                'We typically respond within 2 hours during business hours.'
      };
      
    default:
      return {
        type: 'text',
        message: 'I didn\'t quite understand that. Type "menu" to see available options or "support" to speak with a human.'
      };
  }
}

function detectIntent(message) {
  const greetings = ['hello', 'hi', 'hey', 'good morning', 'good afternoon'];
  const menuKeywords = ['menu', 'options', 'services', 'help'];
  const supportKeywords = ['support', 'help', 'problem', 'issue'];
  const hoursKeywords = ['hours', 'time', 'open', 'closed'];
  
  if (greetings.some(word => message.includes(word))) return 'greeting';
  if (menuKeywords.some(word => message.includes(word))) return 'menu';
  if (supportKeywords.some(word => message.includes(word))) return 'support';
  if (hoursKeywords.some(word => message.includes(word))) return 'hours';
  
  return 'unknown';
}

Step 3: Send Automated Replies

Implement the function to send responses back to users:

const AmanahAgent = require('@amanahagent/sdk');
const client = new AmanahAgent({ apiKey: process.env.AMANAHAGENT_API_KEY });

async function sendReply(to, responseData) {
  try {
    const response = await client.messages.send({
      to: to,
      type: responseData.type,
      message: responseData.message
    });
    
    console.log(`Reply sent to ${to}: ${response.message_id}`);
  } catch (error) {
    console.error('Error sending reply:', error);
  }
}

Advanced Features

🧠 AI Integration

Integrate with OpenAI, Dialogflow, or other AI services for natural language understanding.

  • Intent recognition
  • Entity extraction
  • Context management
  • Multi-language support

💾 Session Management

Store conversation context and user preferences for personalized experiences.

  • User state tracking
  • Conversation history
  • Preferences storage
  • Multi-step flows

Bulk Messaging Best Practices

📢 Bulk Messaging Guide

Learn how to send messages to multiple recipients efficiently while maintaining high delivery rates and compliance with WhatsApp policies.

Important: Bulk messaging requires approved message templates for promotional content. Always follow WhatsApp's business policies.

Rate Limiting Strategy

Implement proper rate limiting to avoid hitting API limits and ensure smooth delivery:

const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function sendBulkMessages(recipients, messageData) {
  const results = [];
  const batchSize = 10; // Send 10 messages per batch
  const batchDelay = 1000; // 1 second delay between batches
  
  for (let i = 0; i < recipients.length; i += batchSize) {
    const batch = recipients.slice(i, i + batchSize);
    
    console.log(`Processing batch ${Math.floor(i/batchSize) + 1}...`);
    
    const batchPromises = batch.map(async (recipient) => {
      try {
        const response = await client.messages.send({
          to: recipient.phone,
          type: 'template',
          template_id: messageData.template_id,
          parameters: {
            name: recipient.name,
            // other template parameters
          }
        });
        
        return { 
          phone: recipient.phone, 
          success: true, 
          message_id: response.message_id 
        };
      } catch (error) {
        return { 
          phone: recipient.phone, 
          success: false, 
          error: error.message 
        };
      }
    });
    
    const batchResults = await Promise.all(batchPromises);
    results.push(...batchResults);
    
    // Wait before processing next batch
    if (i + batchSize < recipients.length) {
      await delay(batchDelay);
    }
  }
  
  return results;
}

Message Templates

Use approved templates for bulk promotional messages:

Template Requirements:

  • Must be pre-approved by WhatsApp
  • Cannot be modified once approved
  • Include opt-out instructions
  • Follow content guidelines
// Example: Sending a promotional template
const templateMessage = {
  template_id: 'summer_sale_2024',
  parameters: {
    customer_name: 'John',
    discount_amount: '25%',
    expiry_date: 'July 31st'
  }
};

await client.messages.send({
  to: '+1234567890',
  type: 'template',
  template_id: templateMessage.template_id,
  parameters: templateMessage.parameters
});

Delivery Monitoring

Track delivery status and handle failures appropriately:

async function monitorDeliveryStatus(messageIds) {
  const statusChecks = messageIds.map(async (messageId) => {
    const status = await client.messages.getStatus(messageId);
    return {
      message_id: messageId,
      status: status.delivery_status,
      delivered_at: status.delivered_at,
      failed_reason: status.failed_reason
    };
  });
  
  const results = await Promise.all(statusChecks);
  
  // Generate delivery report
  const delivered = results.filter(r => r.status === 'delivered').length;
  const failed = results.filter(r => r.status === 'failed').length;
  const pending = results.filter(r => r.status === 'pending').length;
  
  console.log(`Delivery Report:`);
  console.log(`✅ Delivered: ${delivered}`);
  console.log(`❌ Failed: ${failed}`);
  console.log(`⏳ Pending: ${pending}`);
  
  return results;
}

Best Practices Summary

✅ Do

  • Use approved templates for promotional content
  • Implement proper rate limiting
  • Monitor delivery status
  • Segment your audience
  • Include clear opt-out instructions
  • Personalize messages when possible

❌ Don't

  • Send promotional messages without templates
  • Exceed rate limits
  • Ignore delivery failures
  • Send to unverified numbers
  • Spam users with frequent messages
  • Use misleading or deceptive content

Customer Journey Automation

🚀 Automation Guide

Create automated workflows that guide customers through their journey, from welcome messages to post-purchase follow-ups.

Level: Advanced - Requires database integration and workflow management

Welcome Series Automation

Set up a welcome series for new customers:

class CustomerJourney {
  constructor() {
    this.workflows = new Map();
  }
  
  // Start welcome series when customer signs up
  async startWelcomeSeries(customerPhone, customerData) {
    const workflow = {
      customer_phone: customerPhone,
      current_step: 0,
      data: customerData,
      started_at: new Date()
    };
    
    this.workflows.set(customerPhone, workflow);
    
    // Send immediate welcome message
    await this.sendWelcomeMessage(customerPhone, customerData.name);
    
    // Schedule follow-up messages
    this.scheduleFollowUp(customerPhone, 'day_1', 24 * 60 * 60 * 1000); // 1 day
    this.scheduleFollowUp(customerPhone, 'day_3', 3 * 24 * 60 * 60 * 1000); // 3 days
    this.scheduleFollowUp(customerPhone, 'week_1', 7 * 24 * 60 * 60 * 1000); // 1 week
  }
  
  async sendWelcomeMessage(phone, customerName) {
    await client.messages.send({
      to: phone,
      type: 'template',
      template_id: 'welcome_series_1',
      parameters: {
        customer_name: customerName,
        company_name: 'AmanahAgent'
      }
    });
  }
  
  scheduleFollowUp(phone, step, delayMs) {
    setTimeout(async () => {
      await this.processWorkflowStep(phone, step);
    }, delayMs);
  }
  
  async processWorkflowStep(phone, step) {
    const workflow = this.workflows.get(phone);
    if (!workflow) return;
    
    switch (step) {
      case 'day_1':
        await this.sendDay1Message(phone, workflow.data);
        break;
      case 'day_3':
        await this.sendDay3Message(phone, workflow.data);
        break;
      case 'week_1':
        await this.sendWeek1Message(phone, workflow.data);
        break;
    }
  }
}

Purchase Follow-up Workflow

Automate post-purchase communication:

async function startPurchaseFollowUp(orderData) {
  const { customer_phone, customer_name, order_id, items } = orderData;
  
  // Immediate order confirmation
  await client.messages.send({
    to: customer_phone,
    type: 'template',
    template_id: 'order_confirmation',
    parameters: {
      customer_name: customer_name,
      order_id: order_id,
      order_total: orderData.total
    }
  });
  
  // Schedule delivery notification (example: 2 days)
  setTimeout(async () => {
    await client.messages.send({
      to: customer_phone,
      type: 'template',
      template_id: 'delivery_notification',
      parameters: {
        customer_name: customer_name,
        tracking_number: orderData.tracking_number
      }
    });
  }, 2 * 24 * 60 * 60 * 1000);
  
  // Schedule feedback request (example: 1 week)
  setTimeout(async () => {
    await client.messages.send({
      to: customer_phone,
      type: 'template',
      template_id: 'feedback_request',
      parameters: {
        customer_name: customer_name,
        product_name: items[0].name
      }
    });
  }, 7 * 24 * 60 * 60 * 1000);
}

Abandoned Cart Recovery

Win back customers who abandoned their shopping cart:

async function startAbandonedCartSeries(cartData) {
  const { customer_phone, customer_name, cart_items, cart_total } = cartData;
  
  // First reminder - 1 hour after abandonment
  setTimeout(async () => {
    await client.messages.send({
      to: customer_phone,
      type: 'template',
      template_id: 'cart_reminder_1',
      parameters: {
        customer_name: customer_name,
        cart_total: cart_total
      }
    });
  }, 60 * 60 * 1000); // 1 hour
  
  // Second reminder with discount - 24 hours
  setTimeout(async () => {
    await client.messages.send({
      to: customer_phone,
      type: 'template',
      template_id: 'cart_reminder_discount',
      parameters: {
        customer_name: customer_name,
        discount_code: 'SAVE10',
        discount_amount: '10%'
      }
    });
  }, 24 * 60 * 60 * 1000); // 24 hours
  
  // Final reminder - 72 hours
  setTimeout(async () => {
    await client.messages.send({
      to: customer_phone,
      type: 'template',
      template_id: 'cart_final_reminder',
      parameters: {
        customer_name: customer_name
      }
    });
  }, 72 * 60 * 60 * 1000); // 72 hours
}

Workflow Management Tips

📊 Analytics Tracking

  • Track message open rates
  • Monitor conversion rates by step
  • A/B test different message templates
  • Measure customer lifetime value

⚙️ Optimization

  • Adjust timing based on user behavior
  • Personalize content using customer data
  • Allow customers to opt-out easily
  • Use triggers based on user actions