Coder Social home page Coder Social logo

api-library's Introduction

codecov Latest Stable Version Total Downloads Latest Unstable Version License

All Contributors

Using the Mautic API Library

Requirements

  • PHP 8.0 or newer

Installing the API Library

You can install the API Library with the following command:

composer require mautic/api-library

N.B. Make sure you have installed a PSR-18 HTTP Client before you install this package or install one at the same time e.g. composer require mautic/api-library guzzlehttp/guzzle:^7.3.

HTTP Client

We are decoupled from any HTTP messaging client with the help of PSR-18 HTTP Client. This requires an extra package providing psr/http-client-implementation. To use Guzzle 7, for example, simply require guzzlehttp/guzzle:

composer require guzzlehttp/guzzle:^7.3

The installed HTTP Client is auto-discovered using php-http/discovery, but you can also provide your own HTTP Client if you like.

<?php

// Bootup the Composer autoloader
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);
$auth     = $initAuth->newAuth($settings);
// etc.

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',
        ],
    ],
 ];

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!

api-library's People

Contributors

alanhartless avatar allcontributors[bot] avatar dench0 avatar dennisameling avatar dongilbert avatar escopecz avatar fcojavierdomenech avatar hideokamoto avatar ichhabrecht avatar isleshocky77 avatar jazo avatar jonnitto avatar kerleba avatar kuzmany avatar ladysolveig avatar lan-laurene avatar mabumusa1 avatar markll avatar mbabker avatar mollux avatar moongazer avatar npracht avatar r3volut1oner avatar rcheesley avatar rocksheep avatar scottshipman avatar virlatinus avatar wgxo avatar wise-gorilla avatar woeler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-library's Issues

Mautic - Requested URL not found - Fix

Hey,

just wanted to report something. I think it should be added to the README file.


Here's what I found after trying everything, what is possible for a week:

Whenever I made API requests I got the "Requested URL not found" error all the time.
It didn't matter what request has been done.

But all the time it was the same error (/api/contacts/new can be any other endpoint):

error: {message: "Requested URL not found: /api/contacts/new", code: 404}


Here's the super strange solution, that I have found:

In | Configuration -> System Settings -> Path to the cache directory | you HAVO TO change the Path to the cache directory to a path outside of the Mautic installation location.


Could someone explain me, why you have to do that?

Best regards,

FlexMarkets

The response returned is in an unexpected format.

Did something change in the api that hasn't been updated in the library ? because i do encounter a weird error that hasn't been there before 1.4

UnexpectedResponseFormatException in OAuth.php line 789:
The response returned is in an unexpected format.

Form embed, translate error messages

Embedding a Mautic form with the API works but i need to translate the error messages in the url.
At the moment Mautic returns me to
URL?mauticError=Errors%3A<br%20%2F>

  1. %27Email%27%20is%20required.<%2Fli><%2Fol>#keep_me_po

    How can i translate Email is required?
    Is it possible to alter the message, remove the HTML in de url?


    Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Problem after submitting form

Steps to reproduce error: Notice: Undefined index: state in Mautic\Auth\OAuth->validateAccessToken() (line 443 of Auth/OAuth.php).

  • Created a new ApiAuth and succeeded in login. OK
  • stored the access_token date
  • asked form html structure and printed out in drupal website. OK
  • Submitting form, values are saved in mautic. OK
  • Redirect to website, Created a new ApiAuth with the access tokens and then i receive the error
    Notice: Undefined index: state in Mautic\Auth\OAuth->validateAccessToken() (line 443 of Auth/OAuth.php).
    I am not autorized anymore on mautic, receiving 403 on same call to the form.

When i remove the GETTERS from the url (?state=8d6767fb140182c6a6354f1510d66508&code=YjU1MzM2YjJiZTRmNjVmMTRmYjVjOGIyMjAzYzI1ODRjMDYzZWZhNjdiMDgxM2NkNjIzZDE3Nzc3MzhhYjA5OA) everything works back (access tokens are changed and the process starts again.)

