2
votes

What I'm looking to do is add a single recipient to sendgrid when they signup on my site. Once they're added, I will then email the user and add them to a list.

But I'm having trouble adding the user to Sendgrid.

Their documentation (https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Recipients-POST) says to add a user you need to POST their details here:

https://api.sendgrid.com/v3/contactdb/recipients

add_user_new($email);
function add_user_new($email) {

$url = 'https://api.sendgrid.com/v3/contactdb/recipients';

$params =array( array(
   //'name' => 'this is a reserved field',
   'email'=> '[email protected]'
 ));

$json_post_fields = json_encode($params);

// Generate curl request
$ch = curl_init($request);

$headers = array("Authorization: Bearer api_key_here");

curl_setopt($ch, CURLOPT_POST, true);   
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// Apply the JSON to our curl call
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post_fields);

$data = curl_exec($ch);

if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
var_dump($data);
curl_close($ch);
}

echo $json_post_fields;

}

This is the response I get, not sure what I'm missing. The error they say is because the JSON is invalidly formatted.

string(51) "{"errors":[{"message":"request body is invalid"}]} 

This is what my JSON looks like:

{"name":"[email protected]"}
1
Take a look at the docs again. There isn't a request body, the list_id and the recipient_id go in the URL. And there's no name parameter at all... - bwest
@bwest Sorry, I linked to the wrong line in the documentation. The "Add Recipients POST" does not ask for the list_id or recipient_id, since you have not added the user to Sendgrid yet you don't have their ID, so this is the step before adding them to a list. - Andrew Wise
Ahh I see. In that case, at minimum you need to provide the email key in the body. - bwest
I needed to wrap my array in another array - Andrew Wise
@AndrewWise can you post your final answer i am getting same issue here if you post updates it will help others - Sanjay Nakate

1 Answers

-1
votes

Encode your $json_post_fields variable do in JSON format

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_post_fields));