PHP code example of cloudcontactai / ccai-php

1. Go to this page and download the library: Download cloudcontactai/ccai-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/ */

    

cloudcontactai / ccai-php example snippets


$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);



loudContactAI\CCAI\CCAI;
use CloudContactAI\CCAI\SMS\Account;

// Initialize the client
$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Send a single SMS
$response = $ccai->sms->sendSingle(
    firstName: 'John',
    lastName: 'Doe',
    phone: '+15551234567',
    message: 'Hello ${firstName}, this is a test message!',
    title: 'Test Campaign'
);

echo "Message sent with ID: " . $response->id . "\n";

// Send to multiple recipients
$accounts = [
    new Account('John', 'Doe', '+15551234567'),
    new Account('Jane', 'Smith', '+15559876543')
];

$campaignResponse = $ccai->sms->send(
    accounts: $accounts,
    message: 'Hello ${firstName} ${lastName}, this is a test message!',
    title: 'Bulk Test Campaign'
);

echo "Campaign sent with ID: " . $campaignResponse->campaignId . "\n";

// Send to multiple recipients using a template
$response = $ccai->sms->sendWithTemplate(
    accounts: $accounts,
    templateId: 12345,   // the ID of the approved template
    title: 'My Campaign'
);

// Send to a single recipient using a template
$response = $ccai->sms->sendSingleWithTemplate(
    firstName: 'John',
    lastName: 'Doe',
    phone: '+15551234567',
    templateId: 12345,
    title: 'My Campaign'
);

echo "Campaign sent with ID: " . $response->campaignId . "\n";



/**
 * Simple example of sending an MMS message using the CCAI PHP library
 */

AI([
    'clientId' => getenv('CCAI_CLIENT_ID') ?: 'YOUR_CLIENT_ID',
    'apiKey' => getenv('CCAI_API_KEY') ?: 'YOUR_API_KEY'
]);

// Path to the image file you want to send
$filename = 'imagePHP.jpg';
$imagePath = __DIR__ . '/imagePHP.jpg';
$contentType = 'image/jpeg';

try {
    // Send an MMS to a single recipient
    $response = $ccai->mms->sendWithImage(
        $imagePath,
        $contentType,
        [
            [
                'firstName' => 'Jane',
                'lastName' => 'Doe',
                'phone' => '+15555555555'
            ]
        ],
        'Hi ${firstName} ${lastName}, testing a new campaign',
        'MMS Content Test Message'
    );
    
    echo "MMS sent successfully! ID: " . $response->id . "\n";
    
} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}



loudContactAI\CCAI\CCAI;
use CloudContactAI\CCAI\Email\EmailAccount;

// Initialize the client
$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Send a single email
$response = $ccai->email->sendSingle(
    firstName: 'John',
    lastName: 'Doe',
    email: '[email protected]',
    subject: 'Welcome to Our Service',
    htmlContent: '<p>Hello John,</p><p>Thank you for signing up!</p>',
    senderEmail: '[email protected]',
    replyEmail: '[email protected]',
    senderName: 'Your Company',
    title: 'Welcome Email'
);

echo "Email sent successfully!\n";

// Send email campaign to multiple recipients
$accounts = [
    new EmailAccount('John', 'Doe', '[email protected]'),
    new EmailAccount('Jane', 'Smith', '[email protected]')
];

$campaign = [
    'accounts'    => array_map(fn(EmailAccount $a) => $a->toArray(), $accounts),
    'subject'     => 'Monthly Newsletter',
    'title'       => 'July 2025 Newsletter',
    'message'     => '<h1>Hello ${firstName}!</h1><p>Monthly updates...</p>',
    'senderEmail' => '[email protected]',
    'replyEmail'  => '[email protected]',
    'senderName'  => 'Your Company Newsletter',
];

$response = $ccai->email->sendCampaign($campaign);
echo "Campaign sent successfully!\n";



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Opt a contact out of text messages (by phone number)
$result = $ccai->contact->setDoNotText(true, null, '+15551234567');
echo "Opted out: " . json_encode($result) . "\n";

// Opt a contact back in
$ccai->contact->setDoNotText(false, null, '+15551234567');

// Opt out by contactId
$ccai->contact->setDoNotText(true, 'contact-abc-123', null);



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Validate a single email
$emailResult = $ccai->contactValidator->validateEmail('[email protected]');
echo "Status: " . $emailResult['status'] . "\n"; // "valid" | "invalid" | "risky"

// Validate multiple emails (up to 50, processed server-side in chunks)
$bulkEmails = $ccai->contactValidator->validateEmails([
    '[email protected]',
    '[email protected]'
]);
echo "Total: " . $bulkEmails['summary']['total'] . "\n"; // 2
echo "Valid: " . $bulkEmails['summary']['valid'] . "\n"; // 1

