Skip to content

Instantly share code, notes, and snippets.

@escopecz
Last active June 29, 2020 00:17
Show Gist options
  • Save escopecz/931ad49f741b6af75cb6 to your computer and use it in GitHub Desktop.
Save escopecz/931ad49f741b6af75cb6 to your computer and use it in GitHub Desktop.
Mautic API integration tutorial for PHP

Mautic has API to interact with other systems. There is PHP API library for faster integration to PHP projects.

Install Mautic API library with Composer

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.

Install Mautic API library other way

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.

Install by git clone

  1. Go to your project folder where you want to place Mautic API library to be. For example:
 cd /var/www/html/myproject
  1. Run git clone to this folder
git clone [email protected]:mautic/api-library.git .

(the dot at the end means current folder)

Copy from ZIP package

  1. Download the library from https://github.com/mautic/api-library/archive/master.zip
  2. Extract the package to some temporary location.
  3. Copy the /lib folder to your project.

Autoload PHP classes

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

Authorization of your Mautic API application

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.

Get Authorization keys in Mautic

You can create specific authorization API credentials for each connected application. To do that, go to your Mautic administration and follow these steps:

  1. Go to Mautic Configuration / API Settings and set 'API enabled' to 'Yes', leave 'API mode' to 'OAuth1'. Save changes.
  2. At the right-hand side menu where Configuration is should appear the new menu item 'API Credentials'. Hit it.
  3. 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.
  4. Mautic should generate 'Consumer Key' and 'Consumer Secret' key.

Create Authorization form

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.

Handle Authorization request

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:

  1. Admin user fills in the Access Keys and Mautic Base URL to the form.
  2. If $accessTokenData aren't known yet, $auth->validateAccessToken() will redirect user to Mautic where he can authorize the app.
  3. After user confirms authorization, Mautic will redirect him back (to the Callback URL) to your app.
  4. $auth->getAccessTokenData() will return $accessTokenData which you have to save.

Live examples of authorization can be found at:

API Calls

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

@urvishapatel17
Copy link

how to use refresh token for generating new access token?

@BillPackard
Copy link

How to install step by step? Where need to write the credentials?

@ChelseaHenderson123
Copy link

ChelseaHenderson123 commented Apr 17, 2020

Useful information that will come in handy when doing coursework with Mautic API integration for PHP. I think I will develop the project myself. But I will ask for help to design a descriptive part on a website https://writix.co.uk/thesis-writing-help with a specialized profile. With the help of this site you can order help in writing a thesis for a particular project. What about the article, I think the library will install Mautic API using Composer. If this method does not work, then I will download a ZIP package and copy the library folder in my project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment