• Stars
    star
    168
  • Rank 217,617 (Top 5 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Mautic API Library

codecov Latest Stable Version Total Downloads Latest Unstable Version License

All Contributors

Using the Mautic API Library

Requirements

  • PHP 8.0 or newer
  • cURL support

Installing the API Library

You can install the API Library with the following command:

composer require mautic/api-library

Mautic Setup

The API must be enabled in Mautic. Within Mautic, go to the Configuration page (located in the Settings menu) and under API Settings enable Mautic's API. If you intend to use Basic Authentication, ensure you enable it. You can also choose which OAuth protocol to use here. After saving the configuration, go to the API Credentials page (located in the Settings menu) and create a new client. Enter the callback/redirect URI that the request will be sent from. Click Apply, then copy the Client ID and Client Secret to the application that will be using the API.

Authorization

Obtaining an access token

The first step is to obtain authorization. Mautic supports OAuth 1.0a and OAuth 2, however it is up to the administrator to decide which is enabled. Thus it is best to have a configuration option within your project for the administrator to choose what method should be used by your code.

<?php

// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';  

use Mautic\Auth\ApiAuth;

session_start();

$publicKey = '';
$secretKey = '';
$callback  = '';

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = [
    'baseUrl'          => '',       // Base URL of the Mautic instance
    'version'          => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
    'clientKey'        => '',       // Client/Consumer key from Mautic
    'clientSecret'     => '',       // Client/Consumer secret key from Mautic
    'callback'         => '',       // Redirect URI/Callback URI for this script
];

/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken']        = $accessToken;
$settings['accessTokenSecret']  = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken']       = $refreshToken;
*/

// Initiate the auth object
$initAuth = new ApiAuth();
$auth     = $initAuth->newAuth($settings);

// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization

// If the access token is expired, and a refresh token is set above, then a new access token will be requested

try {
    if ($auth->validateAccessToken()) {

        // Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
        // refresh token

        // $accessTokenData will have the following keys:
        // For OAuth1.0a: access_token, access_token_secret, expires
        // For OAuth2: access_token, expires, token_type, refresh_token

        if ($auth->accessTokenUpdated()) {
            $accessTokenData = $auth->getAccessTokenData();

            //store access token data however you want
        }
    }
} catch (Exception $e) {
    // Do Error handling
}

Using Basic Authentication Instead

Instead of messing around with OAuth, you may simply elect to use BasicAuth instead.

Here is the BasicAuth version of the code above.

<?php

// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';  

use Mautic\Auth\ApiAuth;

session_start();

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = [
    'userName'   => '',             // Create a new user       
    'password'   => '',             // Make it a secure password
];

// Initiate the auth object specifying to use BasicAuth
$initAuth = new ApiAuth();
$auth     = $initAuth->newAuth($settings, 'BasicAuth');

// Nothing else to do ... It's ready to use.
// Just pass the auth object to the API context you are creating.

Note: If the credentials are incorrect an error response will be returned.

 [
    'errors' => [
        [
            'code'    => 403,
            'message' => 'access_denied: OAuth2 authentication required',
            'type'    => 'access_denied',
        ],
    ],
 ];

Note: You can also specify a CURLOPT_TIMEOUT in the request (default is set to wait indefinitely):

$initAuth = new ApiAuth();
$auth     = $initAuth->newAuth($settings, 'BasicAuth');
$timeout  = 10;

$auth->setCurlTimeout($timeout);

API Requests

Now that you have an access token and the auth object, you can make API requests. The API is broken down into contexts.

Get a context object

<?php

use Mautic\MauticApi;

// Create an api context by passing in the desired context (Contacts, Forms, Pages, etc), the $auth object from above
// and the base URL to the Mautic server (i.e. http://my-mautic-server.com/api/)

$api        = new MauticApi();
$contactApi = $api->newApi('contacts', $auth, $apiUrl);

Supported contexts are currently:

See the developer documentation.

Retrieving items

All of the above contexts support the following functions for retrieving items:

<?php

$response = $contactApi->get($id);
$contact  = $response[$contactApi->itemName()];

// getList accepts optional parameters for filtering, limiting, and ordering
$response      = $contactApi->getList($filter, $start, $limit, $orderBy, $orderByDir);
$totalContacts = $response['total'];
$contact       = $response[$contactApi->listName()];

Creating an item

<?php

$fields = $contactApi->getFieldList();

$data = array();

foreach ($fields as $field) {
    $data[$field['alias']] = $_POST[$field['alias']];
}

// Set the IP address the contact originated from if it is different than that of the server making the request
$data['ipAddress'] = $ipAddress;

// Create the contact
$response = $contactApi->create($data);
$contact  = $response[$contactApi->itemName()];

Editing an item

<?php

$updatedData = [
    'firstname' => 'Updated Name'
];

$response = $contactApi->edit($contactId, $updatedData);
$contact  = $response[$contactApi->itemName()];

// If you want to create a new contact in the case that $contactId no longer exists
// $response will be populated with the new contact item
$response = $contactApi->edit($contactId, $updatedData, true);
$contact  = $response[$contactApi->itemName()];

Deleting an item

<?php

$response = $contactApi->delete($contactId);
$contact  = $response[$contactApi->itemName()];

Error handling

<?php

// $response returned by an API call should be checked for errors
$response = $contactApi->delete($contactId);

if (isset($response['errors'])) {
    foreach ($response['errors'] as $error) {
        echo $error['code'] . ": " . $error['message'];
    }
}

Contributing

Setting up your environment (automatically)

In order to get started quickly, we recommend that you use DDEV which sets things up automatically for you. It clones https://github.com/mautic/mautic, sets up a local instance for you, and connects the API library tests to that instance.

To get started, run ddev start! Our first-run experience will guide you through the setup.

Setting up your environment (manually)

If you want to set up your local environment manually, ensure that you copy /tests/local.config.php.dist to /tests/local.config.php, and fill in the required settings. We recommend using the Basic Authentication method to get up and running quickly.

Unit tests

Configure the unit tests config before running the unit tests. The tests fire real API requests to a Mautic instance.

  1. Ensure you have set up your local environment using the steps above.
  2. Run composer test to run the tests.

Modify this command to run a specific test: composer test -- --filter testCreateGetAndDelete tests/Api/NotesTest.php

Modify this command to run all tests in one class: composer test -- --filter test tests/Api/NotesTest.php

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Zdeno Kuzmany
Zdeno Kuzmany

πŸ’»
dlopez-akalam
dlopez-akalam

πŸ’»
mollux
mollux

πŸ’»
Martina  Scholz
Martina Scholz

πŸ’»
John Linhart
John Linhart

πŸ‘€
Marinus van Velzen
Marinus van Velzen

πŸ’»
Pierre Ammeloot
Pierre Ammeloot

πŸ““

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

mautic

Mautic: Open Source Marketing Automation Software.
PHP
6,490
star
2

docker-mautic

Docker Image for Mautic
Dockerfile
327
star
3

mautic-wordpress

Wordpress Plugin
PHP
118
star
4

documentation

Mautic End User Documentation
JavaScript
62
star
5

plugin-grapesjs-builder

GrapesJS HTML and MJML integration for Mautic
PHP
48
star
6

mautic-zapier

Zapier JS app communicating with Mautic
JavaScript
25
star
7

mautic-grav

Mautic integration into Grav CMS
PHP
23
star
8

mautic-typo3

Add-on TYPO3 extension that enhances the "EXT:marketing_automation" TYPO3 extension by connecting it to the Mautic Marketing Automation platform: Determine "Persona" from Mautic segments. Also provides additional services e.g. language synchronisation between Mautic and TYPO3.
PHP
21
star
9

mautic-documentation

User documentation for the Mautic project
JavaScript
19
star
10

MauticGeneratorBundle

Generator for Mautic bundles
PHP
16
star
11

mautic-joomla

Joomla Plugin
PHP
15
star
12

composer-plugin

A composer plugin that mautic plugin and theme developers can use to distribute their code.
PHP
14
star
13

plugin-helloworld

Hello World plugin built on the Integration framework
PHP
12
star
14

mautic-saelos-bundle

Bi-Directional Saelos integration plugin for Mautic
PHP
11
star
15

grapesjs-preset-mautic

GrapesJS preset configuration for the Mautic editor
JavaScript
11
star
16

mautic-drupal

Drupal plugin
8
star
17

plugin-crm

PHP
7
star
18

mautic-concrete5

Concrete5 Plugin
PHP
7
star
19

mautic-spi

Mautic Single Page Installer
PHP
7
star
20

mautic-helper-chrome-extension

JavaScript
7
star
21

mautic-community-handbook

A handbook for all things related to the Mautic Community
JavaScript
7
star
22

user-documentation

6
star
23

mautic-tester

Mautic Pull Request Tester
PHP
5
star
24

plugin-tagmanager

PHP
5
star
25

mautic-community-knowledgebase

A Knowledgebase for the Mautic community
5
star
26

website

The Mautic Website
5
star
27

language-packs

Public store of prepared Mautic language packs. Rebuilt every day from Transifex.
5
star
28

core-lib

PHP
5
star
29

recommended-project

This project template provides a starter kit for managing your Mautic dependencies with Composer.
4
star
30

core-composer-scaffold

PHP
4
star
31

plugin-focus

PHP
4
star
32

developer-documentation-new

New developer documentation on Read the Docs
4
star
33

theme-skyline

Twig
3
star
34

theme-sunday

Twig
3
star
35

theme-fresh-wide

CSS
3
star
36

plugin-clearbit

PHP
3
star
37

theme-aurora

Twig
3
star
38

theme-paprika

Twig
3
star
39

plugin-cloudstorage

PHP
3
star
40

theme-coffee

Twig
3
star
41

theme-sparse

Twig
3
star
42

core-project-message

PHP
3
star
43

theme-oxygen

Twig
3
star
44

plugin-fullcontact

PHP
3
star
45

theme-brienz

Twig
3
star
46

plugin-gmail

PHP
3
star
47

theme-vibrant

Twig
3
star
48

theme-mauve

Twig
3
star
49

theme-confirmme

Twig
3
star
50

theme-neopolitan

Twig
3
star
51

theme-nature

Twig
3
star
52

plugin-social

PHP
3
star
53

plugin-zapier

PHP
3
star
54

theme-cards

Twig
3
star
55

plugin-citrix

PHP
3
star
56

plugin-outlook

PHP
3
star
57

theme-fresh-left

CSS
3
star
58

theme-goldstar

Twig
3
star
59

theme-fresh-fixed

CSS
3
star
60

statsapp

Powers the Stats App and the Mautic 3 migration dashboard.
PHP
3
star
61

theme-trulypersonal

Truly Personal theme for Mautic
Twig
3
star
62

plugin-emailmarketing

PHP
3
star
63

grav-plugin-login-oauth2-auth0

PHP
3
star
64

theme-fresh-center

CSS
3
star
65

theme-blank

Twig
3
star
66

mautic.org-website

This repository relates to the mautic.org website. We accept PRs here to make changes, and issues to flag up problems that you might find or changes that are needed.
PHP
2
star
67

marketplace-allowlist

Repo that keeps track of the allowed plugins in the Mautic Marketplace.
2
star
68

Community-Portal

Mautic's community governance portal
HTML
2
star
69

mautic-gmail-plugin

1
star
70

Gsod

1
star
71

plugin-messagebird

MessageBird SMS Integration for >= Mautic 2.13
PHP
1
star
72

plugin-example

An example plugin that does nothing
PHP
1
star