the $_SESSION['oauth']['state'] is filled in the first time but after submitting the form the session oauth is emtpy

Mautic is latest version 2.1.1 and using composer package https://packagist.org/packages/mautic/api-library#dev-master

Requested URL not found: /api/segments/3/contact/add/', 'code' => 404

I get the following error trying to add a contact to a segment (or any other action for that matter):
Requested URL not found: /api/segments/3/contact/add/', 'code' => 404

My env('MAUTIC_BASE_URL') is the URL to my mautic installation without /api/.

Code:

            $settings = [
                'baseUrl' => env('MAUTIC_BASE_URL'),
                'version' => 'OAuth2',
                'clientKey' => env('MAUTIC_CLIENT_KEY'),
                'clientSecret' => env('MAUTIC_CLIENT_SECRET'),
                'callback' => env('MAUTIC_CALLBACK_URL'),
                'accessToken' => env('MAUTIC_ACCESS_TOKEN'),
                'refreshToken' => env('MAUTIC_REFRESH_TOKEN')
            ];
            $auth = new ApiAuth();
            $auth = $auth->newAuth($settings);
            if ($auth->validateAccessToken()) {
                if ($auth->accessTokenUpdated()) {
                    $accessTokenData = $auth->getAccessTokenData();
                }
            }
            $mautic = new MauticApi;
            $listApi = $mautic->newApi("segments", $auth, env('MAUTIC_BASE_URL'));
            $result =  $auth['listApi']->addContact($list_id, $contact_id);
            return $result['error'];

[Mautic 2.5.1] Create Segment

Hi,

When trying to call the endpoint for creating a Segment, I got a 504 response.
Here is the JSON request:

{
    "isPublished": false,
    "name": "REST API Mautic test",
    "alias": "rest-api-mautic-test",
    "description": "test GGAR",
    "isGlobal": true
}

and I am calling this endpoint: https://< mautic server >/api/segments/new

From calling other endpoints with the same credentials, I'm pretty confident that the problem does not come from that.

Get Only Identified Contacts?

Is it possible to use the API to get only contacts that have been identified? Why does the API get every IP address that has visited a site by default? I can't imagine most people want this when getting contacts.

Also, what does this option mean? "publishedOnly - Only return currently published entities."

And this? "minimal - Return only array of entities without additional lists in it."

Nothing seems to change when I set these to "true."

Thanks

Not able to connect with Mautic API

Hi,

I am trying to connect Mautic API through this pluging, Download this plugin and install composer. Then create a new file in apitester (base.php).

base.php (source code):

`

     include '../vendor/autoload.php';
 require_once '../lib/MauticApi.php';
 use Mautic\Auth\ApiAuth;
 use Mautic\MauticApi;
     $apiUrl = "http://localhost/mautic/index.php";

 $settings = array(
     'AuthMethod'       => 'BasicAuth', 
     'userName'         => 'admin',
     'password'         => 'Admin123!',        
     'apiUrl'           => 'http://localhost/mautic/index.php',         
 );


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

	if ($auth) {
		
		$api = new MauticApi();
		$contactApi = $api->newApi('contacts', $auth, $apiUrl);
		
		// Get Contact list
		$results = $contactApi->getList();
		var_dump($results);
	} else {
		echo "Something went wrong!";
	}
} catch (Exception $e) {
	echo "Mautic not connected!";	
}`

But this one always throw an error like:

'errors' =>
array (size=1)
0 =>
array (size=3)
'message' => string 'Requested URL not found: /mautic/index.php/api/contacts?orderByDir=ASC' (length=70)
'code' => int 404
'type' => null
'error' =>
array (size=2)
'message' => string 'Requested URL not found: /mautic/index.php/api/contacts?orderByDir=ASC (error is deprecated as of 2.6.0 and will be removed in 3.0. Use the errors array instead.)' (length=166)
'code' => int 404

