Mautic Community Forums

Is anyone willing to share a template to allow me to communicate with the Mautic APi for $100?

Your software
My Mautic version is:3.3.2
My PHP version is:7.3
My Database type and version is:Mysql DB

Your problem
My problem is: I have been messing with this Mautic API connection for weeks and no further along than i was on day one. I have a lot of experience with PHP, jquery, javascript… etc so I know if i could just make the connection and send a few commands like adding, deleting and moving DB items I will be fine…I would like to use Oath2…if possible…
Please let me know if your are interesting in discussing this further.
Not expecting a lot… just the abiility to do basic communications with the Mautic API…

These errors are showing in the log:

Steps I have tried to fix the problem:

Hi,
Did you check this?
https://developer.mautic.org/#oauth-2

For basic auth, check this forum post:

Hi @tommytx123

It can be a bit tricky to figure it all out in the beginning. Also if you are looking to implement it with JS and CORS. Been there…

I have done a lot with the API now. PHP, and JS. I’m sure I can help you to get startet quicker.

1 Like

Thanks for your response Joey,
Here is what i have after following your conversation with someone else you were conversing with… but not working… In your conversation the other gentleman mentions the need for base 64 in the password… I don’t have any of that do I need to try that… Thanks

indent preformatted text by 4 spaces
<?php

// echo “This is basic-api.php
”;
// Documentation Disaster - #5 by adam.clark
$loginname = ‘???seopr_crm’; // Login name of your API user
$password = ‘???goZulu911@’; // This is the password of the API user
$siteurl = ‘???seopremium/Mautic/’;
$email = ‘???tom@cox.net’;
$firstname = ‘Tom’;
$lastname = ‘Chambers’;
$tag = ‘purchased’;
// This is our curl call:
$curl = curl_init();
// Set some options - we are passing in a user agent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => “https://” . $loginname . “:” . $password . “@” . $siteurl . “/api/contactsnew/”,
CURLOPT_USERAGENT => ‘Wesleys Secret App’,
CURLOPT_POST => 1,
// posting the payload
CURLOPT_POSTFIELDS => array(
‘firstname’ => ‘Mickey’,
‘lastname’ => ‘Mouse’,
‘email’ => ‘tobo@gogo.com’,
‘tags’ => ‘Purchased’
)
));
curl_exec($curl);
?>

To run this php gives a blank page output with absolutely nothing on it…
If I un-remark the line at the top // echo “This is basic-api.php
”; it prints that fine… so suggests there may not be any obvious php errors…

