Mautic Community Forums

Php Library create contact and add to segment

Hi, i’m exploring the Php Library to integrate mautic api with a custom application.
I’m able to retrieve the contact data and now i want to create a contact but i can’t find a method to assing the new contact to a segment.

this is the code for create the contact

 $data = array(
                'firstname' => $firstname,
                'lastname'  => $lastname,
                'email'     => $email,
                'ipAddress' => $_SERVER['REMOTE_ADDR'],
                'overwriteWithBlank' => true,

            $contact = $contactApi->create($data);

to add the contact to the segment, i need the ID of the contact just inserted or is there a way to do it contextually?


Good luck with that… as there does not seem to be a very high level of interest in directly programming the Mautic API… Several folks on here have played with it… especially the Basic access… but its all a bunch of jumbled commands… No one seems to have come out with any simple methods… Most say the instructions are too difficult to follow and may have just given up. I have been collecting little tid bits here and there and have developed some low level knowledge as to programming the API… but nothing earth shattering.
I will be happy to share as much as I know (not that much) and here is some of the code that talks about what you need to connect a contact with a specific Segment… but not sure how to assemble it all.

I wish someone would come out with a very basic step by step tutorial on playing with the API but does not look good for that…

Add a contact to a segment in Mautic…
$response = $segmentApi->addContact($segmentId, $contactId);
if (!isset($response[‘success’])) {
// handle error

This may help you a tiny bit…
I noted up there earlier you stated that you have been able to retrieve the contact data… Did you retrieve that using basic or one of the other OATH’s… Would you be willing to share the code you used… THanks…

I’m getting the data with basicAuth
I know how to add contact to segment but I need the inserted contact’s id
the php library need a method to add a response to the create contact with the last inserted id (or something similar)

I have not tried this myself, but looking at the documentation for the PHP Mautic API library seems to suggest you can just get the contact returned from the response.

Something like this?

// Create the contact
$response = $contactApi->create($data);
$contact  = $response[$contactApi->itemName()];

//Add contact to segment
$response = $segmentApi->addContact($segmentId, $contact['id']);

I have to try, thanks for the suggestion. I will be away until the end of September unfortunately but then I will try, I had also seen the response but it was not clear to me. Thanks