Changes to AuthInterface break custom Auth Providers with Non Auth related changes

So I made a comment when this was proposed originally, but deleted because it may of be mis-construed.

However, I do not understand why the proposed changes were made! None of the new methods have anything to do with Authentication and the one method that is required and potentially should be added to the interface is missing. e.g. validateAccessToken().

WooCommerce and Mautic integration plugin - problem with customer tracking

Hi guys,

I am developing an integration between woocommerce and Mautic. This integration will create new contacts when a customer place an order, as well as sync previous woocommerce customers to Mautic. This plugin also allows to set product name, product SKU and order status as tags.

Everything is working so far except for tracking. Meaning, web activity of contacts are not being detected. This plugin also sends the contact IP, which I though it would enable precious web tracking (by merging the previous collected tracking from the IP to the newly created contact). However, this is not the case.

I checked and I realized that the unidentified and identified contacts have the same IP ID, then the question is does the system not automatically merge these two? When I send the contact from WooCommerce through the API, do I need to check if the IP already exist, and if it does use that unidentified contact ID to populate the contact fields?

Endpoint request - Get leads from a list ID

Need

Via API to get all the contacts from a list via list ID.
Something like « Get leads from a list ID »

Recommandation

Option 1

  1. API Call - Get leads list of list ID X
  2. It returns lead IDs.

Option 2 (more complete)

  1. API Call - Get leads list of list ID X & all the lead fields you need.
  2. It returns le lead IDs + lead fields requested (email, firstname, etc.).

Can't allow access to app

Whenever I Accept/Deny access an app, a file named authorize downloads and I don't know what's wrong.

See the screenshot below:

image

Support authentication via CLI

I'm attempting to use the API to manage many contacts/segments in a more automated fashion from a PHP CLI script. However it appears as though the API with OAuth authentication isn't designed for this, as it wants to redirect the CLI script to a URI to login. Of course with no web browser attached this fails everytime.

Is this possible and if so, is there an example CLI script that can access the Mautic API by chance?

OAuth::makeRequest #L 746 - Problem in symfony 1.0.2

I've been implementing a script to get data from our private Mautic and found this little problem.

On OAuth::makeRequest #L 746

$options[CURLOPT_POSTFIELDS] = http_build_query($parameters);

While this works fine with the apitester, in symfony 1.0.2 the function http_build_query encodes the & as &amp; causing a failure in the request for a token.

I've solved it by modifying this line like this:

$options[CURLOPT_POSTFIELDS] = http_build_query($parameters, '', '&');

Is it possible to make a little modification to check if the http_build_queryactually builds the postfields correctly?

Cannot update lead

$leadApi = \Mautic\MauticApi::getContext(
"leads", $auth, $mauticBaseUrl . '/api/'
);

$filter = 'email:' . $updatedData['email'];
$leads = $leadApi->getList($filter);

if (!empty($leads)) {
$leadId = $leads['leads'][0]['id'];
if (!empty($leadId)) {
// If you want to create a new lead in the case that $leadId no longer exists
// $result will be populated with the new lead item
$result = $leadApi->edit($leadId, $updatedData);
} else {
echo 'No leadId';
}
} else {
echo 'New lead';
$result = $leadApi->create($updatedData);
}

I tested with an existing email and the mautic server response with the leadID. But when I try to update nothing happens.

deprecated: ApiAuth::initiate & MauticApi::getContext

I see that ApiAuth::initiate & MauticApi::getContext were both deprecated and replaced with non-static methods for testing purposes. Should users of the API continue to use the static methods or switch to the non-static methods. If the later, then maybe add note on what should be used.

Authentication with Oauth1a: Incorrect access token parameters returned: Array

I change the mautic api configuration to Oauth1, created new key and configure my callbacks.

I'm think that the problem is with mautic app, because it generate only the client key but not secret key

The errors occours when the library makes the request on
https://safiri.mautic.com/oauth/v1/request_token

