Mautic has API to interact with other systems. There is PHP API library for faster integration to PHP projects.
API library isn't at Packagist in time of writing this article. Good chance is the library is at Packagist in time of reading, so install it from there and skip this.
Install from GitHub repo. So to use the library as Composer package from GitHub repo your composer.json should contain:
...
"repositories": {
"mautic": {
"type": "package",
"package": {
"name": "mautic/api-library",
"version": "1.0.0",
"source": {
"url": "https://github.com/mautic/api-library",
"type": "git",
"reference": "325f0d9ec7ef191f6f8b3513b4ae5558beb9b724"
}
}
}
},
"require": {
...
"mautic/api-library": "1.0.0"
},
"autoload": {
...
"files": ["vendor/mautic/api-library/lib/Mautic/MauticApi.php"]
},
...
Then run composer update
and the Mautic API library will be added to your PHP app and PHP classes autoloaded.
If your project doesn't use Composer yet, you can either clone it from GitHub or download the ZIP package and copy the library folder to your project.
- Go to your project folder where you want to place Mautic API library to be. For example:
cd /var/www/html/myproject
- Run git clone to this folder
git clone [email protected]:mautic/api-library.git .
(the dot at the end means current folder)
- Download the library from https://github.com/mautic/api-library/archive/master.zip
- Extract the package to some temporary location.
- Copy the
/lib
folder to your project.
If API library files are at the right place in your project, autoload it's classes with:
require_once __DIR__ . '/lib/Mautic/MauticApi.php'; // change the path as your project requires it
To use API calls, your application has to be authorized in Mautic instance you want to connect with. Mautic supports OAuth1 and OAuth2. I'll focuse to OAuth1 since it doesn't require HTTPS. If your application has some kind of administration, you'll need to add 3 text inputs and an Authorization button there.
You can create specific authorization API credentials for each connected application. To do that, go to your Mautic administration and follow these steps:
- Go to Mautic Configuration / API Settings and set 'API enabled' to 'Yes', leave 'API mode' to 'OAuth1'. Save changes.
- At the right-hand side menu where Configuration is should appear the new menu item 'API Credentials'. Hit it.
- Create new credential. Fill in 'Name' (name of your app for example) and Callback URL (URL where your app will be listening responses from Mautic). Save credentials.
- Mautic should generate 'Consumer Key' and 'Consumer Secret' key.
If you don't want to hard-code authorization details, create form with text inputs: Mautic Base URL, Consumer Key and Consumer Secret with Save & Authorize button. This form should not be accessible for public.
Note: You can test authorization and API requests in build-in API Tester. You can find it in the /apitester directory of Mautic API Library.
If administrator of your app hits Save & Authorize button, this is how you can handle the request:
// @todo check if the request is sent from user with admin rights
// @todo check if Base URL, Consumer/Client Key and Consumer/Client secret are not empty
// @todo load this array from database / config file
$accessTokenData = array(
'accessToken' => '',
'accessTokenSecret' => '',
'accessTokenExpires' => ''
);
// @todo Sanitize this URL. Make sure it starts with http/https and doesn't end with '/'
$mauticBaseUrl = $_POST['mauticBaseUrl'];
$settings = array(
'clientKey' => $_POST['clientKey'],
'clientSecret' => $_POST['clientSecret'],
'callback' => 'http://yourapp.com', // @todo Change this to your app callback. It should be the same as you entered when you were creating Mautic API credentials.
'accessTokenUrl' => $mauticBaseUrl . '/oauth/v1/access_token',
'authorizationUrl' => $mauticBaseUrl . '/oauth/v1/authorize',
'requestTokenUrl' => $mauticBaseUrl . '/oauth/v1/request_token'
);
if (!empty($accessTokenData['accessToken']) && !empty($accessTokenData['accessTokenSecret'])) {
$settings['accessToken'] = $accessTokenData['accessToken'] ;
$settings['accessTokenSecret'] = $accessTokenData['accessTokenSecret'];
$settings['accessTokenExpires'] = $accessTokenData['accessTokenExpires'];
}
$auth = \Mautic\Auth\ApiAuth::initiate($settings);
if ($auth->validateAccessToken()) {
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
// @todo Save $accessTokenData
// @todo Display success authorization message
} else {
// @todo Display info message that this app is already authorized.
}
}
The workflow is this:
- Admin user fills in the Access Keys and Mautic Base URL to the form.
- If
$accessTokenData
aren't known yet,$auth->validateAccessToken()
will redirect user to Mautic where he can authorize the app. - After user confirms authorization, Mautic will redirect him back (to the Callback URL) to your app.
$auth->getAccessTokenData()
will return $accessTokenData which you have to save.
Live examples of authorization can be found at:
Finally the fun part. I suppose the most used API call will be to create new lead in Mautic. For example if a visitor submits a form in your app. Here is an example:
($auth
and $mauticBaseUrl
are the same as from the code above. It would be clever to add those to methods to have them accessible from different places)
$leadApi = \Mautic\MauticApi::getContext(
"leads",
$auth,
$mauticBaseUrl . '/api/'
);
$lead = $leadApi->create(array(
'ipAddress' => $_SERVER['REMOTE_ADDR'],
'firstname' => $formData['firstname'],
'lastname' => $formData['lastname'],
'email' => $formData['email'],
));
There is much more you can do. All is described at API Library Documentation
Thanks for the good information.