PHP Examples

PHP

Complete PHP examples for integrating with the Magnetite API using cURL and Guzzle HTTP client

Requirements

PHP 7.4+ with cURL support, or optionally Guzzle HTTP client for more advanced features:

# Using Composer (optional, for Guzzle)
composer require guzzlehttp/guzzle vlucas/phpdotenv

# Or just use built-in cURL (no dependencies required)

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 generateLeadMagnet($projectId, $data) {
        return $this->makeRequest('POST', "/projects/{$projectId}/generate", $data);
    }
    
    public function checkStatus($jobId) {
        return $this->makeRequest('GET', "/generation/{$jobId}/status");
    }
    
    public function checkLeadStatus($leadId) {
        return $this->makeRequest('GET', "/leads/{$leadId}/job-status");
    }
    
    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']['message']) 
                ? $decodedResponse['error']['message'] 
                : "HTTP Error $httpCode";
            throw new Exception("API Error ($httpCode): $errorMessage");
        }
        
        if (!$decodedResponse) {
            throw new Exception("Invalid JSON response: " . $response);
        }
        
        return $decodedResponse;
    }
    
    public function pollUntilComplete($jobId, $maxAttempts = 30, $initialDelay = 2) {
        for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
            try {
                $status = $this->checkStatus($jobId);
                
                echo "Attempt $attempt: {$status['status']} ({$status['progress']}%)
";
                
                if ($status['status'] === 'completed') {
                    return $status['result'] ?? $status;
                }
                
                if ($status['status'] === 'failed') {
                    $errorMsg = $status['error']['message'] ?? 'Generation failed';
                    throw new Exception("Generation failed: $errorMsg");
                }
                
                // Exponential backoff with max delay
                $delay = min($initialDelay * pow(1.5, $attempt - 1), 30);
                echo "Waiting " . number_format($delay, 1) . "s before next check...
";
                sleep($delay);
                
            } catch (Exception $e) {
                echo "Polling error on attempt $attempt: " . $e->getMessage() . "
";
                if ($attempt === $maxAttempts) {
                    throw $e;
                }
                sleep(5);
            }
        }
        
        throw new Exception("Generation did not complete within expected time");
    }
}

Environment Configuration

Create a .env file for your credentials:

# .env
MAGNETITE_API_KEY=sk_your_api_key_here
MAGNETITE_PROJECT_ID=your_project_id_here

And a simple environment loader (or use vlucas/phpdotenv):

<?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

Basic Lead Magnet Generation
Simple example of generating a lead magnet
<?php
// basic_example.php

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

function basicExample() {
    try {
        $client = new MagnetiteClient();
        
        $result = $client->generateLeadMagnet(
            getenv('MAGNETITE_PROJECT_ID'),
            [
                'email' => 'john.smith@example.com',
                'fullName' => 'John Smith',
                'company' => 'Acme Corp',
                'domain' => 'acmecorp.com',
                'title' => 'VP of Sales',
                'industry' => 'SaaS'
            ]
        );
        
        echo "Generation started:
";
        echo "Lead ID: {$result['leadId']}
";
        echo "Job ID: {$result['jobId']}
";
        echo "Lead Magnet URL: {$result['leadMagnetUrl']}
";
        
        return $result;
        
    } catch (Exception $e) {
        echo "Error generating lead magnet: " . $e->getMessage() . "
";
        throw $e;
    }
}

// Run the example
try {
    basicExample();
    echo "Done!
";
} catch (Exception $e) {
    exit(1);
}
Generate and Wait for Completion
Poll the API until generation is complete
<?php
// wait_for_completion.php

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

