Giter Site home page Giter Site logo

api-library's Introduction

codecov

All Contributors

About Mautic

Mautic is the world’s largest open source marketing automation project. With over 200,000 organisations using Mautic and over 1,000 community volunteers, we empower businesses by making it easy to manage their marketing across a range of channels. Stay up to date about initiatives, releases and strategy via our blog.

Marketing automation has historically been difficult to implement within organisations. The Mautic Community is an example of open source at its best, offering great software and a vibrant and caring community in which to learn and share knowledge.

Open source means more than open code. Open source provides equality for all and a chance for everyone to improve.

Mautic

Get Involved

Before we tell you how to install and use Mautic, we like to shamelessly plug our awesome user and developer communities! Users, start here for inspiration, or follow us on Twitter @MauticCommunity or Facebook @MauticCommunity. Once you’re familiar with using the software, maybe you will share your wisdom with others in our Slack channel.

Calling all devs, testers and tech writers! Technical contributions are also welcome. First, read our general guidelines about contributing. If you want to contribute code, read our CONTRIBUTING.md or Contributing Code docs then check out the issues with the T1 label to get stuck in quickly and show us what you’re made of.

If you have questions, the Mautic Community can help provide the answers.

Installing and using Mautic

Supported Versions

Please check the latest supported versions on the Mautic Releases page.

Software Downloads

The GitHub version is recommended for both development and testing. The production package (including all libraries) is available at mautic.org/download.

Installation

Disclaimer

Install from source only if you are comfortable using the command line. You'll be required to use various CLI commands to get Mautic working and keep it working. If the source/database schema gets out of sync with Mautic releases, the release updater may not work and will require manual updates. For production, we recommend the pre-packaged Mautic which is available at mautic.org/download.

Also note that source code outside of a tagged release should be considered ‘alpha’. It may contain bugs, cause unexpected results, data corruption or loss, and is not recommended for use in a production environment. Use at your own risk.

How to install Mautic

You must already have Composer available on your computer because this is a development release and you'll need Composer to download the vendor packages.

Also note that if you have DDEV installed, you can run 'ddev config' followed by 'ddev start'. This will kick off the Mautic first-run process which will automatically install dependencies and configure Mautic for use. ✨ 🚀 Read more here

Installing Mautic is a simple three-step process:

  1. Download the repository zip then extract the zip to your web root.
  2. Run the composer install command to install the required packages.
  3. Open your browser and complete the installation through the web installer.

If you get stuck, check our our general troubleshooting page. Still no joy? Join our lively Mautic Community for support and answers.

User Documentation

Documentation on how to use Mautic is available at docs.mautic.org.

Developer Docs

Developer documentation, including API reference docs, is available at developer.mautic.org.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Dennis Ameling
Dennis Ameling

💻 📓
Mohammad Abu Musa
Mohammad Abu Musa

💻 📓 👀
John Linhart
John Linhart

📓 👀 💻 ⚠️
Norman Pracht - Webmecanik
Norman Pracht - Webmecanik

📓 💻
Zdeno Kuzmany
Zdeno Kuzmany

📓 👀 💻 ⚠️
Steve Robinson
Steve Robinson

📓 🐛
Petr Šnobl
Petr Šnobl

💻 🐛
Lukas Günther
Lukas Günther

💻 📖 📓
Ruth Cheesley
Ruth Cheesley

📓 👀 📖
Anton Vlasenko
Anton Vlasenko

💻 ⚠️
Miroslav Fedeleš
Miroslav Fedeleš

💻 ⚠️ 📓 👀
gabepri
gabepri

🐛 💻
incentfit
incentfit

📓
Lukáš Drahý
Lukáš Drahý

💻 👀
Alan Hartless (he/him)
Alan Hartless (he/him)

💻
Mohit Aghera
Mohit Aghera

💻 📓 👀
Dom Parry
Dom Parry

📓
sensalot
sensalot

📓
Rahul Shinde
Rahul Shinde

👀 📓 💻
jos0405
jos0405

💻 📓
Nick Veenhof
Nick Veenhof

👀
Patryk Gruszka
Patryk Gruszka

💻 📖 ⚠️ 👀 📓
Alex Hammerschmied
Alex Hammerschmied

💻 📓
Dirk Spannaus
Dirk Spannaus

🐛 📓
Rehan Nischal
Rehan Nischal

🐛
Christophe9880
Christophe9880

📓
Saurabh Gupta
Saurabh Gupta

💻 👀
Tejas Navghane
Tejas Navghane

⚠️ 💻 📓 👀
Florent Petitjean - Webmecanik
Florent Petitjean - Webmecanik

📓
Oluwatobi Owolabi
Oluwatobi Owolabi

📋
Favour Kelvin
Favour Kelvin

📖 📢
Giovanni Mascellani
Giovanni Mascellani

💻
Raphael van der Woude
Raphael van der Woude

📓
mannp
mannp

🐛 📓
MarketSmart
MarketSmart

💻
Leon
Leon

📓
bryanitamazonva
bryanitamazonva

🐛
n-azimy
n-azimy

💻
Ikko Ashimine
Ikko Ashimine

💻
Max Lawton
Max Lawton

💻 📖
Rohit Pavaskar
Rohit Pavaskar

💻
Disha P
Disha P

💻
Adrian
Adrian

👀 📓 💻
vijayhrdm
vijayhrdm

