player3c
player3c

Reputation: 21

SendGrid Add new Contact to marketing contact list using php curl

Hi im trying to use a custom form on my website to add a new contact to our marketing list, each contact will contain an email and first name.

Im trying to follow this documentation but am having no success: https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact

I have tried using their tool but it always says incorrect JSON but when i use an online validator it says correct, I can't figure out how to match theirs to get my request to post.

This is my current code:

   $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\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"]}",
      CURLOPT_HTTPHEADER => array(
        "authorization: Bearer SG.OCFHb********P3iuikQ.bqKdM-da7X609ZNo9UT7y*********u5fDlfQo80o",
            "content-type: application/json"

      ),
    ));

Upvotes: 1

Views: 1234

Answers (3)

Luis Murrieta
Luis Murrieta

Reputation: 1

This is the best way:

$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 => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'PUT',
    CURLOPT_POSTFIELDS =>'{"list_ids": ["list-ID"], "contacts": [{"email": "' . $_GET["email"] . '"}]}',
    CURLOPT_HTTPHEADER => array(
        ': ',
        'Authorization: Bearer SG.000000000',
        'Content-Type: application/json'
    ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;
    die();

Upvotes: 0

andiOak
andiOak

Reputation: 396

One little trick to not have to deal with all the backslashes and escaping is to use a pre-defined object literal in PHP, by using arrays with (object) in front of them, to define the objects nested in the structures.

  • make an object, turn it into JSON with json_encode
  • enter the encoded JSON object into the CURLOPT_POSTFIELDS in the cURL request.

<?php 

// make custom fields object for entry into the cURL later on:
// THERE IS NO OBJECT LITERAL IN PHP, but using (object) in front of an array, voila

$contact_info = (object)[
    "list_ids" => [
        "eeee-eeee-eeee-eeee-eeeeexample" // array of list ids here.
    ],
    "contacts" => [ // this is an array of objects (array[object]), according to the api-docs.
        (object)[
            "email" => "[email protected]",
            "country" => "the country",
            "city" => "the city",
            "custom_fields" => (object)[
                "e1_T" => "sign-up-page-name",  // only custom fields use ids as the key.
                "e2_T" => "next-custom-field"   // keep adding custom fields in this array.
            ]
        ]
    ]
];

// now all we have to do is to encode the object into JSON:
$json_contact_data = json_encode($contact_info);


// now add the contact:

$curl = curl_init();

// update the contact
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 => $json_contact_data, // here we enter the pre-configured json from above.
    CURLOPT_HTTPHEADER => array(
        "authorization: Bearer " . $your_api_key . "",
        "content-type: application/json"
    )
));

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

$decoded = json_decode($response, true); // decode into associative array.


if ($err) {
    echo "cURL Error #: " . $err;
} else {
    print_r($decoded); // print the decoded json message.
}


?>

Upvotes: 1

Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10704

You just should be added } chars after $first_name.
This is valid JSON:

  CURLOPT_POSTFIELDS => "{\"list_ids\":[\"bf3ce5bd-14a2-414b-9b81-*****8e8ea62\"],\"contacts\":[{\"email\":\"$email\",\"first_name\":\"$first_name\"}]}",

You can check it with https://jsonformatter.curiousconcept.com/ validator website.

Upvotes: 1

Related Questions