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
- Common Operations
- Error Handling
- Usage in Code
- Configuration
- Testing & Debugging
- Best Practices
๐ 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.
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.
// 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.
if ($mautic->testConnection()) {
echo "Successfully connected to Mautic!";
} else {
echo "Connection failed. Check your API key and URL.";
}โ๏ธ Common Operations โ
Create a Contact (Mautic) โ
$response = $mautic->upsertContact([
'email' => '[email protected]',
'firstname' => 'John',
'lastname' => 'Doe',
'tags' => ['customer', 'vip']
]);Schedule Posts (Postiz) โ
$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.
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 โ
// 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.
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 โ
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.
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.
# .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-key2. Services Configuration (config/services.php) โ
This file reads the .env variables and makes them available to the application.
// 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.
php artisan tinker
>>> $connector = app(App\Services\Platforms\MauticConnector::class);
>>> $connector->testConnection();
=> trueView Logs โ
Tail the application log and filter for the service you are debugging.
tail -f storage/logs/laravel.log | grep -i "mautic"โจ Best Practices โ
- Always Check the
successKey: Never assume an API call was successful. - Use Try-Catch Blocks: Wrap external API calls in
try-catchblocks to handle network failures gracefully. - Queue Long-Running Jobs: For bulk operations like sending thousands of emails, dispatch a Queued Job to avoid blocking the user's request.
- Cache Data: Cache responses from platform APIs (like lists of segments or templates) to reduce latency and avoid hitting rate limits. Use
Cache::remember(). - Implement Retry Logic: For critical operations, consider a simple retry mechanism with exponential backoff for transient network errors.
