SDKs & Libraries

Official SDKs and libraries for popular programming languages to integrate AmanahAgent WhatsApp Business API into your applications.

Overview

Our SDKs provide a convenient way to access the AmanahAgent API from your applications. They handle authentication, request formatting, error handling, and provide type-safe interfaces.

🚀 Easy Integration

Simple, intuitive APIs that get you up and running quickly

🛡️ Type Safety

Full TypeScript support and type definitions included

📦 Auto Updates

Automatically stay up-to-date with the latest API features

Available SDKs

📦

JavaScript/Node.js

Official JavaScript SDK for Node.js and browsers

Stablev2.1.0
npm install amanahagent-sdk
View Documentation →
🐍

Python

Official Python SDK with async support

Stablev1.8.0
pip install amanahagent
View Documentation →
🐘

PHP

Official PHP SDK for web applications

Stablev1.5.0
composer require amanahagent/sdk
View Documentation →

Java

Official Java SDK for enterprise applications

Stablev1.3.0
implementation 'com.amanahagent:sdk:1.3.0'
View Documentation →
🐹

Go

Official Go SDK for high-performance applications

Stablev1.2.0
go get github.com/amanahagent/go-sdk
View Documentation →
🔷

C# (.NET)

Official .NET SDK for Windows applications

Betav0.9.0
dotnet add package AmanahAgent.SDK
View Documentation →

JavaScript/Node.js SDK

Installation

# NPM
npm install amanahagent-sdk

# Yarn
yarn add amanahagent-sdk

# PNPM
pnpm add amanahagent-sdk

Quick Start

const { AmanahAgent } = require('amanahagent-sdk');
// or
import { AmanahAgent } from 'amanahagent-sdk';

// Initialize the client
const client = new AmanahAgent({
  apiKey: 'your-api-key',
  baseURL: 'https://api.amanahagent.cloud/v1' // optional
});

// Send a message
async function sendMessage() {
  try {
    const message = await client.messages.send({
      to: '+1234567890',
      type: 'text',
      message: 'Hello from AmanahAgent!'
    });
    
    console.log('Message sent:', message.message_id);
  } catch (error) {
    console.error('Error:', error.message);
  }
}

Advanced Usage

Send Media Messages

// Upload and send image
const media = await client.media.upload('./image.jpg');
const message = await client.messages.send({
  to: '+1234567890',
  type: 'media',
  media_url: media.url
});

// Send document with filename
const message = await client.messages.send({
  to: '+1234567890',
  type: 'media',
  media_url: 'https://example.com/document.pdf',
  filename: 'Important Document.pdf'
});

Template Messages

// Send template message
const message = await client.messages.sendTemplate({
  to: '+1234567890',
  template: {
    name: 'welcome_message',
    language: 'en',
    components: [
      {
        type: 'header',
        parameters: [{ type: 'text', text: 'AmanahAgent' }]
      },
      {
        type: 'body',
        parameters: [{ type: 'text', text: 'John Doe' }]
      }
    ]
  }
});

Contact Management

// Create contact
const contact = await client.contacts.create({
  phone: '+1234567890',
  name: 'John Doe',
  tags: ['customer', 'premium'],
  custom_fields: {
    company: 'Acme Corp',
    department: 'Sales'
  }
});

// Get contacts with pagination
const contacts = await client.contacts.list({
  page: 1,
  limit: 50,
  search: 'john'
});

Webhook Configuration

// Configure webhook
const webhook = await client.webhooks.create({
  url: 'https://your-app.com/webhooks',
  events: ['message.sent', 'message.delivered', 'message.received'],
  secret: 'your-webhook-secret'
});

// Verify webhook signature (Express middleware)
const verifyWebhook = client.webhooks.verifyMiddleware('your-secret');
app.use('/webhooks', verifyWebhook);

TypeScript Support

import { 
  AmanahAgent, 
  Message, 
  Contact, 
  MessageType,
  WebhookEvent 
} from 'amanahagent-sdk';

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

// Type-safe message sending
const message: Message = await client.messages.send({
  to: '+1234567890',
  type: MessageType.TEXT,
  message: 'Hello!'
});

