How to get the ID of the current Contact with PHP Mautic API?

655 Views Asked by At

As I couldn't find anything in the documentation I might have a general understanding issue. But what I want to achieve is getting the ID of the current Contact browsing the Site. To get user details I always have to know the ID, like documented here: https://developer.mautic.org/#contacts

$api        = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $settings['baseUrl']);
$contact    = $contactApi->get(3);

Is there a way to the ID of the current Contact? I want to play highly customized content on the website and an entry point to get user details.

3

There are 3 best solutions below

0
Honk der Hase On

It's a REST API, so you should get a response in any case. What's the content of the response (eg. what contains $contact)? What's the HTTP code of the response? Error messages?

However... I'm not familiar with this particular API, but the principles are always the same

https://developer.mautic.org/?php#list-contacts

Without any query parameters it should give the full list of contacts. Each of the contact records should come with an ID for the details:

https://developer.mautic.org/?php#get-contact

As said, I'm not familiar with the API, so it could be that you get a contact list only from a higher entity, like a Company or so.

I can recommend Postman (https://www.postman.com/), a neat tool to make REST API requests while having full control over all the details.

3
Jay Bhatt On

Assuming that you're trying to get the details of the current logged in user.

You can use themautic.helper.user helper to do that as shown below:

<?php
$user = $this->get('mautic.helper.user')->getUser();

$firstName = $user->getFirstname();
$lastName  = $user->getLastname();
$email     = $user->getEmail();
$profile   = $user->getProfile();

$role = $user->getRole()->getName();

if ($role->isAdmin()) {
    // do something
}

Ref: https://developer.mautic.org/#services44

0
Surge On

In order to do what you want here I do not think you actually need the API to get the user id. Mautic has dynamic content and as long as the user has a cookie dropped on his browser you can use Dynamic Content to say "Hi {contactfield=firstname}, welcome back.

You can actually call any custom field into the dynamic content slot.

Check out dynamic content which is found under the Components section in the left menu