Mautic Community Forums

How can this connection to the Mautic API possibly work?

Your software
My Mautic version is:4.0
My PHP version is:7.0
My Database type and version is:mysql

Your problem
My problem is: I cannot figure out how this could possibly work… It is supposed to be one of the main aids in getting us started… My understanding for basic is you must now use base 64 encoding of the user and pass… and this major instruction does not even use it… Its no wonder almost no one can get the API to work… or am I not understanding what it says.

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

This is what I am referring to:

$auth     = $initAuth->newAuth($settings, 'BasicAuth');

The settings is the user and pw from above… and no where are they using a base 64 conversion… can this work… or or they leading every single person that tries to make heads or tails of it more confused.
This comes from the git hub library and could so easily be changed since tons of folks go there daily trying to learn to use the API… its located at GitHub - mautic/api-library: Mautic API Library

Please if I am reading this wrong… put me back on the right track.

and if it should be base 64… how can i change it to do that…

The newAuth function calls the /lib/Auth/BasicAuth class which has a buildAuthorizationHeader() function that is used along the way. This buildAuthorizationHeader() function encodes your credentials for you.

1 Like

Thank you I will try that…

This all seems so easy for you Alin… can you please take a look at this and tell me if its something you know like you knew that last question. I have asked this same question several different times in several different ways… and no one has answered… I am sure many folks here would like to know this answer… How can i use basic and or Oath to run this command?
it simple adds an existing contact to a segment… this is the code Mautic API uses but i have not been able to figure out how to implement it… THank you so much for the other answer…
Hope you become a super star on her for answering basic API questions as it seems everyone else does not know much about it or those who do know don’t have time to help those of us who don’t know.

Add a contact to a segment in Mautic…

$response = $segmentApi->addContact($segmentId, $contactId);

Looks really simple but i have not been able to get it to work… and i have asked here several times with no response…
When of course the segment and contact id are known in advance…
The ideal situation is to add a contact and while adding place him in a segment… should not be hard to grab the brand new contact id once he is entered and follow with an immediate command to add to the segment… so that a campaign can auto kick off…
There is probably a way to simply go to the mautic db and add an entry directly that will put him/her in a segment… but have not found that in mysql either… i could go that way too.

First off, it’s not recommended to make directly modifications to Mautic database, you should always use the API.

Secondly, assuming you have a class or something that deals with all Mautic methods, you can do something like this

        $initAuth = new ApiAuth();
	$apiUrl = 'https://<base_url_here>/api'
        $auth = $initAuth->newAuth([
            'userName'   => 'usernamehere',
            'password'   => 'passwordhere;,
        ]
, 'BasicAuth');

        $api = new MauticApi();

        $contactApi = $api->newApi('contacts', $auth, $apiUrl);
        $segmentApi = $api->newApi('segments', $auth, $apiUrl);



	// having these defined you can now make api calls
	

// create contact

  $data = [
            'firstname' => 'firstname',
            'lastname'  => 'lastname',
            'address2'  => 'Sam & Sons',
            'email'     => 'email',
            'owner'     => 1,
            'points'    => 3,
            'tags'      => [
                'APItag1',
                'APItag2',
            ],
        ];
        $contactApi->create($data);


//get a contact by email   (this is just one way to do it)

private function getContactByEmail($email)
    {
        $matching_contacts = $contactApi->getList($email, 0, 1);
        foreach ($matching_contacts['contacts'] as $contact)
        {

            if ( $contact['fields']['core']['email']['value'] == $email)
            {
                $result = $contact;
            }
        }

        return $result;
    }

Check documentation and inspect the API returned object’s structure to know how to get all the information

If you encounter errors, please mention the exact errors you get, that will get you faster answers.

Thanks for all your time Alin, but I have no idea how to connect what I am using for a front end driver to connect to the code you sent me… Can you look at what I am using to communicate with the Api and see if you can figure out how to attach your code to my controller…
This particular code will use the basic mode to connect to the API and dump a new contact on it without a problem, but I am not sure how to tie your code to what I have.
I have another front end similar to this that uses get to like pull get stuff from the API… but this is my post work… as i assume that I will need post to submit your code…
If you need the get mode… I can send that also…
Thanks again for all your time I know several others will be following what you do here as much of my code here came from others helping me… so I know a dozen or so are listening with all ears.
Here is the POST version… adds contacts:

<?php

echo "Testing.<br>";

// You need to Authenticate with a BASE64 encoded Username and Password

$username = "myusername";
$password = "mypassword";
$str = $username . ":" . $password;
echo "str: " . $str . "<br>"; 
$apikey = base64_encode($str);
echo "apikey = $apikey<br>";


$endpoint = "https://mybasurl.com/api/";
echo "endpoint = $endpoint<br>";
$url = $endpoint . "contacts/new";
echo "url: " . $url . "<br>";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);

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' => false );

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

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $apikey));

curl_setopt($curl,CURLOPT_HEADER,true);

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

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

$data = curl_exec($curl);

echo "DATA = $data";

if ($data === false) {
  $info = curl_getinfo($curl);
  url_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 "<pre>";
print_r($data);
echo "</pre>";

exit;

// &&&&&&&&&&&&&&&&&&& END OF ADDING CONTACT &&&&&&&&&&&&&&&&&& **Second program commences...\n\n**