在查看了 sendgrid API 并在我自己的服务器上进行了测试之后,我能够将联系人添加到联系人列表中。由于您已经创建了列表,因此下一步是创建要添加到列表中的收件人。你可以这样做
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/recipients'; //12345 is list_id
$params = array(array(
'email' => 'amitkray@gmail.com',
'first_name' => 'Amit',
'last_name' => 'Kumar'
));
$json_post_fields = json_encode($params);
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
curl_close($ch);
}
var_dump($data);
?>
创建收件人后,您现在可以将其添加到列表中。您将获得一个像这样的ID YW1pdGtyYXlAZ21haWwuY29t,它是您的电子邮件ID的base64编码。
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients/YW1pdGtyYXlAZ21haWwuY29t'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.00000000");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
添加后,您可以验证用户是否已添加到列表中
<?php
$url = 'https://api.sendgrid.com/v3/';
$request = $url.'contactdb/lists/12345/recipients?page_size=100&page=1'; //12345 is list_id
// Generate curl request
$ch = curl_init();
$headers =
array("Content-Type: application/json",
"Authorization: Bearer SG.000000");
curl_setopt($ch, CURLOPT_GET, true);
curl_setopt($ch, CURLOPT_URL, $request);
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
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
curl_close($ch);
}
var_dump($data);
?>
注意:最好的方法是创建一个类,因为大多数代码都是重复的。我将为 sendgrid 创建一个包装类,并很快将其发布在此处,并能够完成通过 sendgrid API 实现的所有任务。