Mautic API Library

repository·main·Indexed 41 days ago

https://github.com/mautic/api-library

A PHP client for simplifying interactions with the Mautic API. It provides structured context objects for Mautic resources and supports authentication flows including OAuth 1.0a, OAuth 2, and Basic Authentication. The library is PSR-18 compliant and allows for managing contacts, campaigns, and campaign events through methods for creating, retrieving, editing, and deleting items, as well as performing batch operations.

Tokens
10.7K
Snippets
38
Records
53
Agent score
51%

What's inside Mautic API Library

  1. Configure Mautic for API Access

    main

    Before using the library, you must enable the API in your Mautic instance:

    1. Go to Settings > Configuration and enable Mautic's API.
    2. If using Basic Authentication, ensure it is enabled in the same settings.
    3. Go to Settings > API Credentials and create a new client.
    4. Enter your application's callback/redirect URI.
    5. Copy the generated Client ID and Client Secret for use in your application.
  2. Obtain an access token via OAuth

    main

    Mautic supports OAuth 1.0a and OAuth 2. Use the ApiAuth class to manage the authorization flow. You can pass existing tokens into the $settings array to prevent unnecessary reauthorization.

    <?php
    
    include __DIR__ . '/vendor/autoload.php';  
    
    use Mautic\Auth\ApiAuth;
    
    session_start();
    
    $settings = [
        'baseUrl'          => '',       // Base URL of the Mautic instance
        'version'          => 'OAuth2', // 'OAuth2' (default) or 'OAuth1a'
        'clientKey'        => '',       // Client/Consumer key from Mautic
        'clientSecret'     => '',       // Client/Consumer secret from Mautic
        'callback'         => '',       // Redirect URI/Callback URI
    ];
    
    // Optional: Pass existing tokens to avoid reauthorization
    // $settings['accessToken']        = $accessToken;
    // $settings['accessTokenSecret']  = $accessTokenSecret; // for OAuth1.0a
    // $settings['accessTokenExpires'] = $accessTokenExpires; // UNIX timestamp
    // $settings['refreshToken']       = $refreshToken;
    
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings);
    
    try {
        if ($auth->validateAccessToken()) {
            if ($auth->accessTokenUpdated()) {
                $accessTokenData = $auth->getAccessTokenData();
                // $accessTokenData contains: 
                // OAuth1.0a: access_token, access_token_secret, expires
                // OAuth2: access_token, expires, token_type, refresh_token
            }
        }
    } catch (Exception $e) {
        // Handle error
    }
  3. Configure HTTP client timeout in version 4.0

    main

    In version 4.0.0, the setCurlTimeout() method on the authentication object has been removed. To set a request timeout, you must now configure it directly on your PSR-18 compliant HTTP client during instantiation.

    If you are using Guzzle 7, pass the timeout option into the client constructor.

    $httpClient = new \GuzzleHttp\Client([
        'timeout'  => 10,
    ]);
    $settings = [
        // ...
    ];
    
    $initAuth = new \Mautic\Auth\ApiAuth($httpClient);
    $auth = $initAuth->newAuth($settings);
  4. Install the Mautic API Library

    main

    Install the library using Composer. You must also install a PSR-18 compliant HTTP client (such as Guzzle) to ensure the library can make network requests.

    composer require mautic/api-library guzzlehttp/guzzle:^7.3
  5. Manage Contacts via the Contacts API

    main

    The Mautic\Api\Contacts class provides methods to interact with contact data in Mautic. You can retrieve contact lists, manage contact points (scoring), handle 'Do Not Contact' (DNC) settings, and manage UTM tags.

    Common tasks include:

    • Retrieving lists of owners, custom fields, or segments.
    • Fetching activity, notes, devices, or campaigns associated with a specific contact.
    • Modifying contact scoring (points and point groups).
    • Managing DNC status and UTM tags.
  6. Use Basic Authentication with the Mautic API

    main

    To use Basic Authentication, you must first initialize an authentication object using Mautic\Auth\ApiAuth with a settings array specifying 'AuthMethod' => 'BasicAuth'. This authentication object is then passed to the newApi method when creating a specific API context (e.g., 'contacts').

    Settings Array Keys:

    • AuthMethod: Must be 'BasicAuth' (or 'OAuth').
    • userName: The username/login identifier for the Mautic user.
    • password: The password for the user.
    • apiUrl: The base URL of your Mautic instance.

    Error Handling: If credentials are incorrect or the wrong authentication method is used, the API will return an error response in the following format:

    {
      "errors": [
        {
          "code": 403,
          "message": "access_denied: OAuth2 authentication required"
        }
      ]
    }
    use Mautic\Auth\ApiAuth;
    use Mautic\MauticApi;
    
    // 1. Define settings
    $settings = [
        'AuthMethod' => 'BasicAuth',
        'userName'   => 'your_username',
        'password'   => 'your_password',
        'apiUrl'     => 'https://your-mautic-url.com/api',
    ];
    
    // 2. Initialize the auth object
    $initAuth = new ApiAuth();
    $auth = $initAuth->newAuth($settings, $settings['AuthMethod']);
    
    // 3. Create the API context and use it
    $api = new MauticApi();
    $contactApi = $api->newApi('contacts', $auth, $settings['apiUrl']);
    
    // 4. Perform requests
    $results = $contactApi->getList();
  7. Handle API errors

    main

    API responses may contain an errors key. Always check for this key to handle issues like authentication failures or invalid data.

    <?php
    
    $response = $contactApi->delete($contactId);
    
    if (isset($response['errors'])) {
        foreach ($response['errors'] as $error) {
            echo $error['code'] . ": " . $error['message'];
        }
    }
    
    /* 
    Example error structure:
    [
        'errors' => [
            [
                'code'    => 403,
                'message' => 'access_denied: OAuth2 authentication required',
                'type'    => 'access_denied',
            ],
        ],
    ]
    */
  8. Use Basic Authentication

    main

    For simpler setups, you can use Basic Authentication by providing a userName and password in the settings and specifying 'BasicAuth' as the second argument to newAuth().

    <?php
    
    include __DIR__ . '/vendor/autoload.php';  
    
    use Mautic\Auth\ApiAuth;
    
    session_start();
    
    $settings = [
        'userName'   => '',             // Mautic username
        'password'   => '',             // Mautic password
    ];
    
    $initAuth = new ApiAuth();
    $auth     = $initAuth->newAuth($settings, 'BasicAuth');
  9. Configure an HTTP Client for Mautic API

    main

    The library is decoupled from specific HTTP implementations via the PSR-18 standard. You can provide your own client (e.g., Guzzle) to the ApiAuth constructor.

    <?php
    
    include __DIR__ . '/vendor/autoload.php';  
    
    use GuzzleHttp\Client;
    use Mautic\Auth\ApiAuth;
    
    // Initiate an HTTP Client
    $httpClient = new Client([
        'timeout'  => 10,
    ]);
    
    // Initiate the auth object
    $initAuth = new ApiAuth($httpClient);
    // ...
  10. Create an API context object

    main

    To interact with specific Mautic resources (like Contacts, Forms, or Pages), create a context object using MauticApi::newApi().

    <?php
    
    use Mautic\MauticApi;
    
    $api        = new MauticApi();
    // $auth is the object obtained from ApiAuth
    // $apiUrl is the base URL of your Mautic server (e.g., http://my-mautic-server.com/api/)
    $contactApi = $api->newApi('contacts', $auth, $apiUrl);
  11. Create, Edit, and Delete items

    main

    Context objects provide methods to manage resource lifecycles:

    • create($data): Creates a new item.
    • edit($id, $data, $createIfMissing = false): Updates an existing item. If the third parameter is true, it will create the item if the ID is not found.
    • delete($id): Removes an item.
    <?php
    
    // Create
    $fields = $contactApi->getFieldList();
    $data = [];
    foreach ($fields as $field) {
        $data[$field['alias']] = $_POST[$field['alias']];
    }
    $data['ipAddress'] = $ipAddress;
    $response = $contactApi->create($data);
    $contact  = $response[$contactApi->itemName()];
    
    // Edit
    $updatedData = ['firstname' => 'Updated Name'];
    $response = $contactApi->edit($contactId, $updatedData);
    // To create if missing:
    // $response = $contactApi->edit($contactId, $updatedData, true);
    
    // Delete
    $response = $contactApi->delete($contactId);