🐛
julienWebmecanik
julienWebmecanik

💻
Johan Buchert
Johan Buchert

📓
TS16V
TS16V

🐛
rafalsk
rafalsk

🐛
Jonathan Dahan
Jonathan Dahan

🐛
j26w
j26w

📓
Theodoros Ploumis
Theodoros Ploumis

💻
Sreenivasulu Avula
Sreenivasulu Avula

📓 👀
Mohammad Lahlouh
Mohammad Lahlouh

📓
ArnaudSau
ArnaudSau

💻
Andrew Bell
Andrew Bell

📓
Alfredo Arena
Alfredo Arena

💻
mollux
mollux

💻
ekkeguembel
ekkeguembel

📓
Madlen
Madlen

📓
Kathrin Schmid
Kathrin Schmid

🌍
Rahul Dhande
Rahul Dhande

💻
Artem Lopata
Artem Lopata

📓 👀 💻
Anthony Bailey
Anthony Bailey

💻
Eloi Marques da Silva
Eloi Marques da Silva

💻
Tomasz Kowalczyk
Tomasz Kowalczyk

💻
jensolsson
jensolsson

📓
Tony Bogdanov
Tony Bogdanov

💻
Brady Cargle
Brady Cargle

📓
mmarton
mmarton

📓
bodrak
bodrak

💻
nick-vanpraet
nick-vanpraet

💻
Volha Pivavarchyk
Volha Pivavarchyk

📓 💻
Nish Joseph
Nish Joseph

💻
Damzoneuh
Damzoneuh

💻
alinmbb
alinmbb

💻
Déborah Salves
Déborah Salves

📓
automatyzuj
automatyzuj

📓
KN4CK3R
KN4CK3R

💻
Benjamin Lévêque
Benjamin Lévêque

💻
Benjamin
Benjamin

💻
Iris Amrein
Iris Amrein

📓
peter.osvath
peter.osvath

💻
poweriguana
poweriguana

📓 📆
OnyXxL
OnyXxL

📓
Dominik Lacković
Dominik Lacković

📓
Omer Toledano
Omer Toledano

📓
ZebruhDivs
ZebruhDivs

📓
Alan Wierzchoń
Alan Wierzchoń

💻
Tomazz Jurich
Tomazz Jurich

📓
putzwasser
putzwasser

🐛
erk
erk

📓
Daniel
Daniel

📓
agencia904
agencia904

📓
mbfds
mbfds

📓
Lucas Lazarini
Lucas Lazarini

📓
Gonzalo Cao Cabeza de Vaca
Gonzalo Cao Cabeza de Vaca

📓
Robmobius
Robmobius

📓
Marc Beinder
Marc Beinder

💻
bergwerkweb
bergwerkweb

💻
Rembrand
Rembrand

📓 💻 👀
TechBill
TechBill

📓
Irfan Hanfi
Irfan Hanfi

💻
Anna Munk
Anna Munk

💻
Sven Döring
Sven Döring

📓
Pedro de Jesus
Pedro de Jesus

💻
Jean-Marc
Jean-Marc

📓
Paul Sanduleac
Paul Sanduleac

💻
Lenon Leite
Lenon Leite

💻
Alan Syrgak
Alan Syrgak

📓
Mohammed Header
Mohammed Header

💻
Dana Linhartová
Dana Linhartová

💻
Thanks
Thanks

⚠️
Patrick
Patrick

📓
Tomas Votruba
Tomas Votruba

💻
Tirtharaj Ghosh
Tirtharaj Ghosh

📖
Ruben Nogueira
Ruben Nogueira

💻
Oleh Vanin
Oleh Vanin

👀
Tim Mallezie
Tim Mallezie

💻
Markus Staab
Markus Staab

💻
code5rick
code5rick

🐛 💻
jcrandell7
jcrandell7

📓
Jason Woods
Jason Woods

💻
Enkhjargal Lkhagvaa
Enkhjargal Lkhagvaa

👀
alexbusu-motork
alexbusu-motork

👀
David Gorges
David Gorges

🐛 💻
Gernot Pansy
Gernot Pansy

🐛 💻
andersonjeccel
andersonjeccel

💻 ️️️️♿️ 📖 🐛 👀 📓 🎨 📆
Alexei Pl
Alexei Pl

🐛 💻
Alvaro
Alvaro

🐛
Ajit
Ajit

💻 🐛
Esthertests
Esthertests

👀
magdalenaleonow
magdalenaleonow

🐛
Priyanshi Gaur
Priyanshi Gaur

💻
Damian
Damian

👀 🐛
Markus Heinilä
Markus Heinilä

👀
Juan Gadiel Rosado Colon
Juan Gadiel Rosado Colon

🐛 📓
Abhisek Mazumdar
Abhisek Mazumdar

💻
Lukas Pokorny
Lukas Pokorny

📖 💻
Tosin Akinbowa
Tosin Akinbowa

💻
nishant-s7
nishant-s7

💻

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

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

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.

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

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 & 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?

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

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.

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);
?>

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.

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'

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.

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?

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?

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'.

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();

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

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.).

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?

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.

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.

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.

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().

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

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

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.

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?

[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

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.

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

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?

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

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!");
    }
}

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.

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.

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;
  }

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.

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?

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.
        )

)

[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.

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.

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?

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.

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

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.