Array
(
    [error] => Array
        (
            [message] => signature_invalid
            [code] => 0
        )

    [allydeEmailLimits] => Array
        (
            [hourly] => Array
                (
                    [sent] => 0
                    [limit] => 50
                    [rate] => 0
                    [remaining] => 50
                )

            [hourlyTooltip] => <span class='email-sent'>0</span> out of <span class='email-limit'>50</span> emails sent this hour with <span class='email-remaining'>50</span> remaining.
            [monthly] => Array
                (
                    [sent] => 0
                    [limit] => 12000
                    [rate] => 0
                    [remaining] => 12000
                )

            [monthlyTooltip] => <span class='email-sent'>0</span> out of <span class='email-limit'>12000</span> emails sent this month with <span class='email-remaining'>12000</span> remaining.
        )

)

Bug: OAuth1 API calls with complex data can fail with signature_invalid error

For OAuth1a API calls a Signature is calculated based on a normalized view of the data being sent in the request. see RFC.

If you attempt to send complex data the current algorithm for normalizing the SigningString has a bug which means your call can fail with a signature_invalid error.

What is Complex data?
Basically any array attached to a field whether it is a simple array or key/value array.

An example of a contact that will work.

$contact = [
    'email' => '[email protected]',
    'tags'   => ['aTag', 'zTag']
];

and one that will fail.

$contact = [
    'email' => '[email protected]',
    'tags'   => ['zTag', 'aTag']
];

Yes, just switching the order of the tags can break the compatibility of the API and the main Mautic app.

In essence, the problem exists because the API normalize function is recursive and begins by performing a ksort() on the parameters array. However as noted here under section 9.1.1 (1) If two or more parameters share the same name, they are sorted by their value. Unfortunately recursively using ksort() breaks this compatibility.

For the techos' compare normalizeParameters() used in the API to normalizeRequestParameters() used by Mautic. Also note that the Server version is not recursive and in general it looks like OAuth1a could not support 3 level deep arrays.

functions not found

If using example in README.md, $auth->validateAccessToken(), $auth->accessTokenUpdated(), and $auth->getAccessTokenData() will not be found for the ApiAuth object calling them.
The functions exist for the object returned from ApiAuth::newAuth(), so if setting $auth to that like $auth = $auth->newAuth($settings), the functions will exist.

REST api plans?

Hi, are there plans to make a REST API that can be queried from different languages? We want to create a plugin within our nodejs backend to query and update lead records from mautic.

Obtaining an Access Token

Am I missing something here? I used the example code in the readme file, but I'm never redirected to the app. I just get this error:

Fatal error: Call to undefined method Mautic\Auth\ApiAuth::validateAccessToken()

That's with this code:

<?php

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

use Mautic\Auth\ApiAuth;

$publicKey = '24gnw4fpxu3o8s4ws8ccsccwoso48ccw44s0c84s0owgscgk0w';
$secretKey = 'ky7juiwu3hcgks8coco0kcs8ocsss8o4oo40gokccw04cks0g';
$callback  = 'http://local.dev';

// ApiAuth::initiate will accept an array of OAuth settings
$settings = array(
    'baseUrl'          => 'https://mymauticinstallation.com',     
    'version'          => 'OAuth1a', 
    'clientKey'        => $publicKey,       
    'clientSecret'     => $secretKey,     
    'callback'         => $callback     
);


$auth = new ApiAuth();
$auth->newAuth($settings);

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

        if ($auth->accessTokenUpdated()) {
            $accessTokenData = $auth->getAccessTokenData();
            echo $accessTokenData;
        }
    }
} catch (Exception $e) {
    // Do Error handling
}

If I just remove the try/catch, I end up with a blank page.

Thanks

Bad Request is treated as a valid response

Trying to create a lead with invalid data (bad country in my case) leads to 400 Bad Request from Mautic and empty JSON object ({}) being returned. Yet the library still treats this as a valid response, because it looks at the JSON, which is valid, and does not check the headers and status code.

