PHP code example of code-matic / opencdp-php

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

    

code-matic / opencdp-php example snippets




use Codematic\OpenCDP\CDPClient;
use Codematic\OpenCDP\CDPConfig;
use Codematic\OpenCDP\Identifiers;
use Codematic\OpenCDP\SendEmailRequest;

entify('user123', [
    'email' => '[email protected]',
    'name' => 'John Doe',
    'plan' => 'premium'
]);

// Track an event
$client->track('user123', 'purchase_completed', [
    'amount' => 99.99,
    'item_id' => 'prod-123'
]);

$config = new CDPConfig(
    cdpApiKey: 'your-cdp-api-key',
    cdpEndpoint: 'https://api.opencdp.io/gateway/data-gateway', // Optional custom endpoint
    timeout: 10000, // Request timeout in milliseconds (default: 10000)
    debug: false, // Enable debug logging (default: false)
    failOnException: false, // Throw exceptions on errors (default: false)
    logger: null, // Custom logger instance (LoggerInterface)
    sendToCustomerIo: false, // Enable dual-write to Customer.io (default: false)
    customerIo: [ // Required if sendToCustomerIo is true
        'siteId' => 'your-customer-io-site-id',
        'apiKey' => 'your-customer-io-api-key',
        'region' => 'us' // or 'eu' for EU data centers
    ]
);

$client->identify('user123', [
    'email' => '[email protected]',
    'name' => 'John Doe',
    'plan' => 'premium',
    'created_at' => time()
]);

$client->track('user123', 'purchase_completed', [
    'amount' => 99.99,
    'currency' => 'USD',
    'item_id' => 'prod-123',
    'category' => 'electronics'
]);

use Codematic\OpenCDP\DeviceRegistrationParameters;

$params = new DeviceRegistrationParameters(
    deviceId: 'device-abc-123',
    platform: 'ios',
    fcmToken: 'fcm-token-here',
    name: 'iOS Device',
    osVersion: '15.0',
    model: 'iPhone 13',
    appVersion: '1.0.0'
);

$client->registerDevice('user123', $params);

use Codematic\OpenCDP\SendEmailRequest;
use Codematic\OpenCDP\Identifiers;

$request = new SendEmailRequest([
    'to' => '[email protected]',
    'identifiers' => Identifiers::withId('user123'),
    'transactional_message_id' => 'WELCOME_EMAIL',
    'message_data' => [
        'name' => 'John',
        'activation_link' => 'https://example.com/activate'
    ]
]);

$response = $client->sendEmail($request);

$request = new SendEmailRequest([
    'to' => '[email protected]',
    'identifiers' => Identifiers::withEmail('[email protected]'),
    'transactional_message_id' => 'WELCOME_EMAIL',
    'subject' => 'Welcome to Our Platform!',
    'body' => '<h1>Welcome!</h1><p>Thank you for joining us.</p>',
    'message_data' => ['name' => 'John']
]);

$response = $client->sendEmail($request);

$request = new SendEmailRequest([
    'to' => '[email protected]',
    'identifiers' => Identifiers::withEmail('[email protected]'),
    'from' => '[email protected]',
    'subject' => 'Raw Email Test',
    'body' => '<h1>This is a raw HTML email</h1>',
    'plaintext_body' => 'This is a plain text email',
    'reply_to' => '[email protected]'
]);

$response = $client->sendEmail($request);

$request = (new SendEmailRequest([
    'to' => '[email protected]',
    'identifiers' => Identifiers::withId('user123'),
    'transactional_message_id' => 'INVOICE_EMAIL',
]))
    ->withAttachmentFile('/path/to/invoice.pdf')                // named "invoice.pdf"
    ->withAttachment('notes.txt', 'Plain text content')         // base64-encoded by default
    ->withAttachment('report.csv', $existingBase64, false);     // already base64, sent as-is

$response = $client->sendEmail($request);

use Codematic\OpenCDP\SendPushRequest;

$request = new SendPushRequest(
    identifiers: Identifiers::withId('user123'),
    transactional_message_id: 'WELCOME_PUSH',
    title: 'Welcome!',
    body: 'Thank you for joining us!'
);

$response = $client->sendPush($request);

$request = new SendPushRequest(
    identifiers: Identifiers::withEmail('[email protected]'),
    transactional_message_id: 'ORDER_UPDATE',
    message_data: [
        'order_id' => '12345',
        'tracking_number' => 'TRK123456',
        'items' => [
            ['name' => 'Shoes', 'price' => '59.99']
        ]
    ]
);

$response = $client->sendPush($request);

use Codematic\OpenCDP\SendSmsRequest;

// Using template
$request = new SendSmsRequest(
    identifiers: Identifiers::withId('user123'),
    transactional_message_id: 'WELCOME_SMS',
    message_data: ['name' => 'John']
);

// With body override
$request = new SendSmsRequest(
    identifiers: Identifiers::withId('user123'),
    transactional_message_id: 'WELCOME_SMS',
    body: 'Thank you for joining us!'
);

// Raw SMS (without template)
$request = new SendSmsRequest(
    identifiers: Identifiers::withId('user123'),
    to: '+1234567890',
    from: '+1987654321',
    body: 'This is a raw SMS message'
);

$response = $client->sendSms($request);

use Codematic\OpenCDP\SendWhatsAppRequest;

$request = new SendWhatsAppRequest(
    identifiers: Identifiers::withId('user123'),
    transactional_message_id: 'ORDER_WHATSAPP',
    to: '+14155551234',              // Optional: overrides the profile phone number
    message_data: ['order_number' => '12345']  // {{trigger.order_number}} in the template
);

$response = $client->sendWhatsApp($request);

$config = new CDPConfig(
    cdpApiKey: 'your-cdp-api-key',
    sendToCustomerIo: true,
    customerIo: [
        'siteId' => 'your-customer-io-site-id',
        'apiKey' => 'your-customer-io-api-key',
        'region' => 'us' // or 'eu'
    ]
);

$client = new CDPClient($config);

// Now all identify, track, and registerDevice calls will send data to both platforms
// Note: Transactional messages (email/push/SMS) are NOT sent to Customer.io to avoid duplicates

$config = new CDPConfig(
    cdpApiKey: 'your-cdp-api-key',
    failOnException: true // Throw exceptions on errors
);

$client = new CDPClient($config);

try {
    $client->identify('user123', ['email' => 'invalid-email']);
} catch (\InvalidArgumentException $e) {
    // Handle validation error
    echo "Validation error: " . $e->getMessage();
} catch (\Codematic\OpenCDP\Exceptions\CDPException $e) {
    // Handle CDP API error
    echo "CDP error: " . $e->getMessage();
    echo "Status: " . $e->status;
    echo "Error Code: " . $e->errorCode;
    print_r($e->summary);
}

$config = new CDPConfig(
    cdpApiKey: 'your-cdp-api-key',
    debug: true
);

$client = new CDPClient($config);

use Codematic\OpenCDP\LoggerInterface;

class MyLogger implements LoggerInterface
{
    public function debug(string $message, array $context = []): void
    {
        // Your debug logging logic
    }

    public function error(string $message, array $context = []): void
    {
        // Your error logging logic
    }

    public function warn(string $message, array $context = []): void
    {
        // Your warning logging logic
    }
}

$config = new CDPConfig(
    cdpApiKey: 'your-cdp-api-key',
    logger: new MyLogger()
);

$client->ping(); // Throws exception only if failOnException is true
bash
composer 
bash
# PHP CodeSniffer (PSR-12 standards)
composer phpcs

# Static Analysis
composer phpstan