// Webhook event handling
function handleWebhook(event: WebhookEvent) {
  switch (event.event) {
    case 'message.sent':
      console.log('Message sent:', event.data.message_id);
      break;
    case 'message.received':
      console.log('New message from:', event.data.from);
      break;
  }
}

Configuration Options

OptionTypeDefaultDescription
apiKeystring-Your AmanahAgent API key
baseURLstringhttps://api.amanahagent.cloud/v1API base URL
timeoutnumber30000Request timeout in milliseconds
retriesnumber3Number of retry attempts

Python SDK

Installation

# Install with pip
pip install amanahagent

# Install with poetry
poetry add amanahagent

# Install with pipenv
pipenv install amanahagent

Quick Start

from amanahagent import AmanahAgent

# Initialize the client
client = AmanahAgent(api_key='your-api-key')

# Send a message
try:
    message = client.messages.send(
        to='+1234567890',
        type='text',
        message='Hello from AmanahAgent!'
    )
    print(f'Message sent: {message.message_id}')
except Exception as error:
    print(f'Error: {error}')

Async Support

import asyncio
from amanahagent import AsyncAmanahAgent

async def send_message():
    client = AsyncAmanahAgent(api_key='your-api-key')
    
    try:
        message = await client.messages.send(
            to='+1234567890',
            type='text',
            message='Hello from async AmanahAgent!'
        )
        print(f'Message sent: {message.message_id}')
    except Exception as error:
        print(f'Error: {error}')
    finally:
        await client.close()

# Run async function
asyncio.run(send_message())

Django Integration

# settings.py
AMANAHAGENT_API_KEY = 'your-api-key'

# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from amanahagent import AmanahAgent
from django.conf import settings
import json

client = AmanahAgent(api_key=settings.AMANAHAGENT_API_KEY)

@csrf_exempt
@require_http_methods(["POST"])
def send_message(request):
    data = json.loads(request.body)
    
    try:
        message = client.messages.send(
            to=data['to'],
            type=data['type'],
            message=data['message']
        )
        return JsonResponse({'message_id': message.message_id})
    except Exception as error:
        return JsonResponse({'error': str(error)}, status=400)

Flask Integration

from flask import Flask, request, jsonify
from amanahagent import AmanahAgent
import os

app = Flask(__name__)
client = AmanahAgent(api_key=os.environ['AMANAHAGENT_API_KEY'])

@app.route('/send-message', methods=['POST'])
def send_message():
    data = request.json
    
    try:
        message = client.messages.send(
            to=data['to'],
            type=data['type'],
            message=data['message']
        )
        return jsonify({'message_id': message.message_id})
    except Exception as error:
        return jsonify({'error': str(error)}), 400

# Webhook handler with signature verification
@app.route('/webhooks/amanahagent', methods=['POST'])
def webhook_handler():
    signature = request.headers.get('X-Webhook-Signature')
    
    if client.webhooks.verify_signature(request.data, signature, 'your-secret'):
        event = request.json
        print(f"Received event: {event['event']}")
        return jsonify({'status': 'success'})
    else:
        return jsonify({'error': 'Invalid signature'}), 401

PHP SDK

Installation

# Install via Composer
composer require amanahagent/sdk

# Or add to your composer.json
{
    "require": {
        "amanahagent/sdk": "^1.5"
    }
}

Quick Start

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

use AmanahAgent\SDK\AmanahAgent;

// Initialize the client
$client = new AmanahAgent([
    'api_key' => 'your-api-key'
]);

// Send a message
try {
    $message = $client->messages->send([
        'to' => '+1234567890',
        'type' => 'text',
        'message' => 'Hello from AmanahAgent!'
    ]);
    
    echo "Message sent: " . $message->message_id;
} catch (Exception $error) {
    echo "Error: " . $error->getMessage();
}
?>

Laravel Integration

// config/services.php
'amanahagent' => [
    'api_key' => env('AMANAHAGENT_API_KEY'),
],

// app/Services/WhatsAppService.php
<?php
namespace App\Services;