// Validate a single phone number
$phoneResult = $ccai->contactValidator->validatePhone('+15551234567', 'US');
echo "Status: " . $phoneResult['status'] . "\n"; // "valid" | "invalid" | "landline"

// Validate multiple phone numbers (up to 50, processed server-side in chunks)
$bulkPhones = $ccai->contactValidator->validatePhones([
    ['phone' => '+15551234567'],
    ['phone' => '+15559876543', 'countryCode' => 'US']
]);
echo "Landline: " . $bulkPhones['summary']['landline'] . "\n"; // 1



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Create a brand
$brand = $ccai->brands->create([
    'legalCompanyName' => 'Collect.org Inc.',
    'dba'              => 'Collect',
    'entityType'       => 'NON_PROFIT',
    'taxId'            => '123456789',
    'taxIdCountry'     => 'US',
    'country'          => 'US',
    'verticalType'     => 'NON_PROFIT',
    'websiteUrl'       => 'https://www.collect.org',
    'street'           => '123 Main Street',
    'city'             => 'San Francisco',
    'state'            => 'CA',
    'postalCode'       => '94105',
    'contactFirstName' => 'Jane',
    'contactLastName'  => 'Doe',
    'contactEmail'     => '[email protected]',
    'contactPhone'     => '+14155551234',
]);
echo "Brand created with ID: " . $brand['id'] . "\n";

// Get a brand by ID
$fetched = $ccai->brands->get($brand['id']);
echo "Website match score: " . ($fetched['websiteMatchScore'] ?? 'pending') . "\n";

// List all brands
$brands = $ccai->brands->list();
echo "Found " . count($brands) . " brand(s)\n";

// Update a brand (partial update)
$ccai->brands->update($brand['id'], [
    'street' => '456 Oak Avenue',
    'city'   => 'Los Angeles',
]);

// Delete a brand
$ccai->brands->delete($brand['id']);



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Create a campaign
$campaign = $ccai->campaigns->create([
    'brandId'          => 1,
    'useCase'          => 'MIXED',
    'subUseCases'      => ['CUSTOMER_CARE', 'TWO_FACTOR_AUTHENTICATION', 'ACCOUNT_NOTIFICATION'],
    'description'      => 'Security codes and support messaging.',
    'messageFlow'      => 'Users opt-in via signup form at https://example.com/signup',
    'hasEmbeddedLinks' => true,
    'hasEmbeddedPhone' => false,
    'isAgeGated'       => false,
    'isDirectLending'  => false,
    'optInKeywords'    => ['START'],
    'optInMessage'     => 'Welcome! Reply STOP to cancel.',
    'optInProofUrl'    => 'https://example.com/opt-in-proof.png',
    'helpKeywords'     => ['HELP'],
    'helpMessage'      => 'For HELP email [email protected].',
    'optOutKeywords'   => ['STOP'],
    'optOutMessage'    => 'STOP received. You are unsubscribed.',
    'sampleMessages'   => [
        'Your code is 554321. Reply STOP to cancel.',
        'Your ticket has been updated. Reply HELP for info.',
    ],
]);
echo "Campaign created with ID: " . $campaign['id'] . "\n";

// Get a campaign by ID
$fetched = $ccai->campaigns->get($campaign['id']);

// List all campaigns
$campaigns = $ccai->campaigns->list();
echo "Found " . count($campaigns) . " campaign(s)\n";

// Update a campaign (partial update)
$ccai->campaigns->update($campaign['id'], [
    'description' => 'Updated description.',
]);

// Delete a campaign
$ccai->campaigns->delete($campaign['id']);



loudContactAI\CCAI\CCAI;
// Initialize the client
$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Example 1: Register a webhook with auto-generated secret
// If secretKey is not provided, the server will auto-generate one
$webhook = $ccai->webhook->register([
    'url' => 'https://your-domain.com/api/ccai-webhook',
]);

echo "Webhook registered with ID: {$webhook['id']}\n";
echo "Auto-generated Secret: {$webhook['secretKey']}\n";

// Example 2: Register a webhook with a custom secret
$webhookWithCustomSecret = $ccai->webhook->register([
    'url' => 'https://your-domain.com/api/ccai-webhook-v2',
    'secretKey' => 'your-custom-secret-key',
]);

echo "Webhook with custom secret registered: {$webhookWithCustomSecret['id']}\n";

// List all webhooks
$webhooks = $ccai->webhook->list();
echo "Found " . count($webhooks) . " webhooks\n";