Note:Line 45 is this — ‘email’ => ‘tobo@gogo.com’,
Error shown in the php error logs.
[18-May-2021 19:06:40 UTC] PHP Parse error: syntax error, unexpected ‘https’ (T_STRING), expecting ‘;’ or ‘,’ in /home/idxseopremium/public_html/_test1/basic-api.php on line 45

 <?php
   // echo "This is basic-api.php<br>";
   // https://forum.mautic.org/t/documentation-disaster/18201/5
   $loginname = '???seopr_crm';   // Login name of your API user
   $password = '???goZulu911@';        // This is the password of the API user
  $siteurl = '???seopremium/Mautic/';
  $email = '???tom@cox.net';`

Not sure what the https complaint is since the closest https is on line 32 not 45.
Line 32. Is the closest https
Line 45. ‘email’ => ‘tobo@gogo.com’,

Tommy… if you follow the conversation with me an Joey in “Documentation Disaster”, you will see the code that I put at the bottom of that. It is super clear what you need to do.

You need to Authenticate with a BASE64 encoded Username and Password

$username = "myLoginUsernameToMyMauticInstance";
$password = "myPasswordToMyMauticInstance"; 
$str = $username . ":" . $password; echo "<p>str: " . $str . "</p>";
$apikey = base64_encode($str);
$endpoint = "https://YOUR-URL-OF-MAUTIC-INSTANCE.com/api/";



$url = $endpoint . "contacts/new"; echo "<p>URL: " . $url . "</p>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);

## SET TO POST AND GET BUILD THE DATA ****************************** 
curl_setopt($curl, CURLOPT_POST, 1); // Set as a POST
$data = array(
    'owner' => 1,
    'firstname' => 'Jim',
    'lastname'  => 'Contact',
    'email'     => 'jim.contact@his-site.com',
    'ipAddress' => $_SERVER['REMOTE_ADDR'],
    'overwriteWithBlank' => true
);

echo "<pre>";
print_r($data);
echo "</pre>";


# curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
## ****************************************************************** 

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey));
curl_setopt($curl,CURLOPT_HEADER,true); // copied from th PHP AbstractAuth.php "function makeRequest".
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the result output to be a string.
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // copied from th PHP AbstractAuth.php "function makeRequest".
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$data = curl_exec($curl);
if ($data === false) 
	{
	$info = curl_getinfo($curl);
	curl_close($curl);
	die('error occurred during curl exec. Additional info: ' . var_export($info));
	}
	else
	{
	$info = curl_getinfo($curl);
	var_export($info);
	curl_close($curl);
	}

This should work

2 Likes

TO “GET A CONTACT”… Do something like this:

/* Authenticate As above example */
 $username = "YourMauticUNtoLogin";
$password = "YourMauticPWtoLogin"; 
$str = $username . ":" . $password; echo "<p>str: " . $str . "</p>";
$apikey = base64_encode($str);
$endpoint = "https://YOUR-mautic-DOMAIN.com/api/";

   /* The $id is the contact's ID */
    $id=2;
    $url = $endpoint . "contacts/" . $id; // echo "URL: " . $url ;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);



curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey)); echo "<p>apikey: " . $apikey . "</p>";
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the result output to be a string.
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$data = curl_exec($curl);
if ($data === false) 
	{
	$info = curl_getinfo($curl);
	curl_close($curl);
	die('error occured during curl exec. Additional info: ' . var_export($info));
	}
	else
	{
	curl_close($curl);
	}





$decodedContact = json_decode($data);
echo "<h2>decodedContact</h2>";
echo "<pre>";
print_r($decodedContact);
echo "</pre>";
1 Like

In your code above where you quote Documentation Disaster, that is not the code I suggested.

Also… (and it may just be the formatting in the Forum post but I am not sure)… , you have “;” on new lines
You have … “// posting the payload” right in the midde of your “curl_setopt_array($curl, array(” array just below Curl definition “CURLOPT_POST => 1,”

So it looks pretty broken code… but, also, it is not the code to use as far as I am concerned. I too, battled with this for days. But Joey is great help - sign up to his newsletter and stuff.

I hope I have helped you.

Also… when you post code… Paste it into the box, select it and then click the “</>” button in the text-editor bar… and that will format it better for us.

Thanks !!!

2 Likes

Thank you… I will give it a try… What is so difficult is add a lot of code and having no way to know at what point it failed… if I was a little more code handy… I would add a lot of check points to see how far it progressed… I suppose that the error log should do that for you but not very well… I have turned on every sort of error logger i know of and much of the time it does not show anything…I add this at the top of the php file and sometimes it does and sometimes it don’t report errors…
But yes i will put in my pw and url and give it a try… as I followed what you wrote but with the add ins was difficult what parts of the program i needed… Thanks a lot will let you know…

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$username = "myuser";
$password = "mypass"; 
$str = $username . ":" . $password; echo "<p>str: " . $str . "</p>";
$apikey = base64_encode($str);
$endpoint = "https://?????premium.com/Mautic/api/";

$url = $endpoint . "contacts/new"; echo "<p>URL: " . $url . "</p>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);



## SET TO POST AND GET BUILD THE DATA ****************************** 
curl_setopt($curl, CURLOPT_POST, 1); // Set as a POST
$data = array(
'owner' => 1,
'firstname' => 'Mickey',
'lastname'  => 'Mouse',
'email'     => 'mickey@disneyland.com',
'ipAddress' => $_SERVER['REMOTE_ADDR'],
'overwriteWithBlank' => true
);

echo "<pre>";
print_r($data);
echo "</pre>";

Looks like it did everything perfect but put it in the db…
And i manually installed one in the db just to make sure that is ok…
Also I made a very basic form with segment to force a campaign to start and it loaded into the db and said it had activated the segment…to start the campaign…
I even removed the owner and would not post either way… I changed the PW and user and got exact same results… no post to db… and its same user and pass that i get in with…
Is there anyway to determine if its not getting inside… since it acts same way if PW is bad or good… but no errors…anywhere… and it formats the data that is going in very nicely… but no go into db…
The echoed URL looked perfect…

Did it format the code in the box correctly… looks nice but does not appear to be indented 4 letters… as it said… it correctly identified the IP.

This may be helpful
image

In your code above Tommy… I can’t see :slight_smile:

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey)); echo "<p>apikey: " . $apikey . "</p>";
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the result output to be a string.
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$data = curl_exec($curl);
if ($data === false) 
	{
	$info = curl_getinfo($curl);
	curl_close($curl);
	die('error occured during curl exec. Additional info: ' . var_export($info));
	}
	else
	{
	curl_close($curl);
	}

I’ll be honest, I am not 100% sure what it all does, but you definitely need to pass the $apikey in the header

Other issues could be that you have the wrong URL… Is your “Mautic” folder the ROOT of your Mautic installation?? And, you have a capital “M” on “Mautic”… is that correct (as PHP is case sensitive)

Thanks Adam…answers to your obvious questions…
Yes its on a uppercase first letter subdomain … https;//mydomain.com/Mautic/
not in the root…Here is my best code that shows how i addressed saving a contact and retrieving a contact by id number… It appears ok other than the fact that it is not getting in with the API key i generate… as if i put a bad pw in the program i see the exact same result when a good pw is used… Is it possible my security is so good that it is rejecting my user and pw by http… i remember i used to to that long ago to get direct to cpanel via http but security has long since shut that down.
But the way its looking is something and could be security may be keeping me out an required the oath2 service… Have you conquered the oath2 service that would be great if you have any scripts that work with the oath2… Below is my two final that i believe are correct but do not ``allow adding the new lead or retrieving the contact by id either… really does seem like some security holding back… I tried logged into Mautic and logged out and nothing mattered including using a wrong pw for the program and same results with good or bad pw…

Below are two programs one for adding a new contact and one for retrieving a contact by id.
:stuck_out_tongue:

&&&&&&&&&&&&&&&&&&&&& ADDING A NEW CONTACT &&&&&&&&&&&&&&&

<?php ini_set('display_errors', 'On'); error_reporting(E_ALL); echo "

1. Adam Testing by Tom.


"; // You need to Authenticate with a BASE64 encoded Username and Password // Note: The u and p are the exact credentials that I use to access my mautic. $username = "XXXXXX; $password = "XXXXXX"; $str = $username . ":" . $password; echo "

str: " . $str . "

"; $apikey = base64_encode($str); echo "API KEY = $apikey
"; // note: Full path to my mautic.. yes M uppercase (so mautic is in sub dir = /Mautic // note: the url below minus the /api/ is the exact url i use to enter my mautic. $endpoint = "https://XXXXXXpremium.com/Mautic/api/"; echo "ENDPOINT = $endpoint
"; $url = $endpoint . "contacts/new"; echo "

URL: " . $url . "

"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); ## SET TO POST AND GET BUILD THE DATA ****************************** // I used the exact data owner, firstname etc that you used to make it easier to verify the data when you look at it. curl_setopt($curl, CURLOPT_POST, 1); // Set as a POST $data = array( 'owner' => 1, 'firstname' => 'Kelly', 'lastname' => 'Mouse', 'email' => 'kelly@disneyworld.com', 'ipAddress' => $_SERVER['REMOTE_ADDR'], 'overwriteWithBlank' => true ); echo "
";
print_r($data);
echo "
"; # curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); ## ****************************************************************** curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey)); curl_setopt($curl,CURLOPT_HEADER,true); // copied from th PHP AbstractAuth.php "function makeRequest". curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the result output to be a string. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // copied from th PHP AbstractAuth.php "function makeRequest". curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $data = curl_exec($curl); echo "DATA = $data
"; if ($data === false) { $info = curl_getinfo($curl); curl_close($curl); die('error occurred during curl exec. Additional info: ' . var_export($info)); } else { $info = curl_getinfo($curl); var_export($info); curl_close($curl); } echo "
";
print_r($data);
echo "
"; exit; // &&&&&&&&&&&&&&&&&&& END OF ADDING CONTACT &&&&&&&&&&&&&&&&&& **Second program commences...\n\n** // &&&&&&&&&&&&&&&&& BEGIN RETRIEVE A CONTACT BY ID &&&&&&&&&&&&&&&&&&&\n\n Next is re-trievieng an existing contact by ID. <?php // TO GET A CONTACT Do something like this: /* Authenticate As above example */ $username = "XXXXXXXX"; $password = "XXXXXXXX"; $str = $username . ":" . $password; echo "

str: " . $str . "

"; $apikey = base64_encode($str); echo "APIKEY = $apikey
"; $endpoint = "https://XXXXXXpremium.com/Mautic/api/"; echo "Sendpoint - $endpoint
"; // The $id is the contact's ID $id=9; echo "ID = $id
"; $url = $endpoint . "contacts/" . $id; // echo "URL: " . $url ; echo "

$url


"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey)); echo "

apikey: " . $apikey . "

"; curl_setopt($curl,CURLOPT_FOLLOWLOCATION,true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Set the result output to be a string. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $data = curl_exec($curl); if ($data === false) { $info = curl_getinfo($curl); curl_close($curl); die('error occured during curl exec. Additional info: ' . var_export($info)); } else { curl_close($curl); } $decodedContact = json_decode($data); echo "

decodedContact

"; echo "
";
print_r($decodedContact);
echo "
"; exit; // &&&&&&&&&&&&&&&&& END OF RETRIEVING A CONTACT BY ID &&&&&&&&&&&&&&
Sorry about that was trying to figure out the </> thingy....

Tommy… Is any of it working??

We’re closer I suspect… maybe… Could you edit your post and do the whole “</>” thing. It is difficult to read. Or… you can send me your PHP files to oobaCreativ@gmail.com and I will take a look… and we can post any resolution here ???

It’s tricky to tell what the problem is.

One thought I had… Do you have a working HTTPS certificate on your server? I am presuming so.

PS: I am not even going to attempt oAuth… I am not sure I even want to. If I was developing an App that needed it, I might look again but just getting the basic cURL stuff to work was hard enough.

: -)

Also… there are MUCH MUCH cleverer folk in the Mautic community than me. I am hoping to be “the dumb one” that works out how to make the training and documentation better. But I am way behind on my learning at the moment due to existing work commitments.

Nope… neither the send contact to DB or read contact by ID… so I will send to your email to work it out… but will be tomorrow as I have a previous engagement tonight… but would like to dump a small piece of php here to see if i fully understand the </> sometimes it don’t work for me correctly…
So what i will do here is paste my code than hi-light the code… Then click the </> that way I can test this short piece…

You need to Authenticate with a BASE64 encoded Username and Password

$username = "myLoginUsernameToMyMauticInstance";
$password = "myPasswordToMyMauticInstance"; 
$str = $username . ":" . $password; echo "<p>str: " . $str . "</p>";
$apikey = base64_encode($str);
$endpoint = "https://YOUR-URL-OF-MAUTIC-INSTANCE.com/api/";

Looks like it worked fine this time… I will just have to be careful.

Thanks so much for your help Adam… I am sure we are making progress.

Yes cert for domain is in place and working fine…
sending both files to your email… is it possible to enter your data and see if it words as is…
Thanks Tom
Let me know if you do not receive the data to your email in the next hour…

Nothing in my inbox… :slight_smile:

That’s 'cos I am an idiot and rushed typing my own email address. Should have been:

oobaCreative@gmail.com

I might miss the gist here, but why are you not using the Mautic API library?
https://packagist.org/packages/mautic/api-library

It will do all the heavy lifting for you.
And read the Rest API section in
https://developer.mautic.org/
Even showing how to do OpenAuth2.

Something that might help. Hard reset your cache by deleting the /var/cache directory. That helped me getting the API running.

I sent it again to the new email

Thanks for the response maxemojo…but very few folk according to the comments ever figure this out to work in a real live situation… each and everybody says I dun this and i did that but no one ever shares actual live examples of a REAL live working model… I think i have read and viwed a dozen youtube and read the manual a dozen times… and they give all sorts of possible ways to do it… but NONE before Joeyk and Adam actually gave live examples… of full code that worked for them…
IF you look back at the comments it seems that rarely does anyone get it to work… and then when the do they won’t share the actual code they used from A-Z…
Once i get all the bugs worked out of my code I will publish it in full… not bits and pieces…
But thanks for the offer to go back and simply follow the steps… if it were that easy there would not be so many requests for help on here…