PHP Examples

PHP

Complete PHP examples for integrating with the Magnetite API using cURL

Requirements

PHP 7.4+ with cURL support:

# Check PHP version and cURL support
php -v
php -m | grep curl

Basic cURL Client Class

A simple client class using PHP's built-in cURL functionality:

<?php
// MagnetiteClient.php

class MagnetiteClient {
    private $apiKey;
    private $baseUrl;

    public function __construct($apiKey = null) {
        $this->apiKey = $apiKey ?: $_ENV['MAGNETITE_API_KEY'] ?? getenv('MAGNETITE_API_KEY');
        $this->baseUrl = 'https://magnetite.ai/api';

        if (!$this->apiKey) {
            throw new Exception('API key is required. Set MAGNETITE_API_KEY environment variable or pass it directly.');
        }
    }

    public function addLead($campaignId, $leadData) {
        return $this->makeRequest('POST', "/campaigns/{$campaignId}/leads", $leadData);
    }

    public function addLeadsBulk($campaignId, $leads, $delaySeconds = 1) {
        $results = [];

        foreach ($leads as $index => $lead) {
            try {
                $result = $this->addLead($campaignId, $lead);
                $results[] = [
                    'lead' => $lead,
                    'success' => true,
                    'result' => $result
                ];
                echo "Added lead " . ($index + 1) . "/" . count($leads) . ": {$lead['email']}\n";
            } catch (Exception $e) {
                $results[] = [
                    'lead' => $lead,
                    'success' => false,
                    'error' => $e->getMessage()
                ];
                echo "Failed to add lead {$lead['email']}: " . $e->getMessage() . "\n";
            }

            // Respect rate limits
            if ($index < count($leads) - 1) {
                sleep($delaySeconds);
            }
        }

        return $results;
    }

    private function makeRequest($method, $endpoint, $data = null) {
        $url = $this->baseUrl . $endpoint;

        $curl = curl_init();

        $headers = [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json',
            'User-Agent: MagnetitePHP/1.0'
        ];

        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_FOLLOWLOCATION => true,
        ]);

        if ($data && ($method === 'POST' || $method === 'PUT')) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        }

        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $error = curl_error($curl);

        curl_close($curl);

        if ($error) {
            throw new Exception("cURL Error: " . $error);
        }

        $decodedResponse = json_decode($response, true);

        if ($httpCode >= 400) {
            $errorMessage = isset($decodedResponse['error'])
                ? $decodedResponse['error']
                : "HTTP Error $httpCode";
            throw new Exception("API Error ($httpCode): $errorMessage");
        }

        if (!$decodedResponse) {
            throw new Exception("Invalid JSON response: " . $response);
        }

        return $decodedResponse;
    }
}

Environment Configuration

Create a .env file for your credentials:

# .env
MAGNETITE_API_KEY=sk_your_api_key_here
MAGNETITE_CAMPAIGN_ID=your_campaign_id_here

And a simple environment loader:

<?php
// load_env.php

function loadEnv($path) {
    if (!file_exists($path)) {
        return;
    }

    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) {
            continue; // Skip comments
        }

        list($key, $value) = explode('=', $line, 2);
        $key = trim($key);
        $value = trim($value);

        if (!array_key_exists($key, $_SERVER) && !array_key_exists($key, $_ENV)) {
            putenv(sprintf('%s=%s', $key, $value));
            $_ENV[$key] = $value;
            $_SERVER[$key] = $value;
        }
    }
}

// Load environment variables
loadEnv(__DIR__ . '/.env');

Complete Examples

Add a Single Lead
Simple example of adding a lead to your campaign
<?php
// add_lead.php

require_once 'load_env.php';
require_once 'MagnetiteClient.php';