This behavior is partly also Mautic's fault, because there should be an error description aside from the non 2XX status code.

Provide changelog

As a developer that uses this library, it would be very nice to be able to read a changelog before I update the api version using 'composer update'

Stable release?

I'm kind of hesitant to use this package with a @dev version in production, since it indicates there might be code breaking changes. Any chance for a stable release?

Update of boolean Lead's fields

How can I set a boolean field to False?

I am trying many combinations but with no luck so far:
1.
$data = array('boolean_sample' => 0); //value in lead is still 1..
2.
$data = array('boolean_sample' => FALSE); //field is still set to 1 like above
3.
$data = array('boolean_sample' => 'FALSE'); //returns empty array as if nothing was updated

How should I do?

Segments class does not contain method getSegments

From the documentation:

To get all segments:

<?php
use Mautic\MauticApi;
use Mautic\Auth\ApiAuth;

// ...
$auth     = ApiAuth::initiate($settings);
$apiUrl   = "https://your-mautic.com"; 
$segmentApi = MauticApi::getContext("segments", $auth, $apiUrl);

//...
$segments = $segmentApi->getSegments();

However, if you look at Segments class, the file does not contain method getSegments()

The method is specified in Leads class as getLists()

So, correct way to get all segments is this:

<?php
use Mautic\MauticApi;
use Mautic\Auth\ApiAuth;

// ...
$auth     = ApiAuth::initiate($settings);
$apiUrl   = "https://your-mautic.com"; 
$segmentApi = MauticApi::getContext("leads", $auth, $apiUrl);
//...
$segments = $segmentApi->getLists();

See inside for working api example Mautic 2.8.0 with Laravel 5.4

I just spent 2 hours getting this to work.. was really banging my head.. it always seemed like it executed the callback BEFORE I had a chance to store the accessTokenData. Then finally it hit me.. the callback url has to execute the same code as what's executed before the callback is done. So essentially the code in the example needs to be run twice and on the 2nd run then you get a chance to store the accessTokenData

Anyway I suppose this is standard with oauth but it wasn't clear to me, and maybe I'm explaining it wrong. But in any case the code below works! There's lots of people that seem to be having trouble so I thought this would be helpful to post

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Requests;
use Cache;
use Mautic\Auth\ApiAuth;
use Mautic\MauticApi;

class MauticController extends Controller
{
    protected $settings = [
        'baseUrl' => 'https://mautic.omitted.com',
        'version' => 'OAuth2', // SET this when creating your API Credentials
        'clientKey' => 'omitted', // GET this from API Credentials
        'clientSecret' => 'omitted', // GET this from API Credentials
        'callback' => 'http://signup.omitted.dev/authorize' // SET this when creating your API Credentials
    ];

    private function getAuth()
    {
        session_start();

        if (Cache::has("mauticTokenData")) {
            $mauticTokenData = Cache::get("mauticTokenData");

            $this->settings['accessToken'] = $mauticTokenData['access_token'];
            $this->settings['accessTokenExpires'] = $mauticTokenData['expires'];
            $this->settings['refreshToken'] = $mauticTokenData['refresh_token'];
        }

        $initAuth = new ApiAuth();
        $auth = $initAuth->newAuth($this->settings);

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

                if ($auth->accessTokenUpdated()) {
                    Cache::put('mauticTokenData', $auth->getAccessTokenData(), 1440);
                }

                return $auth;
            }
        } catch (\Exception $e) {
            ddd($e);
        }
    }

    /**
     * @Get("/authorize"))
     */
    public function apiAuthorize()
    {
        $auth = $this->getAuth();

        $api = new MauticApi();

        $contactsApi = $api->newApi('contacts', $auth, $this->settings['baseUrl']);

        $response = $contactsApi->getList();

        if(isset($response['errors'])) {
            ddd($response['errors']);
        }

        $contactCount = count($response['contacts']);

        ddd("There are a total of {$contactCount} contacts!");
    }
}

