Hey there, fellow developer! Ready to dive into the world of Mautic API integration? You're in the right place. We'll be using the mautic/api-library
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that mautic/api-library
installed:
composer require mautic/api-library
Easy peasy, right?
Now, let's tackle OAuth2 authentication:
use Mautic\Auth\ApiAuth; $auth = new ApiAuth(); $credentials = [ 'clientKey' => 'your_client_id', 'clientSecret' => 'your_client_secret', 'callback' => 'https://your-callback-url.com' ]; $authorizationUrl = $auth->newAuth($credentials, 'OAuth2'); // Redirect user to $authorizationUrl, then handle the callback
Let's get that API client up and running:
use Mautic\MauticApi; $api = new MauticApi(); $contactApi = $api->newApi('contacts', $auth, 'https://your-mautic-instance.com'); // Fetch contacts $contacts = $contactApi->getList();
Here are some operations you'll probably use a lot:
// Create a contact $newContact = $contactApi->create(['email' => '[email protected]']); // Update a contact $updatedContact = $contactApi->edit(123, ['firstname' => 'John']); // Delete a contact $contactApi->delete(123); // Fetch segments $segmentApi = $api->newApi('segments', $auth, 'https://your-mautic-instance.com'); $segments = $segmentApi->getList(); // Add contact to segment $segmentApi->addContact(456, 123); // segmentId, contactId
Always check those responses:
if ($contacts['total'] > 0) { foreach ($contacts['contacts'] as $contact) { // Do something with each contact } } else { // Handle no contacts found }
Want to level up? Try these:
// Pagination $contacts = $contactApi->getList($start, $limit, $orderBy, $orderByDir, $publishedOnly, $minimal); // Filtering $contacts = $contactApi->getList(0, 100, null, null, null, null, [ 'search' => 'email:*@example.com', 'orderBy' => 'email', 'orderByDir' => 'DESC' ]); // Batch operations $batchApi = $api->newApi('contacts', $auth, 'https://your-mautic-instance.com'); $batchApi->createBatch([ ['email' => '[email protected]'], ['email' => '[email protected]'] ]);
And there you have it! You're now armed with the knowledge to build a solid Mautic API integration. Remember, the official Mautic API documentation is your friend for more in-depth info.
Now go forth and integrate! You've got this. 💪