function addSingleLead() {
    try {
        $client = new MagnetiteClient();

        $result = $client->addLead(
            getenv('MAGNETITE_CAMPAIGN_ID'),
            [
                'companyName' => 'Acme Corp',
                'contactName' => 'John Smith',
                'email' => 'john@acme.com',
                'title' => 'VP of Sales',
                'domain' => 'acme.com',
                'linkedInUrl' => 'https://linkedin.com/in/johnsmith',
                'notes' => 'Met at SaaStr conference'
            ]
        );

        echo "Lead added successfully!\n";
        echo "Prospect ID: {$result['prospectId']}\n";
        echo "Status: {$result['status']}\n";
        echo "Message: {$result['message']}\n";

        return $result;

    } catch (Exception $e) {
        echo "Error adding lead: " . $e->getMessage() . "\n";
        throw $e;
    }
}

// Run the example
try {
    addSingleLead();
    echo "Done!\n";
} catch (Exception $e) {
    exit(1);
}
Add Lead with Enrichment Data
Pass pre-enriched company and contact data
<?php
// add_enriched_lead.php

require_once 'load_env.php';
require_once 'MagnetiteClient.php';

function addEnrichedLead() {
    try {
        $client = new MagnetiteClient();

        $result = $client->addLead(
            getenv('MAGNETITE_CAMPAIGN_ID'),
            [
                // Required fields
                'companyName' => 'TechCorp Inc',
                'contactName' => 'Jane Doe',
                'email' => 'jane@techcorp.com',

                // Optional basic fields
                'title' => 'Marketing Director',
                'domain' => 'techcorp.com',
                'phone' => '+1-555-123-4567',
                'linkedInUrl' => 'https://linkedin.com/in/janedoe',
                'companyLinkedInUrl' => 'https://linkedin.com/company/techcorp',
                'notes' => 'Referred by partner XYZ',

                // Pre-enriched company data (optional)
                'company' => [
                    'industry' => 'Technology',
                    'employeeCount' => 250,
                    'revenue' => '$50M-100M',
                    'fundingStage' => 'Series B',
                    'technologies' => ['React', 'Node.js', 'AWS'],
                    'description' => 'Enterprise SaaS platform'
                ],

                // Pre-enriched contact data (optional)
                'contact' => [
                    'bio' => 'Marketing leader with 10+ years experience',
                    'seniority' => 'Director',
                    'department' => 'Marketing',
                    'city' => 'San Francisco',
                    'state' => 'CA',
                    'country' => 'USA'
                ],

                // Extra context for research agent (optional)
                'extraContext' => [
                    'meetingNotes' => 'Discussed integration needs',
                    'painPoints' => ['Lead generation', 'Sales automation'],
                    'referredBy' => 'Partner program'
                ]
            ]
        );

        echo "Enriched lead added!\n";
        echo "Result: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";

    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "\n";
        throw $e;
    }
}

// Run the example
try {
    addEnrichedLead();
    echo "Done!\n";
} catch (Exception $e) {
    exit(1);
}
Bulk Lead Import
Import multiple leads with rate limiting
<?php
// bulk_import.php

require_once 'load_env.php';
require_once 'MagnetiteClient.php';

function bulkImport() {
    $client = new MagnetiteClient();

    $leads = [
        [
            'companyName' => 'StartupCo',
            'contactName' => 'Sarah Johnson',
            'email' => 'sarah@startupco.com',
            'title' => 'CEO'
        ],
        [
            'companyName' => 'BigCorp Industries',
            'contactName' => 'Michael Chen',
            'email' => 'michael@bigcorp.com',
            'title' => 'Sales Director'
        ],
        [
            'companyName' => 'MidSize Solutions',
            'contactName' => 'Emily Rodriguez',
            'email' => 'emily@midsize.com',
            'title' => 'VP of Marketing'
        ]
    ];

    echo "Importing " . count($leads) . " leads to campaign...\n";

    $results = $client->addLeadsBulk(
        getenv('MAGNETITE_CAMPAIGN_ID'),
        $leads,
        1 // 1 second delay between requests
    );

    // Summary
    $successful = array_filter($results, function($r) { return $r['success']; });
    $failed = array_filter($results, function($r) { return !$r['success']; });

    echo "\n=== IMPORT SUMMARY ===\n";
    echo "Total processed: " . count($results) . "\n";
    echo "Successful: " . count($successful) . "\n";
    echo "Failed: " . count($failed) . "\n";

    if (count($failed) > 0) {
        echo "\nFailed leads:\n";
        foreach ($failed as $result) {
            echo "  - {$result['lead']['email']}: {$result['error']}\n";
        }
    }

    return $results;
}

