PHP code example of eaglebirth / eaglebirth-php

1. Go to this page and download the library: Download eaglebirth/eaglebirth-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

eaglebirth / eaglebirth-php example snippets




agleBirth\EagleBirth;

// Initialize the client
$client = new EagleBirth('eb_test_your_api_key_here');

// Send an email
$response = $client->email->send(
    email: '[email protected]',
    subject: 'Welcome!',
    message: 'Thank you for signing up.'
);

print_r($response);

// Test environment - automatically routes to sandbox.eaglebirth.com
$client = new EagleBirth('eb_test_...');

// Production environment - automatically routes to eaglebirth.com
$client = new EagleBirth('eb_live_...');

// Send a simple email
$client->email->send(
    email: '[email protected]',
    subject: 'Welcome to our service',
    message: 'Thank you for joining us!'
);

// Send with custom reply-to and header
$client->email->send(
    email: '[email protected]',
    subject: 'Account Verification',
    message: 'Please verify your email address.',
    replyTo: '[email protected]',
    header: 'MyApp Verification'
);

// Send an SMS
$client->sms->send(
    phoneNumber: '+1234567890',
    message: 'Your verification code is 123456'
);

// Get SMS pricing
$prices = $client->sms->getPrices('+1234567890');
print_r($prices);

// Send a WhatsApp message
$client->whatsapp->send(
    phoneNumber: '+1234567890',
    message: 'Hello from EagleBirth!',
    template: 'normal_message'
);

// Send OTP via email
$result = $client->otp->send(
    validationType: 'email',
    email: '[email protected]',
    codeLength: 6,
    timeout: 180,
    trials: 3
);
$codeId = $result['code_id'];

// Validate the OTP
$validation = $client->otp->validate(
    codeId: $codeId,
    code: '123456'
);

// Check if code was validated
$status = $client->otp->checkValidated($codeId);

// Generate a simple QR code
$qr = $client->qr->generate(
    text: 'https://example.com'
);

// Generate with custom colors and logo
$qr = $client->qr->generate(
    text: 'https://example.com',
    image: '/path/to/logo.png',
    imageType: 'object',
    color: '#000000',
    backgroundColor: '#FFFFFF',
    qrType: 'rounded'
);

// Generate with logo from URL
$qr = $client->qr->generate(
    text: 'https://example.com',
    image: 'https://example.com/logo.png',
    imageType: 'link'
);

// Extract face details from an image file
$details = $client->vision->extractFaceDetails(
    image: '/path/to/photo.jpg',
    imageType: 'object'
);

// Extract face details from image URL
$details = $client->vision->extractFaceDetails(
    image: 'https://example.com/photo.jpg',
    imageType: 'link'
);

// Compare two faces
$comparison = $client->vision->compareFaces(
    image1: '/path/to/photo1.jpg',
    image2: '/path/to/photo2.jpg',
    image1Type: 'object',
    image2Type: 'object'
);

// Extract text from image (OCR)
$text = $client->vision->extractText(
    image: '/path/to/document.jpg',
    imageType: 'object'
);

// Create a directory
$client->storage->directory->create(
    path: '/photos/vacation/',
    private: 'yes',  // 'yes' or 'no'
    directoryPassword: 'secret123'  // Optional password protection
);

// Upload a file
$client->storage->file->upload(
    file: '/path/to/document.pdf',
    path: '/documents/report.pdf',
    private: 'no',
    filePassword: 'filepass123'  // Optional file password
);

// List directory contents
$contents = $client->storage->directory->listContent(
    path: '/photos/vacation/',
    directoryPassword: 'secret123'  // If directory is password protected
);

foreach ($contents['data']['directories'] as $dir) {
    echo "Directory: {$dir['path']}\n";
}

foreach ($contents['data']['files'] as $file) {
    echo "File: {$file['filename']} - {$file['size']} bytes\n";
}

// Retrieve a file
$fileData = $client->storage->file->retrieve(
    path: '/documents/report.pdf',
    password: 'filepass123'  // If file is password protected
);

// Update file privacy
$client->storage->file->updatePrivacy(
    path: '/documents/report.pdf',
    private: 'yes',
    refreshToken: 'yes'  // Generate new access token
);

// Update directory password
$client->storage->directory->updatePassword(
    path: '/photos/vacation/',
    directoryPassword: 'newsecret456'
);

// Delete a file
$client->storage->file->delete(path: '/documents/old_report.pdf');

// Delete a directory
$client->storage->directory->delete(path: '/photos/old_vacation/');

// Note: The client is already authenticated with your API key.
// User Management operates on your app's users.


// Step 1: Redirect users to EagleBirth Auth UI with PKCE parameters
// (You generate code_verifier and code_challenge in your app)

// Step 2: After successful authentication, EagleBirth redirects back to your app
// with a 'code' parameter in the URL

