【问题标题】:How to Add Recipient to Sendgrid v3 API with PHP如何使用 PHP 将收件人添加到 Sendgrid v3 API
【发布时间】:2016-04-12 15:16:24
【问题描述】:

我要做的是在他们在我的网站上注册时向 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"}

【问题讨论】:

  • 再次查看文档。没有请求正文,list_idrecipient_id 进入 URL。而且根本没有name 参数...
  • @bwest 抱歉,我链接到文档中的错误行。 “添加收件人 POST”不要求提供 list_id 或收件人 ID,因为您尚未将用户添加到 Sendgrid,但您还没有他们的 ID,因此这是将他们添加到列表之前的步骤。
  • 啊,我明白了。在这种情况下,您至少需要在正文中提供 email 键。
  • 我需要将我的数组包装在另一个数组中
  • @AndrewWise 你能发布你的最终答案吗?如果你发布更新它会帮助其他人,我在这里遇到同样的问题

标签: php sendgrid


【解决方案1】:

将您的 $json_post_fields 变量编码为 JSON 格式

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

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 2018-11-09
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    相关资源
    最近更新 更多