use AmanahAgent\SDK\AmanahAgent;

class WhatsAppService
{
    private $client;
    
    public function __construct()
    {
        $this->client = new AmanahAgent([
            'api_key' => config('services.amanahagent.api_key')
        ]);
    }
    
    public function sendMessage($to, $message)
    {
        return $this->client->messages->send([
            'to' => $to,
            'type' => 'text',
            'message' => $message
        ]);
    }
}

// app/Http/Controllers/WhatsAppController.php
<?php
namespace App\Http\Controllers;

use App\Services\WhatsAppService;
use Illuminate\Http\Request;

class WhatsAppController extends Controller
{
    public function sendMessage(Request $request, WhatsAppService $whatsapp)
    {
        $request->validate([
            'to' => 'required|string',
            'message' => 'required|string'
        ]);
        
        try {
            $message = $whatsapp->sendMessage(
                $request->to,
                $request->message
            );
            
            return response()->json(['message_id' => $message->message_id]);
        } catch (Exception $e) {
            return response()->json(['error' => $e->getMessage()], 400);
        }
    }
}

Webhook Handling

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

use AmanahAgent\SDK\AmanahAgent;

$client = new AmanahAgent(['api_key' => 'your-api-key']);

// Get the raw POST data
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';

// Verify signature
if ($client->webhooks->verifySignature($payload, $signature, 'your-secret')) {
    $event = json_decode($payload, true);
    
    // Handle different event types
    switch ($event['event']) {
        case 'message.delivered':
            // Handle message delivered
            error_log("Message delivered: " . $event['data']['message_id']);
            break;
            
        case 'message.received':
            // Handle incoming message
            $from = $event['data']['from'];
            $message = $event['data']['message'];
            error_log("Received message from {$from}: {$message}");
            break;
    }
    
    http_response_code(200);
    echo 'OK';
} else {
    http_response_code(401);
    echo 'Unauthorized';
}
?>

Java SDK

Installation

Gradle

// build.gradle
dependencies {
    implementation 'com.amanahagent:sdk:1.3.0'
}

Maven

<!-- pom.xml -->
<dependency>
    <groupId>com.amanahagent</groupId>
    <artifactId>sdk</artifactId>
    <version>1.3.0</version>
</dependency>

Quick Start

import com.amanahagent.sdk.AmanahAgent;
import com.amanahagent.sdk.models.Message;
import com.amanahagent.sdk.models.SendMessageRequest;

public class WhatsAppExample {
    public static void main(String[] args) {
        // Initialize the client
        AmanahAgent client = AmanahAgent.builder()
            .apiKey("your-api-key")
            .build();
        
        // Send a message
        try {
            SendMessageRequest request = SendMessageRequest.builder()
                .to("+1234567890")
                .type("text")
                .message("Hello from AmanahAgent!")
                .build();
            
            Message message = client.messages().send(request);
            System.out.println("Message sent: " + message.getMessageId());
        } catch (Exception error) {
            System.err.println("Error: " + error.getMessage());
        }
    }
}

Spring Boot Integration

// application.yml
amanahagent:
  api-key: your-api-key

// AmanahAgentConfig.java
@Configuration
public class AmanahAgentConfig {
    @Value("${amanahagent.api-key}")
    private String apiKey;
    
    @Bean
    public AmanahAgent amanahAgent() {
        return AmanahAgent.builder()
            .apiKey(apiKey)
            .build();
    }
}

// WhatsAppService.java
@Service
public class WhatsAppService {
    private final AmanahAgent client;
    
    public WhatsAppService(AmanahAgent client) {
        this.client = client;
    }
    
    public Message sendMessage(String to, String message) {
        SendMessageRequest request = SendMessageRequest.builder()
            .to(to)
            .type("text")
            .message(message)
            .build();
            
        return client.messages().send(request);
    }
}

// WhatsAppController.java
@RestController
@RequestMapping("/api/whatsapp")
public class WhatsAppController {
    private final WhatsAppService whatsAppService;
    
    public WhatsAppController(WhatsAppService whatsAppService) {
        this.whatsAppService = whatsAppService;
    }
    
