PHP Examples

PHP integration examples using the Metigan SDK. Learn how to send emails, manage contacts, and integrate Metigan into your PHP applications.

Installation

Composer

composer.jsonTerminal
1
composer require metigan/metigan-php

Basic Setup

basic.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php

require 'vendor/autoload.php';

use Metigan\MetiganClient;
use Metigan\Exception\ApiException;
use Metigan\Exception\ValidationException;

// Initialize the client
$client = new MetiganClient(getenv('METIGAN_API_KEY'));

// Send email
try {
    $result = $client->email()->sendEmail(
        fromAddress: "Sender <sender@example.com>",
        recipients: ["recipient@example.com"],
        subject: "Hello!",
        content: "<h1>Hello!</h1><p>Thank you for signing up.</p>"
    );

    if ($result['success'] ?? false) {
        echo "Email sent successfully!
";
        // IMPORTANT: API returns fields in camelCase (emailsRemaining), not snake_case
        echo "Emails remaining: " . ($result['emailsRemaining'] ?? 'N/A') . "
";
    }
} catch (ValidationException $e) {
    echo "Validation Error: " . $e->getMessage() . "
";
} catch (ApiException $e) {
    echo "API Error: " . $e->getStatusCode() . " - " . $e->getMessage() . "
";
}

Sending Emails

Basic Email

send-email.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
$result = $client->email()->sendEmail(
    fromAddress: "sender@example.com",
    recipients: ["recipient@example.com"],
    subject: "Email Subject",
    content: "<h1>HTML Content</h1><p>This is the email body.</p>"
);

if ($result['success']) {
    echo "Email sent successfully!
";
    echo "Emails remaining: " . $result['emailsRemaining'] . "
";
}

Email with CC and BCC

send-email-cc.phpPhp
1
2
3
4
5
6
7
8
9
$result = $client->email()->sendEmail(
    fromAddress: "company@email.com",
    recipients: ["main@email.com"],
    subject: "Meeting",
    content: "Email content",
    cc: ["copy@email.com"],
    bcc: ["hidden-copy@email.com"],
    replyTo: "reply-here@email.com"
);

Email with Attachments

send-email-attachment.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$fileData = file_get_contents("document.pdf");

$result = $client->email()->sendEmail(
    fromAddress: "company@email.com",
    recipients: ["customer@email.com"],
    subject: "Important Document",
    content: "Please find the document attached.",
    attachments: [
        [
            'content' => $fileData,
            'filename' => 'document.pdf',
            'contentType' => 'application/pdf'
        ]
    ]
);

Email with Template

send-email-template.phpPhp
1
2
3
4
5
6
7
8
9
10
$result = $client->email()->sendEmailWithTemplate(
    templateId: "template-123",
    variables: [
        'name' => 'John Doe',
        'company' => 'Acme Inc'
    ],
    fromAddress: "sender@example.com",
    recipients: ["recipient@example.com"],
    replyTo: "reply@example.com"
);

OTP Email (Verification Code)

Send One-Time Password emails with priority delivery and built-in rate limiting.

otp-example.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php

use Metigan\MetiganClient;

$client = new MetiganClient(getenv('METIGAN_API_KEY'));

/**
 * Send OTP with default template
 */
