Search code examples
phpjsoncurlsendgrid

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"

      ),
    ));

Solution

  • 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.