0

I try to add a contact to a list of contact in my Mailjet account, there is my code :

<?php

require('../mailjet_apiv3/src/Mailjet/php-mailjet-v3-simple.class.php');

$mj = new Mailjet($apiKey, $secretKey);
$list_id =123;
$params = array(
    'method'    => 'POST',
    'Email' =>  'test@tst.tst'
);
            $result = $mj->contact($params);

            if(isset($result->StatusCode) && $result->StatusCode == '400')
                return false;

            $contact_id = $result->Data[0]->ID;

            // Add the contact to a contact list
            $params = array(
                'method'    => 'POST',
                'ContactID' => $contact_id,
                'ListID'    => $list_id
            );
            $result = $mj->listrecipient($params);
?>

I get this error : Notice: Trying to get property of non-object in .../addContactMailJet.php on line 30.

I could not find the problem, have someone idea what is wrong !

Youssef Mayoufi
  • 25
  • 1
  • 12

1 Answers1

0

The status code is accessed this way:

$mj->_response_code

Because you are maybe trying to POST on the same contact over and over, it might have sent you back an error response code.

But a better way to add a contact to a list would be to use the contactslistManageContact resource. Here's how:

 /**
     *  @param  array   $contact    An array describing a contact.
 *                              Example below the function.
 *  @param  int     $listID     The ID of the list.
 *
 */
 function addDetailedContactToList ($contact, $listID)
 {
     $mj = new Mailjet(getenv('MJ_APIKEY_PUBLIC'), getenv('MJ_APIKEY_PRIVATE'));
     $params = array(
         "method" => "POST",
         "Action" =>  "addnoforce",
         "ID" => $listID
     );

     // merge the contact informations with the call informations
     $params = array_merge($params, $contact);
     $result = $mj->contactslistManageContact($params);

     if ($mj->_response_code == 201)
         echo "success - detailed contact added to the list ".$listID;
     else
         echo "error - ".$mj->_response_code;

     return $result;
 }
 // $contact array example
 /*  $contact = array(
  *      "Email"         =>  "foo@bar.com",   // Mandatory field!
  *      "Name"          =>  "FooBar"
  *  );
  */
Guillaume Badi
  • 749
  • 5
  • 15