Api.php should call setBaseUrl __construct

In api-library/lib/Api/Api.php line 53 should be changed from:
$this->baseUrl = $baseUrl;
to
$this->setBaseUrl($baseUrl);
for consistency. Otherwise the trailing slash isn't automatically added on the initial creation.

I already forked this project to include in a separate project that includes several changes that don't apply to this project, so if someone else could change this so that would be helpful.

Rest Api to register contact events

Hi,

I'm very new to mautic. I want to know about rest api's of Mautic. So, I have a website. If user logs into my website mean, I'll create one account in Mautic. However, I've successfully created the account using rest API. If the same user logs into my site I want to register some events associated with that contact.

Is there any possibility to do with Mautic Rest Api's?

Basic Authorization

Hello guys. I am looking for examples about how to use basic authorization on API.

I have tried:

$settings = array(
'baseUrl' => '', // Base URL of the Mautic instance
'version' => 'basic',
'clientKey' => 'HTTP username',
'clientSecret' => 'HTTP password',
'callback' => '' // Redirect URI/Callback URI for this script
);

Anyone could help me about how to use it correctly?

This form should not contain additional fields.

Hello,
I get the following error trying to add a contact, and i obtain this response
'code' => 400,
'message' => '#: Este formulario no debería contener campos adicionales.',

Has anyone had this problem?

The code has been working fine until yesterday. This is the code

public function createUser($user) {
    $data = array(
      'activation_date' => $user->getActivationDate(),
      'unsubscribe_reason' => $user->getUnsubscribeReason(),
      'receibe_information_event' => $user->getReceibeInformationEvent() == 1 ? "YES":"NO",
      'allow_publish_your_data' => $user->getAllowPublishYourData() == 1 ? "YES":"NO",
      'status_reason' => $user->getStatusReason(),
      'active' => $user->getActive(),
      'origen_del_lead' => $user->getLeadOrigin(),
      'guid'      => $user->getGuid(),
      'firstname' => $user->getName(),
      'lastname'  => $user->getFirt_surname(),
      'email'     => $user->getEmail(),
      'country'   => $user->getCountry(),
      'city'      => $user->getCity(),
      'sexo' => $user->getGender() == 'Male' ? "HOMBRE" : "MUJER",
      'sector' => $user->getSector(),
      'knowopentalent' => ($user->getKnowOpenTalent() === true ? 'YES' : 'NO'),
      'language' => $user->getLanguage(),
      'website' => $user->getWeb(),
      'accept_conditions' => $user->getAcceptLegal() == '1' ? "YES" : "NO",
      'receive_information' => $user->getReceiveInformation() == '1' ? "YES":"NO",

      'interests_movil_app' => (array_key_exists('1', $user->getInterests())) ? 'YES':'NO',
      'interestsbanking' => (array_key_exists('2', $user->getInterests())) ? 'YES':'NO',
      'interests_bigdata' => (array_key_exists('3', $user->getInterests())) ? 'YES':'NO',
      'interest_technological_de' => (array_key_exists('4', $user->getInterests())) ? 'YES':'NO',
      'interest_entrepreneurship' => (array_key_exists('5', $user->getInterests())) ? 'YES':'NO',
      'interests_innovation' => (array_key_exists('6', $user->getInterests())) ? 'YES':'NO',
    );

    // Hay que verificar si existe el usuario (es un update)
    $existUser = UserFactory::createUser($user->getUid());
    if($existUser) {
      $dateNow = new \Datetime('now');
      $data['modification_date'] = $dateNow->format('Y/m/d H:i');
      // comprobamos si es una baja
      if ($user->getStatusReason() == "NO") {
        $data['unsubscribe_date'] = $dateNow->format('Y/m/d H:i');
      }
      $contact = $this->contactApi->edit($user->getCrmId(), $data);
    } else {
      $dateNow = new \Datetime('now');
      $data['creation_date'] = $dateNow->format('Y/m/d H:i');
      $data['modification_date'] = $data['creation_date'];
      // Se añade el prefijo para diferenciar los
      // leads que son pruebas de los de prodrucción
      $data['firstname'] = ORIGIN_PREFIX.$data['firstname'];
      $contact = $this->contactApi->create($data);
    }
    if ($userObject = $this->checkResponse($contact)) {
      // Actualizamos drupal cache 
      if ((BBVA_CACHE) && ($cache = cache_get('user_' . $user->uid))) {
        $user->setImage(DrupalUser::getUserPicture($user));
        cache_set('user_' . $user->uid, $user, 'cache');
      }      
      return true;
    }
    return false;
  }