// Step 3: Exchange the code for user session data
$userSession = $client->users->exchangeCodeForUser(
    code: 'code_from_url_redirect',
    codeVerifier: 'your_original_code_verifier'
);

// Access user information
$userData = $userSession['data'];
echo "Email: {$userData['email']}\n";
echo "Username: {$userData['username']}\n";
echo "Name: {$userData['first_name']} {$userData['last_name']}\n";
echo "Phone: {$userData['phone']}\n";
echo "User ID: {$userData['user_id']}\n";

// Access session tokens
$accessToken = $userData['access'];
$refreshToken = $userData['refresh'];

// Use the access token for authenticated requests
// Store the refresh token for renewing the session

// Register a new webhook
$result = $client->webhooks->create(
    url: 'https://yourapp.com/webhooks/eaglebirth',
    event: 'message.reply'
);
// ⚠ Save the secret — it is shown only once
$webhookId = $result['data']['id'];
$secret     = $result['data']['secret'];
echo "Webhook created: {$webhookId}\n";
echo "Save your secret: {$secret}\n";

// List all registered webhooks
$hooks = $client->webhooks->list();
foreach ($hooks['data'] as $hook) {
    $active = $hook['is_active'] ? 'yes' : 'no';
    echo "{$hook['id']} — {$hook['event']} → {$hook['url']} (active={$active})\n";
}

// Send a test delivery to confirm your endpoint is reachable
$testResult = $client->webhooks->test($webhookId);
echo "Your server responded with HTTP {$testResult['data']['http_status']}\n";

// Pause deliveries temporarily
$client->webhooks->update($webhookId, null, false);

// Change the endpoint URL
$client->webhooks->update($webhookId, 'https://yourapp.com/new-path');

// Resume deliveries
$client->webhooks->update($webhookId, null, true);

// Permanently delete a webhook
$client->webhooks->delete($webhookId);



use EagleBirth\Resources\Webhooks;

// Plain PHP — works with any framework
$body      = file_get_contents('php://input');  // raw bytes — do not decode JSON first
$secret    = getenv('EAGLEBIRTH_WEBHOOK_SECRET');
$signature = $_SERVER['HTTP_X_EAGLEBIRTH_SIGNATURE'] ?? '';

if (!Webhooks::verifySignature($body, $secret, $signature)) {
    http_response_code(400);
    exit('Invalid signature');
}

$payload = json_decode($body, true);
$event   = $payload['event'];
$data    = $payload['data'];
// e.g. 'message.reply.sms', 'message.reply.whatsapp', 'message.reply.email'

switch ($event) {
    case 'message.reply.sms':
        echo "SMS reply from {$data['from']}: {$data['body']}\n";
        break;
    case 'message.reply.whatsapp':
        echo "WhatsApp reply from {$data['from']}: {$data['body']}\n";
        break;
    case 'message.reply.email':
        echo "Email reply from {$data['from']}: {$data['subject']}\n";
        break;
}

http_response_code(200);

use EagleBirth\Exceptions\EagleBirthException;
use EagleBirth\Exceptions\AuthenticationException;
use EagleBirth\Exceptions\APIException;

try {
    $response = $client->email->send(
        email: '[email protected]',
        subject: 'Test',
        message: 'Hello!'
    );
} catch (AuthenticationException $e) {
    // Invalid API key or authentication failed
    echo "Authentication error: " . $e->getMessage();
} catch (APIException $e) {
    // API returned an error
    echo "API error: " . $e->getMessage();
    echo "Status code: " . $e->getCode();
} catch (EagleBirthException $e) {
    // General SDK error
    echo "Error: " . $e->getMessage();
}

// Custom base URL (for testing or self-hosted)
$client = new EagleBirth(
    apiKey: 'eb_test_...',
    baseUrl: 'https://custom-api.example.com/api'
);

// Custom timeout (default: 30 seconds)
$client = new EagleBirth(
    apiKey: 'eb_test_...',
    baseUrl: null,
    timeout: 60
);

// Upload a file
$client->storage->file->upload(
    file: '/path/to/document.pdf',
    path: '/docs/report.pdf',
    private: 'no'
);

// Create a directory
$client->storage->directory->create(
    path: '/photos/vacation/',
    private: 'yes'
);

// List directory contents
$contents = $client->storage->directory->listContent(path: '/photos/');

// Retrieve a file
$fileData = $client->storage->file->retrieve(path: '/docs/report.pdf');

// Sign in with app credentials
$authResponse = $client->auth->signIn(
    clientId: 'your_client_id',
    secretId: 'your_secret_id'
);

// Get user tokens
$tokens = $client->auth->getToken(
    username: '[email protected]',
    password: 'password123'
);

// Refresh access token
$newToken = $client->auth->refreshToken(refresh: 'your_refresh_token');
bash
composer