function generateAndWait() {
    try {
        $client = new MagnetiteClient();
        
        // Start generation
        $generation = $client->generateLeadMagnet(
            getenv('MAGNETITE_PROJECT_ID'),
            [
                'email' => 'jane.doe@techcorp.com',
                'fullName' => 'Jane Doe',
                'company' => 'TechCorp Inc',
                'domain' => 'techcorp.com',
                'title' => 'Marketing Director',
                'industry' => 'Technology',
                'companySize' => '51-200'
            ]
        );
        
        echo "Generation started with job ID: {$generation['jobId']}
";
        echo "Lead magnet will be available at: {$generation['leadMagnetUrl']}
";
        
        // Wait for completion
        $result = $client->pollUntilComplete($generation['jobId']);
        
        echo "Generation completed!
";
        echo "Final URL: " . ($result['leadMagnetUrl'] ?? 'N/A') . "
";
        echo "Processing time: " . ($result['processingTime'] ?? 'N/A') . "s
";
        
        return $result;
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "
";
        throw $e;
    }
}

// Run the example
try {
    generateAndWait();
    echo "All done!
";
} catch (Exception $e) {
    exit(1);
}
Bulk Processing
Process multiple leads with proper rate limiting
<?php
// bulk_processing.php

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

function processSingleLead($client, $lead) {
    try {
        $result = $client->generateLeadMagnet(
            getenv('MAGNETITE_PROJECT_ID'),
            $lead
        );
        
        echo "Started generation for {$lead['email']} (Job: {$result['jobId']})
";
        
        return [
            'lead' => $lead,
            'success' => true,
            'result' => $result
        ];
        
    } catch (Exception $e) {
        echo "Failed to start generation for {$lead['email']}: " . $e->getMessage() . "
";
        return [
            'lead' => $lead,
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

function bulkProcessing() {
    $client = new MagnetiteClient();
    
    $leads = [
        [
            'email' => 'ceo@startup.com',
            'fullName' => 'Sarah Johnson',
            'company' => 'StartupCo',
            'domain' => 'startup.com',
            'title' => 'CEO'
        ],
        [
            'email' => 'director@bigcorp.com',
            'fullName' => 'Michael Chen',
            'company' => 'BigCorp Industries',
            'domain' => 'bigcorp.com',
            'title' => 'Sales Director'
        ],
        [
            'email' => 'manager@midsize.com',
            'fullName' => 'Emily Rodriguez',
            'company' => 'MidSize Solutions',
            'domain' => 'midsize.com',
            'title' => 'Marketing Manager'
        ]
    ];
    
    $results = [];
    $batchSize = 3;
    $delayBetweenRequests = 7; // seconds (to respect rate limits)
    
    echo "Processing " . count($leads) . " leads with {$delayBetweenRequests}s delay between requests
";
    
    // Process leads in batches to respect rate limits
    for ($i = 0; $i < count($leads); $i += $batchSize) {
        $batch = array_slice($leads, $i, $batchSize);
        
        echo "Processing batch " . (intval($i / $batchSize) + 1) . " (" . count($batch) . " leads)
";
        
        foreach ($batch as $lead) {
            $result = processSingleLead($client, $lead);
            $results[] = $result;
            
            // Add delay between individual requests
            if (count($results) < count($leads)) {
                echo "Waiting {$delayBetweenRequests}s before next request...
";
                sleep($delayBetweenRequests);
            }
        }
    }
    
    // Summary
    $successful = array_filter($results, function($r) { return $r['success']; });
    $failed = array_filter($results, function($r) { return !$r['success']; });
    
    echo "
=== SUMMARY ===
";
    echo "Total processed: " . count($results) . "
";
    echo "Successful: " . count($successful) . "
";
    echo "Failed: " . count($failed) . "
";
    
    if (count($failed) > 0) {
        echo "
Failed leads:
";
        foreach ($failed as $result) {
            echo "  - {$result['lead']['email']}: {$result['error']}
";
        }
    }
    
    return $results;
}

// Run the example
try {
    bulkProcessing();
    echo "Bulk processing complete!
";
} catch (Exception $e) {
    echo "Fatal error: " . $e->getMessage() . "
";
    exit(1);
}
Guzzle HTTP Client Implementation
Advanced client using Guzzle for better HTTP handling
<?php
// GuzzleMagnetiteClient.php
// Requires: composer require guzzlehttp/guzzle

use GuzzleHttpClient;
use GuzzleHttpExceptionRequestException;
use GuzzleHttpExceptionClientException;
use GuzzleHttpExceptionServerException;

class GuzzleMagnetiteClient {
    private $client;
    private $apiKey;
    
    public function __construct($apiKey = null) {
        $this->apiKey = $apiKey ?: $_ENV['MAGNETITE_API_KEY'] ?? getenv('MAGNETITE_API_KEY');
        
        if (!$this->apiKey) {
            throw new Exception('API key is required');
        }
        
        $this->client = new Client([
            'base_uri' => 'https://magnetite.ai/api/',
            'timeout' => 30,
            'headers' => [
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
                'User-Agent' => 'MagnetitePHP-Guzzle/1.0'
            ]
        ]);
    }
    
    public function generateLeadMagnet($projectId, $data) {
        return $this->makeRequest('POST', "projects/{$projectId}/generate", ['json' => $data]);
    }
    
    public function checkStatus($jobId) {
        return $this->makeRequest('GET', "generation/{$jobId}/status");
    }
    
    public function checkLeadStatus($leadId) {
        return $this->makeRequest('GET', "leads/{$leadId}/job-status");
    }
    
    private function makeRequest($method, $endpoint, $options = []) {
        try {
            $response = $this->client->request($method, $endpoint, $options);
            $body = $response->getBody()->getContents();
            
            return json_decode($body, true);
            
        } catch (ClientException $e) {
            // 4xx errors
            $response = $e->getResponse();
            $body = $response->getBody()->getContents();
            $errorData = json_decode($body, true);
            
            $message = isset($errorData['error']['message']) 
                ? $errorData['error']['message']
                : 'Client error';
                
            throw new Exception("API Error ({$response->getStatusCode()}): {$message}");
            
        } catch (ServerException $e) {
            // 5xx errors
            $response = $e->getResponse();
            throw new Exception("Server Error ({$response->getStatusCode()}): Server error occurred");
            
        } catch (RequestException $e) {
            // Network errors
            throw new Exception("Request Error: " . $e->getMessage());
        }
    }
    
    public function generateWithRetry($projectId, $data, $maxRetries = 3) {
        $attempt = 0;
        $lastException = null;
        
        while ($attempt < $maxRetries) {
            try {
                $attempt++;
                echo "Generation attempt $attempt/$maxRetries
";
                
                $result = $this->generateLeadMagnet($projectId, $data);
                echo "Generation successful on attempt $attempt
";
                
                return $result;
                
            } catch (Exception $e) {
                $lastException = $e;
                $errorMessage = $e->getMessage();
                
                // Check if error is retryable
                if (strpos($errorMessage, 'rate limit') !== false) {
                    echo "Rate limit hit on attempt $attempt, waiting longer...
";
                    sleep(pow(2, $attempt) * 5); // Exponential backoff
                } elseif (strpos($errorMessage, 'Server Error') !== false) {
                    echo "Server error on attempt $attempt, retrying...
";
                    sleep($attempt * 2);
                } elseif (strpos($errorMessage, 'insufficient credits') !== false) {
                    echo "Insufficient credits - cannot retry
";
                    throw $e;
                } else {
                    echo "Non-retryable error on attempt $attempt: $errorMessage
";
                    if ($attempt === $maxRetries) {
                        throw $e;
                    }
                    sleep(1);
                }
            }
        }
        
        throw $lastException;
    }
}

// Example usage
function guzzleExample() {
    try {
        $client = new GuzzleMagnetiteClient();
        
        $result = $client->generateWithRetry(
            getenv('MAGNETITE_PROJECT_ID'),
            [
                'email' => 'test@example.com',
                'fullName' => 'Test User',
                'company' => 'Test Company',
                'title' => 'Test Title'
            ]
        );
        
        echo "Generation started successfully!
";
        echo "Job ID: {$result['jobId']}
";
        echo "Lead Magnet URL: {$result['leadMagnetUrl']}
";
        
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage() . "
";
    }
}

Error Handling Best Practices

Comprehensive error handling with logging and retries:

<?php
// error_handling_example.php

class MagnetiteErrorHandler {
    private $client;
    private $logFile;
    
    public function __construct($client, $logFile = null) {
        $this->client = $client;
        $this->logFile = $logFile ?: __DIR__ . '/magnetite.log';
    }
    
    public function processLeadWithRetry($leadData, $maxRetries = 3) {
        $attempt = 0;
        $lastException = null;
        
        while ($attempt < $maxRetries) {
            try {
                $attempt++;
                $this->log("INFO", "Processing {$leadData['email']} - attempt $attempt/$maxRetries");
                
                $result = $this->client->generateLeadMagnet(
                    getenv('MAGNETITE_PROJECT_ID'),
                    $leadData
                );
                
                $this->log("INFO", "Successfully processed {$leadData['email']} - Job ID: {$result['jobId']}");
                
                return [
                    'success' => true,
                    'result' => $result,
                    'attempts' => $attempt
                ];
                
            } catch (Exception $e) {
                $lastException = $e;
                $errorMessage = $e->getMessage();
                
                $this->log("ERROR", "Attempt $attempt failed for {$leadData['email']}: $errorMessage");
                
                // Determine if we should retry
                if ($this->isRetryableError($errorMessage)) {
                    if ($attempt < $maxRetries) {
                        $delay = $this->getRetryDelay($errorMessage, $attempt);
                        $this->log("INFO", "Retrying in {$delay}s...");
                        sleep($delay);
                        continue;
                    }
                } else {
                    $this->log("ERROR", "Non-retryable error for {$leadData['email']}: $errorMessage");
                    break;
                }
            }
        }
        
        $this->log("ERROR", "All attempts failed for {$leadData['email']}");
        
        return [
            'success' => false,
            'error' => $lastException->getMessage(),
            'attempts' => $attempt
        ];
    }
    
    private function isRetryableError($errorMessage) {
        $retryableErrors = [
            'rate limit',
            'server error',
            'timeout',
            'network error',
            'connection',
            '503',
            '502',
            '500'
        ];
        
        $errorLower = strtolower($errorMessage);
        
        foreach ($retryableErrors as $pattern) {
            if (strpos($errorLower, $pattern) !== false) {
                return true;
            }
        }
        
        return false;
    }
    
    private function getRetryDelay($errorMessage, $attempt) {
        if (strpos(strtolower($errorMessage), 'rate limit') !== false) {
            return min(pow(2, $attempt) * 10, 60); // Exponential backoff for rate limits
        }
        
        return min($attempt * 5, 30); // Linear backoff for other errors
    }
    
    private function log($level, $message) {
        $timestamp = date('Y-m-d H:i:s');
        $logEntry = "[$timestamp] $level: $message
";
        
        file_put_contents($this->logFile, $logEntry, FILE_APPEND | LOCK_EX);
        echo $logEntry;
    }
}

// Usage example
function errorHandlingExample() {
    require_once 'MagnetiteClient.php';
    
    $client = new MagnetiteClient();
    $handler = new MagnetiteErrorHandler($client);
    
    $leads = [
        ['email' => 'test1@example.com', 'fullName' => 'Test User 1', 'company' => 'Company 1'],
        ['email' => 'test2@example.com', 'fullName' => 'Test User 2', 'company' => 'Company 2'],
    ];
    
    $results = [];
    
    foreach ($leads as $lead) {
        $result = $handler->processLeadWithRetry($lead);
        $results[] = $result;
        
        // Brief pause between leads
        sleep(2);
    }
    
    // Summary
    $successful = array_filter($results, function($r) { return $r['success']; });
    $failed = array_filter($results, function($r) { return !$r['success']; });
    
    echo "
=== FINAL SUMMARY ===
";
    echo "Total processed: " . count($results) . "
";
    echo "Successful: " . count($successful) . "
";
    echo "Failed: " . count($failed) . "
";
    
    $totalAttempts = array_sum(array_column($results, 'attempts'));
    echo "Total API calls made: $totalAttempts
";
    
    return $results;
}

// Run the example
try {
    errorHandlingExample();
} catch (Exception $e) {
    echo "Fatal error: " . $e->getMessage() . "
";
}

Next Steps

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