如何使用PHP将收件人添加到Sendgrid v3 API

时间:2016-04-12 15:16:25

标签: php sendgrid

我要做的是在我的网站上注册时向sendgrid添加一个收件人。一旦添加,我将通过电子邮件发送给用户并将其添加到列表中。

但是我将用户添加到Sendgrid时遇到了麻烦。

他们的文档(https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Add-Recipients-POST)说要添加一个用户,你需要在这里发布他们的详细信息:

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'=> 'info@domain.com'
 ));

$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;

}

这是我得到的回应,不知道我错过了什么。他们说的错误是因为JSON格式无效。

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

这就是我的JSON的样子:

{"name":"hello@test.com"}

1 个答案:

答案 0 :(得分:-1)

以JSON格式对$ json_post_fields变量进行编码

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_post_fields));
相关问题