    @PostMapping("/send")
    public ResponseEntity<MessageResponse> sendMessage(@RequestBody MessageRequest request) {
        try {
            Message message = whatsAppService.sendMessage(request.getTo(), request.getMessage());
            return ResponseEntity.ok(new MessageResponse(message.getMessageId()));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                .body(new MessageResponse(null, e.getMessage()));
        }
    }
}

Go SDK

Installation

# Install the SDK
go get github.com/amanahagent/go-sdk

# Initialize go module (if not already done)
go mod init your-project
go mod tidy

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/amanahagent/go-sdk"
)

func main() {
    // Initialize the client
    client := amanahagent.New("your-api-key")
    
    // Send a message
    ctx := context.Background()
    message, err := client.Messages.Send(ctx, &amanahagent.SendMessageRequest{
        To:      "+1234567890",
        Type:    "text",
        Message: "Hello from AmanahAgent!",
    })
    
    if err != nil {
        log.Fatal("Error sending message:", err)
    }
    
    fmt.Printf("Message sent: %s\n", message.MessageID)
}

Gin Framework Integration

package main

import (
    "net/http"
    "os"
    
    "github.com/gin-gonic/gin"
    "github.com/amanahagent/go-sdk"
)

type MessageRequest struct {
    To      string `json:"to" binding:"required"`
    Message string `json:"message" binding:"required"`
}

func main() {
    // Initialize AmanahAgent client
    client := amanahagent.New(os.Getenv("AMANAHAGENT_API_KEY"))
    
    r := gin.Default()
    
    r.POST("/send-message", func(c *gin.Context) {
        var req MessageRequest
        if err := c.ShouldBindJSON(&req); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        
        message, err := client.Messages.Send(c.Request.Context(), &amanahagent.SendMessageRequest{
            To:      req.To,
            Type:    "text",
            Message: req.Message,
        })
        
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        
        c.JSON(http.StatusOK, gin.H{"message_id": message.MessageID})
    })
    
    r.Run(":8080")
}

Webhook Handling

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
    "strings"
    
    "github.com/amanahagent/go-sdk"
)

func verifySignature(payload []byte, signature, secret string) bool {
    mac := hmac.New(sha256.New, []byte(secret))
    mac.Write(payload)
    calculatedSignature := "sha256=" + hex.EncodeToString(mac.Sum(nil))
    return hmac.Equal([]byte(signature), []byte(calculatedSignature))
}

func webhookHandler(w http.ResponseWriter, r *http.Request) {
    payload, err := ioutil.ReadAll(r.Body)
    if err != nil {
        http.Error(w, "Error reading request body", http.StatusBadRequest)
        return
    }
    
    signature := r.Header.Get("X-Webhook-Signature")
    secret := os.Getenv("WEBHOOK_SECRET")
    
    if !verifySignature(payload, signature, secret) {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }
    
    var event amanahagent.WebhookEvent
    if err := json.Unmarshal(payload, &event); err != nil {
        http.Error(w, "Error parsing JSON", http.StatusBadRequest)
        return
    }
    
    // Handle different event types
    switch event.Event {
    case "message.delivered":
        fmt.Printf("Message delivered: %s\n", event.Data.MessageID)
    case "message.received":
        fmt.Printf("Received message from %s: %s\n", event.Data.From, event.Data.Message)
    }
    
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("OK"))
}

func main() {
    http.HandleFunc("/webhooks/amanahagent", webhookHandler)
    log.Println("Webhook server listening on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

SDK Feature Comparison

FeatureJavaScriptPythonPHPJavaGoC#
Message Sending
Media Upload
Template Messages
Contact Management
Webhook Verification
TypeScript/Type Safety
Async Support

Full support

Partial/Beta support

Not yet available

Contributing

We welcome contributions to our SDKs! Each SDK is open source and hosted on GitHub.

🐛 Found a Bug?

Open an issue on the respective GitHub repository with detailed information about the bug.

View Repositories →

💡 Feature Request?

Submit a feature request or contribute new functionality via pull requests.

Contact Support →