// Update a webhook
$updated = $ccai->webhook->update((string) $webhook['id'], [
    'url' => 'https://your-domain.com/api/new-webhook-endpoint'
]);

echo "Webhook updated: {$updated['url']}\n";

// Delete a webhook
$ccai->webhook->delete((string) $webhook['id']);
echo "Webhook deleted\n";

// Verify webhook signature in your HTTP handler
$signature = $_SERVER['HTTP_X_CCAI_SIGNATURE'] ?? '';
$body = file_get_contents('php://input');
$secret = 'your-webhook-secret-key'; // Use the secret returned during registration

// Parse the webhook payload to get client_id and event_hash
$payload = json_decode($body, true);
$clientId = getenv('CCAI_CLIENT_ID');
$eventHash = $payload['eventHash'] ?? '';

if ($ccai->webhook->verifySignature($signature, $clientId, $eventHash, $secret)) {
    // Signature is valid, process the webhook
    $event = $ccai->webhook->parseWebhookEvent($body);
    echo "Webhook event type: {$event['eventType']}\n";
    echo "Webhook data: " . json_encode($event['data']) . "\n";
} else {
    http_response_code(401);
    echo "Invalid signature\n";
    exit;
}



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Create a brand
$brand = $ccai->brands->create([
    'legalCompanyName' => 'Collect.org Inc.',
    'dba' => 'Collect',
    'entityType' => 'NON_PROFIT',
    'taxId' => '123456789',
    'taxIdCountry' => 'US',
    'country' => 'US',
    'verticalType' => 'NON_PROFIT',
    'websiteUrl' => 'https://www.collect.org',
    'street' => '123 Main Street',
    'city' => 'San Francisco',
    'state' => 'CA',
    'postalCode' => '94105',
    'contactFirstName' => 'Jane',
    'contactLastName' => 'Doe',
    'contactEmail' => '[email protected]',
    'contactPhone' => '+14155551234',
]);
echo "Brand created with ID: {$brand['id']}\n";

// Get a brand by ID
$fetched = $ccai->brands->get($brand['id']);
echo "Website match score: " . ($fetched['websiteMatchScore'] ?? 'pending') . "\n";

// List all brands for the account
$brands = $ccai->brands->list();
echo "Found " . count($brands) . " brand(s)\n";

// Update a brand (partial update)
$updated = $ccai->brands->update($brand['id'], [
    'street' => '456 Oak Avenue',
    'city' => 'Los Angeles',
]);

// Delete a brand
$ccai->brands->delete($brand['id']);



loudContactAI\CCAI\CCAI;

$ccai = new CCAI([
    'clientId' => 'YOUR-CLIENT-ID',
    'apiKey' => 'YOUR-API-KEY'
]);

// Create a campaign
$campaign = $ccai->campaigns->create([
    'brandId' => 1,
    'useCase' => 'MIXED',
    'subUseCases' => ['CUSTOMER_CARE', 'TWO_FACTOR_AUTHENTICATION', 'ACCOUNT_NOTIFICATION'],
    'description' => 'Security codes and support messaging.',
    'messageFlow' => 'Users opt-in via signup form at https://example.com/signup',
    'termsLink' => 'https://example.com/terms',
    'privacyLink' => 'https://example.com/privacy',
    'hasEmbeddedLinks' => true,
    'hasEmbeddedPhone' => false,
    'isAgeGated' => false,
    'isDirectLending' => false,
    'optInKeywords' => ['START'],
    'optInMessage' => 'Welcome! Reply STOP to cancel.',
    'optInProofUrl' => 'https://example.com/opt-in-proof.png',
    'helpKeywords' => ['HELP'],
    'helpMessage' => 'For HELP email [email protected].',
    'optOutKeywords' => ['STOP'],
    'optOutMessage' => 'STOP received. You are unsubscribed.',
    'sampleMessages' => [
        'Your code is 554321. Reply STOP to cancel.',
        'Your ticket has been updated. Reply HELP for info.',
    ],
]);
echo "Campaign created with ID: {$campaign['id']}\n";

// Get a campaign by ID
$fetched = $ccai->campaigns->get($campaign['id']);

// List all campaigns for the account
$campaigns = $ccai->campaigns->list();
echo "Found " . count($campaigns) . " campaign(s)\n";

// Update a campaign (partial update)
$updated = $ccai->campaigns->update($campaign['id'], [
    'description' => 'Updated description.',
]);

// Delete a campaign
$ccai->campaigns->delete($campaign['id']);
bash
composer 
bash
# Basic email sending
php send_email.php

# Advanced email campaigns with HTML templates and scheduling
php email_campaign_examples.php

# Webhook management and handling
php webhook_example.php