Getting error Invalid grant_type parameter or parameter missing

hi,

I have installed mautic in my server and trying to connect it with my website i installed api-library and API Tester but when i send the request i get this error.

Incorrect access token parameters returned: Invalid grant_type parameter or parameter missing

double-optin using the API

After reading mautic/mautic#46 and https://www.mautic.org/blog/integrator/creating-a-double-opt-in-email-campaign/, I wonder:

Can signup be emulated via an API call?

That would imply:

  • the signup form people submit is not Mautic-generated
  • the signup form people submit is initially posted to a local server which somehow proxify the signup request

The API call expected would:

  • put the contact in pending list if he does not exist already
  • do nothing if contact already exist
  • send him a confirmation email immediately

I saw that (undocumented) Email class which does not seem implemented yet but it still does not fit the need.
Am I overlooking some features?

Confused about $auth->accessTokenUpdated()

I'm a little confused regarding the OAuth authentication, specifically the call $auth->accessTokenUpdated(). It never seems to return true. As a result I have make a call to $auth->getAccessTokenData(); and store the results before the call to accessTokenUpdated. Am i missing something? Thanks

My sample code based on sample from https://github.com/mautic/api-library:


session_name("oauthtester");
session_start();

require dirname(__DIR__).'/vendor/autoload.php';
require 'settings.php';

use Mautic\Auth\ApiAuth;
use Mautic\MauticApi;

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

if (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) {
  $settings['accessToken'] = $_GET['oauth_token'];
  $settings['accessTokenSecret'] = $_GET['oauth_verifier'];
}

// Initiate the auth object
$auth = ApiAuth::initiate($settings);

if (isset($_SESSION['accessTokenData'])) { //todo read from more permanent
  $auth->setAccessTokenDetails(json_decode($_SESSION['accessTokenData'], true));
}