function sendVerificationCode(MetiganClient $client, string $userEmail): array {
    // Generate 6-digit code
    $code = str_pad((string)random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
    
    $result = $client->email()->sendOtp(
        to: $userEmail,
        from: "security@myapp.com",
        code: $code,
        appName: "MyApp",
        expiresInMinutes: 10
    );
    
    if ($result['success'] ?? false) {
        echo "OTP sent! Tracking: " . $result['trackingId'] . "
";
        return ['success' => true, 'code' => $code];
    }
    
    return ['success' => false, 'error' => $result['error'] ?? 'Unknown error'];
}

/**
 * Send OTP with custom branded template
 */
function sendBrandedOtp(MetiganClient $client, string $userEmail, string $templateId): array {
    $code = str_pad((string)random_int(100000, 999999), 6, '0', STR_PAD_LEFT);
    
    $result = $client->email()->sendOtp(
        to: $userEmail,
        from: "security@myapp.com",
        code: $code,
        appName: "MyApp",
        expiresInMinutes: 5,
        templateId: $templateId  // Custom branded template
    );
    
    return $result;
}

// Usage
$result = sendVerificationCode($client, "user@example.com");

Transactional Email (Fast Lane)

Send time-sensitive transactional emails like password resets, receipts, and confirmations.

transactional-example.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
<?php

use Metigan\MetiganClient;

$client = new MetiganClient(getenv('METIGAN_API_KEY'));

/**
 * Send password reset email
 */
function sendPasswordReset(MetiganClient $client, string $userEmail, string $resetLink): array {
    $result = $client->email()->sendTransactional(
        to: $userEmail,
        from: "security@myapp.com",
        subject: "Reset Your Password",
        content: "
            <h1>Password Reset</h1>
            <p>Click the link below to reset your password:</p>
            <a href='{$resetLink}' style='padding: 12px 24px; background: #2563eb; 
               color: white; text-decoration: none; border-radius: 8px; display: inline-block;'>
                Reset Password
            </a>
            <p style='color: #666; margin-top: 20px;'>This link expires in 1 hour.</p>
        "
    );
    
    return $result;
}

/**
 * Send order confirmation email
 */
function sendOrderConfirmation(MetiganClient $client, array $order): array {
    $result = $client->email()->sendTransactional(
        to: $order['customerEmail'],
        from: "orders@myshop.com",
        subject: "Order Confirmed #{$order['id']}",
        content: "
            <h1>Thank you for your order!</h1>
            <p>Order #{$order['id']} has been confirmed.</p>
            <p><strong>Total:</strong> $" . number_format($order['total'], 2) . "</p>
            <a href='https://myshop.com/orders/{$order['id']}'>Track Your Order</a>
        "
    );
    
    return $result;
}

/**
 * Send payment receipt
 */
function sendPaymentReceipt(MetiganClient $client, array $payment): array {
    $amount = number_format($payment['amount'], 2);
    
    $result = $client->email()->sendTransactional(
        to: $payment['customerEmail'],
        from: "billing@myservice.com",
        subject: "Payment Receipt - {$payment['currency']} {$amount}",
        content: "
            <h1>Payment Receipt</h1>
            <p>Thank you for your payment.</p>
            <div style='background: #f5f5f5; padding: 20px; border-radius: 8px;'>
                <p><strong>Amount:</strong> {$payment['currency']} {$amount}</p>
                <p><strong>Receipt ID:</strong> {$payment['id']}</p>
                <p><strong>Date:</strong> {$payment['date']}</p>
            </div>
        "
    );
    
    return $result;
}

// Usage examples
$resetResult = sendPasswordReset($client, "user@example.com", "https://myapp.com/reset?token=abc123");

$orderResult = sendOrderConfirmation($client, [
    'id' => 'ORD-2024-001',
    'customerEmail' => 'customer@example.com',
    'total' => 99.99
]);

Managing Contacts

Create Contact

create-contact.phpPhp
1
2
3
4
5
6
7
8
$contact = $client->contacts()->create(
    email: "new@email.com",
    audienceId: "audience-123",
    firstName: "Jane",
    lastName: "Doe",
    phone: "+1234567890",
    tags: ["customer", "newsletter"]
);

Get Contact

get-contact.phpPhp
1
2
$contact = $client->contacts()->get("contact-456");
echo $contact['email'] . ": " . $contact['firstName'];

List Contacts

list-contacts.phpPhp
1
2
3
4
5
6
7
8
9
10
11
$result = $client->contacts()->list(
    audienceId: "audience-123",
    status: "subscribed",
    page: 1,
    limit: 50
);

foreach ($result['contacts'] ?? [] as $contact) {
    echo $contact['email'] . ": " . ($contact['firstName'] ?? 'N/A') . "
";
}

Update Contact

update-contact.phpPhp
1
2
3
4
5
$updated = $client->contacts()->update(
    contactId: "contact-456",
    firstName: "Jane Marie",
    tags: ["customer", "vip"]
);

Manage Subscription

manage-subscription.phpPhp
1
2
3
4
5
// Subscribe
$client->contacts()->subscribe("contact-456");

// Unsubscribe
$client->contacts()->unsubscribe("contact-456");

Managing Audiences

Create Audience

create-audience.phpPhp
1
2
3
4
$audience = $client->audiences()->create(
    name: "Main Newsletter",
    description: "Main subscriber list"
);

List Audiences

list-audiences.phpPhp
1
2
3
4
5
6
$result = $client->audiences()->list(page: 1, limit: 10);

foreach ($result['audiences'] ?? [] as $audience) {
    echo $audience['name'] . ": " . ($audience['count'] ?? 0) . " contacts
";
}

Audience Stats

audience-stats.phpPhp
1
2
3
4
5
$stats = $client->audiences()->getStats("audience-123");
echo "Total: " . ($stats['total'] ?? 0) . "
";
echo "Subscribed: " . ($stats['subscribed'] ?? 0) . "
";

Error Handling

error-handling.phpPhp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use Metigan\Exception\ApiException;
use Metigan\Exception\ValidationException;

try {
    $result = $client->email()->sendEmail(/* ... */);
} catch (ValidationException $e) {
    echo "Validation Error: " . $e->getMessage() . "
";
    if ($e->getField()) {
        echo "Field: " . $e->getField() . "
";
    }
} catch (ApiException $e) {
    echo "API Error: " . $e->getStatusCode() . " - " . $e->getMessage() . "
";
} catch (Exception $e) {
    echo "Unknown error: " . $e->getMessage() . "
";
}

Advanced Configuration

config.phpPhp
1
2
3
4
5
6
7
$client = new MetiganClient(
    apiKey: "your-api-key",
    timeout: 30,        // Optional, defaults to 30 seconds
    retryCount: 3,      // Optional, defaults to 3
    retryDelay: 2,      // Optional, defaults to 2 seconds
    debug: false        // Optional, defaults to false
);
Response Format

The API returns all fields in camelCase format. Always use camelCase when accessing response data:

  • emailsRemaining (not emails_remaining)
  • recipientCount (not recipient_count)
  • successfulEmails (not successful_emails)