Skip to content

How-To: Using Platform Connectors โ€‹

This guide provides a comprehensive walkthrough for using the AIOHM platform's internal connector services to interact with third-party platforms like Mautic and Postiz.

Table of Contents โ€‹


๐Ÿš€ Basic Usage โ€‹

Platform connectors are service classes that provide a standardized way to communicate with external APIs.

1. Import the Connector โ€‹

First, import the class for the service you want to use.

php
use App\Services\Platforms\MauticConnector;
use App\Services\PostizIntegrationService;

2. Create a Connector Instance โ€‹

It is highly recommended to use Laravel's dependency injection to automatically resolve connector instances in your class constructors. However, you can also instantiate them manually if needed.

php
// Recommended: Dependency Injection
public function __construct(private MauticConnector $mautic) {}

// Manual Instantiation
$mautic = new MauticConnector('your-tenant-id', $apiKey);
$postiz = new PostizIntegrationService();

3. Test the Connection โ€‹

Before performing operations, you can verify that your configuration is correct by testing the connection.

php
if ($mautic->testConnection()) {
    echo "Successfully connected to Mautic!";
} else {
    echo "Connection failed. Check your API key and URL.";
}

โš™๏ธ Common Operations โ€‹

Create a Contact (Mautic) โ€‹

php
$response = $mautic->upsertContact([
    'email' => '[email protected]',
    'firstname' => 'John',
    'lastname' => 'Doe',
    'tags' => ['customer', 'vip']
]);

Schedule Posts (Postiz) โ€‹

php
$response = $postiz->bulkSchedulePosts('your-tenant-id', [
    [
        'content' => 'Check out our new product!',
        'integrations' => ['facebook', 'instagram'],
        'scheduledAt' => '2024-12-01T10:00:00Z'
    ]
]);

โš ๏ธ Error Handling โ€‹

All connector methods return a standardized array. Always check the success key before proceeding.

php
try {
    $response = $connector->send($data);

    if (!$response['success']) {
        // Log the specific error message from the connector
        Log::error('Connector operation failed', [
            'error' => $response['error'],
            'message' => $response['message']
        ]);
    }
} catch (\Exception $e) {
    // Catch exceptions from network issues, etc.
    Log::critical('A critical exception occurred', ['error' => $e->getMessage()]);
}

Standard Response Format โ€‹

php
// On Success
[
    'success' => true,
    'data' => [...],  // Operation-specific data
    'message' => 'Operation completed successfully'
]

// On Failure
[
    'success' => false,
    'error' => 'ErrorType', // e.g., 'Validation Error', 'Authentication Failed'
    'message' => 'A human-readable explanation of what went wrong.'
]

๐Ÿ‘จโ€๐Ÿ’ป Usage in Code โ€‹

Connectors can be used anywhere in the application, from controllers to queued jobs.

In Services โ€‹

Using dependency injection in the constructor is the cleanest approach.

php
class CampaignService {
    public function __construct(
        private MauticConnector $mautic,
        private PostizIntegrationService $postiz
    ) {}

    public function launchCampaign(Brand $brand, array $data) {
        $segmentResult = $this->mautic->createSegment([...]);
        $socialResult = $this->postiz->bulkSchedulePosts($brand->id, [...]);

        // ...
    }
}

In Controllers โ€‹

php
class CampaignController {
    public function store(Request $request, MauticConnector $mautic) {
        $validated = $request->validate([...]);
        $result = $mautic->upsertContact($validated);

        return response()->json($result);
    }
}

In Queued Jobs โ€‹

Type-hint the connector in the handle method for automatic resolution.

php
class SendCampaignJob implements ShouldQueue {
    use InteractsWithQueue, Queueable, SerializesModels;

    public function handle(MauticConnector $connector) {
        $result = $connector->createCampaign([...]);

        if (!$result['success']) {
            throw new \Exception($result['message']);
        }
    }
}

๐Ÿ”ง Configuration โ€‹

Credentials for all third-party services are stored as environment variables and loaded via the config/services.php file. Never hardcode credentials.

1. Environment Variables (.env) โ€‹

Add the API keys and URLs for each service to your .env file.

dotenv
# .env

# Mautic
MAUTIC_URL=https://mautic.example.com
MAUTIC_API_KEY=your-api-key

# Postiz
POSTIZ_URL=https://social.aiohm.app
POSTIZ_API_KEY=your-api-key

2. Services Configuration (config/services.php) โ€‹

This file reads the .env variables and makes them available to the application.

php
// config/services.php

return [
    // ...
    'mautic' => [
        'url' => env('MAUTIC_URL'),
        'api_key' => env('MAUTIC_API_KEY'),
    ],
    // ...
];

๐Ÿงช Testing & Debugging โ€‹

Check Connection Status โ€‹

Quickly verify your credentials and network access from the command line.

bash
php artisan tinker
>>> $connector = app(App\Services\Platforms\MauticConnector::class);
>>> $connector->testConnection();
=> true

View Logs โ€‹

Tail the application log and filter for the service you are debugging.

bash
tail -f storage/logs/laravel.log | grep -i "mautic"

โœจ Best Practices โ€‹

  1. Always Check the success Key: Never assume an API call was successful.
  2. Use Try-Catch Blocks: Wrap external API calls in try-catch blocks to handle network failures gracefully.
  3. Queue Long-Running Jobs: For bulk operations like sending thousands of emails, dispatch a Queued Job to avoid blocking the user's request.
  4. Cache Data: Cache responses from platform APIs (like lists of segments or templates) to reduce latency and avoid hitting rate limits. Use Cache::remember().
  5. Implement Retry Logic: For critical operations, consider a simple retry mechanism with exponential backoff for transient network errors.

Released under the MIT License.