Adding contacts to Sendgrid using PHP doesn't seem to work

67 Views Asked by At

I have been trying to use the SendGrid API to add contacts to a particular list (List ID) from the content the user places inna form.

I have created a form with the correct field names and ID, then wrote some PHP.

No errors come up on the PHP, but no contact gets added to the Sendgrid List. Can some one help me determine what is wrong with my code, no doubt I'm missing something.

if(isset($_POST['email'])) {
    
$first_name = $_POST['firstName']; // required
$last_name = $_POST['lastName']; // required
$email = $_POST['email']; // required

$honeypot = $_POST['Lastname'];
    
if(!empty( $honeypot ) ){
    echo "The information you have entered is not in the correct format or you are a bot. The information you entered has not been submitted.";
    return; 
    
} else {
            
    $curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.sendgrid.com/v3/marketing/contacts",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "PUT",


  CURLOPT_POSTFIELDS => "{\"list_ids\":[\"8266d64e-64e1-4ee6-a23c-bf93be742d18\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\",\"last_name\":\"$last_name\"}]}",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer MY-API-KEY",
        "content-type: application/json"

  ),
));
    
    echo "test";        
}       }
1

There are 1 best solutions below

0
On

Turns out the issue was that I wasn’t executing anything. Thanks for comments, they helped me work it out.