// Run the example
try {
    bulkImport();
    echo "\nBulk import complete!\n";
} catch (Exception $e) {
    echo "Fatal error: " . $e->getMessage() . "\n";
    exit(1);
}
CSV Import
Import leads from a CSV file
<?php
// csv_import.php

require_once 'load_env.php';
require_once 'MagnetiteClient.php';

function importFromCsv($csvPath) {
    $client = new MagnetiteClient();
    $campaignId = getenv('MAGNETITE_CAMPAIGN_ID');

    $leads = [];

    // Read CSV file
    if (($handle = fopen($csvPath, 'r')) !== false) {
        $headers = fgetcsv($handle);

        while (($row = fgetcsv($handle)) !== false) {
            $data = array_combine($headers, $row);

            $lead = [
                'companyName' => $data['company_name'] ?? $data['company'],
                'contactName' => $data['contact_name'] ?? $data['name'],
                'email' => $data['email'],
            ];

            // Add optional fields if present
            if (!empty($data['title'])) {
                $lead['title'] = $data['title'];
            }
            if (!empty($data['domain'])) {
                $lead['domain'] = $data['domain'];
            }
            if (!empty($data['linkedin_url'])) {
                $lead['linkedInUrl'] = $data['linkedin_url'];
            }
            if (!empty($data['notes'])) {
                $lead['notes'] = $data['notes'];
            }

            $leads[] = $lead;
        }

        fclose($handle);
    }

    echo "Loaded " . count($leads) . " leads from CSV\n";
    echo "Importing to campaign $campaignId...\n";

    $results = $client->addLeadsBulk($campaignId, $leads, 1);

    // Summary
    $successful = array_filter($results, function($r) { return $r['success']; });
    $failed = array_filter($results, function($r) { return !$r['success']; });

    echo "\nImported " . count($successful) . " leads successfully\n";
    echo "Failed: " . count($failed) . "\n";

    // Save failed leads for retry
    if (count($failed) > 0) {
        $fp = fopen('failed_leads.csv', 'w');
        fputcsv($fp, array_keys($failed[0]['lead']));
        foreach ($failed as $item) {
            fputcsv($fp, $item['lead']);
        }
        fclose($fp);
        echo "Failed leads saved to failed_leads.csv\n";
    }

    return $results;
}

// Run the example
if (isset($argv[1])) {
    importFromCsv($argv[1]);
} else {
    echo "Usage: php csv_import.php leads.csv\n";
}
Webhook Receiver
Handle meeting booked webhooks from Magnetite
<?php
// webhook.php

// Read the incoming webhook payload
$payload = file_get_contents('php://input');
$event = json_decode($payload, true);

// Log the webhook
file_put_contents(
    'webhooks.log',
    date('Y-m-d H:i:s') . " - " . $payload . "\n",
    FILE_APPEND
);

if ($event['event'] === 'meeting_booked') {
    $prospect = $event['prospect'];
    $meeting = $event['meeting'];
    $campaignId = $event['campaignId'];

    // Handle the meeting booking
    echo "Meeting booked!\n";
    echo "Company: {$prospect['companyName']}\n";
    echo "Contact: {$prospect['contactName']}\n";
    echo "Email: {$prospect['email']}\n";
    echo "Scheduled: {$meeting['scheduledAt']}\n";
    echo "Duration: {$meeting['duration']} minutes\n";

    // Examples of what you might do:
    // - Update your CRM
    // - Send Slack notification
    // - Create calendar event
    // - Update database

    // updateCRM($prospect, $meeting);
    // sendSlackNotification($prospect, $meeting);
}

// Return success response
http_response_code(200);
header('Content-Type: application/json');
echo json_encode(['received' => true]);

Next Steps

Explore more examples in different programming languages or dive deeper into the API.