if ($auth->validateAccessToken()){
  $accessTokenData = $auth->getAccessTokenData();
  $_SESSION['accessTokenData'] = json_encode($accessTokenData); //todo save more permanently

  if ($auth->accessTokenUpdated()) {
    echo '333<br>';
    $accessTokenData = $auth->getAccessTokenData();

    //store access token data however you want

  }

  $leadApi = MauticApi::getContext("leads", $auth, $baseUrl .'/api/');
    $leads = $leadApi->getList();
  echo '$leads =' . print_r($leads, true);

Even if I make a call to $auth->getAccessTokenData(); and store the results before the call to accessTokenUpdated, I get token_rejected [code] => 401 when I call $leadApi->getList(). So I'm doing something wrong.

Mautic Is Not Receiving Mandrill's Spam Webhook

Even though Mandrill is refusing to send e-mails because it was marked as spam, Mautic is not marking the lead as Do Not Contact.

What happens is that Mautic keeps sending while Mandrill refuses it until i delete the lead manually.

Release a stable version

I've been using this API in production for automatically signing users up to the mailing list. With sudden deprecations and such, Mautic cannot be a viable option if the API keeps breaking.

Please release a stable version.

Requested URL not found - Add Contact to a Stage

I'm trying to add a contact to a stage, but it keeps returning 404 error.

Array
(
    [error] => Array
        (
            [message] => Requested URL not found: /automacao/api/stages/1/contact/9/add
            [code] => 404
        )

)

The documentation says that the url should be

/stages/SEGMENT_ID/contact/add/CONTACT_ID

But i get the same error when i try to set the url on this way.
The version i'm using is 2.6.

Form api discards given alias on forms and formfields

Hello all,

I'm trying to create forms where I set the alias in the post request, however Mautic keeps discarding them and simply adding a random string as alias. This looks like a bug to me. It is a problem when I try to edit an already existing form via the API because it will completely delete all the results and all the fields from the form and then recreate them instead of looking if the aliases match, as they will never match with this random string thing intervening somewhere.

Here is a simple request:

`$data = array(
    'name' => 'test',
    'alias' => 'testform',
    'formType' => 'standalone',
    'description' => 'API test',
    'fields' => array(
        array(
            'label' => 'field name',
            'alias' => 'myfield',
            'type' => 'text'
        )
    ),
    'actions' => array(
        array(
            'name' => 'action name',
            'description' => 'action desc',
            'type' => 'lead.pointschange',
            'properties' => array(
                'operator' => 'plus',
                'points' => 2
            )
        )
    )
);

$form = $formApi->create($data);`

The form is now created but the alias of my field is 'qmoyx'.

[Mautic 2.5.1] Points REST API

Although present in the Mautic REST API documentation, when trying to use the Points endpoint, I get a 200 HTTP status but containing the following:

{
  "error": {
    "message": "Requested URL not found: /api/contacts/14637/points/plus/10",
    "code": 404
  }
}

Here is the request : https://mautic server/api/contacts/14637/points/plus/10
The contact is OK since I can get info using the endpoint : https://mautic server/api/contacts/14637

I am running : Mautic 2.5.1

Getting reports filtered by date range

I am using the Mautic REST api using Python Requests.

I am using the following HTTP command to get a specific report:

GET http://myserver/api/reports/report_id

When I do this I receive a json with the last 30 days worth of leads present in the report. I didn't find anywhere documentation on the parameters for the reports endpoint. Which parameters can I use to set the number of leads to return and the range of lead register dates?

Thank you.

better docs for authorization

I can't get the authorization API to work. From what I can tell from the Mautic documentation, you either have to the authorization manually or use the API. I can't get the API to work, without the user needing to confirm access from Mautic. I thought this would have been possible by using the tokens generated with OAuth1a, but as I make the first call to the contact API, I get an invalid token error.
This is what I tried:

<?php
// ApiAuth::initiate will accept an array of OAuth settings
$mauticSettings = array(
        'baseUrl' => 'http://example.net',       // Base URL of the Mautic instance
        'version' => 'OAuth1a', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
        'clientKey' => 'key',       // Client/Consumer key from Mautic
        'clientSecret' => 'secret',       // Client/Consumer secret key from Mautic
        'callback' => 'http://example.com/account/index2.php'        // Redirect URI/Callback URI for this script
);

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

// 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) {
    die($e->message);
}

$mauticApi = new MauticApi();
$contactApi = $mauticApi->newApi('contacts', $auth, 'http://mautic.v-b.be/api');
$contact = $contactApi->get(1);
$mauticMessage = print_r($accessTokenData, true).print_r($contact, true);
?>

PHP session needs to be running in order to get Oauth1a key

It started with this:

$settings = array(
    '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
);
$auth = ApiAuth::initiate($settings);

if ($auth->validateAccessToken()) {
//...

But in my case the line if ($auth->validateAccessToken()) was always throwing false

So I was digging deep into the code and found out on line 637 of OAuth.php:

$authUrl .= '?oauth_token='.$_SESSION['oauth']['token'];

So I tried to start the session:

session_name("tasselhof");
session_start();
$auth = ApiAuth::initiate($settings);



if ($auth->validateAccessToken()) {
//...

And, starting a session fixed all my problems

Therefore, I think I found a bug in mautic API, because I believe this should be done by API itself, so that the API has to programatically make sure that session is started before using $_SESSION variable

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.