【问题标题】:Sendgrid PHP API v3 Contact List Update ErrorSendgrid PHP API v3 联系人列表更新错误
【发布时间】:2017-04-19 19:05:28
【问题描述】:

按照https://github.com/sendgrid/sendgrid-php/blob/master/examples/contactdb/contactdb.php 的示例,尝试使用 Sendgrid API 创建自定义联系人表单以将收件人添加到联系人列表中,目前我有:

require("sendgrid-php.php");

// Send an Email
$from = new SendGrid\Email(null, "info@test.com");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "my@email.com");
$content = new SendGrid\Content("text/plain", "Hello, Email!");
$mail = new SendGrid\Mail($from, $subject, $to, $content);

$apiKey = 'API_GOES_HERE';
$sg = new \SendGrid($apiKey);

$list_id = "12345";
$recipient_id = base64_encode("test@email.com");
$listResponse = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post();
echo $listResponse->statusCode();
echo $listResponse->body();
echo $listResponse->headers();

但我得到了错误:

**message":"Recipient ID does not exist"**

【问题讨论】:

    标签: php forms api sendgrid


    【解决方案1】:

    所以文档没有说的是用户必须首先存在于 SendGrid 中才能添加到联系人列表中。

    所以步骤是:

    1. 创建收件人
    2. 向收件人发送电子邮件
    3. 将收件人添加到联系人列表中

    这是我的工作代码,以防万一有人需要,这样你就不会像我那样花几个小时了:

    // Get SendGrid credentials
    require("sendgrid-php.php");
    $apiKey = 'YOUR_API_KEY';
    $sg = new \SendGrid($apiKey);
    
    // Only process POST requests
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
        // Get the form fields and remove whitespace
        $array[0]['first_name'] = strip_tags(trim($_POST['first-name']));
        $array[0]['last_name'] = strip_tags(trim($_POST['last-name']));
        $array[0]['email'] = filter_var(trim($_POST['user-email']), FILTER_SANITIZE_EMAIL);
        $firstName = strip_tags(trim($_POST['first-name']));
        $lastName = strip_tags(trim($_POST['last-name']));
        $recipient = filter_var(trim($_POST['user-email']), FILTER_SANITIZE_EMAIL);  
    
        // Create the recipient in SendGrid (part I was missing)
        $recipientResponse = $sg->client->contactdb()->recipients()->post($array);
    
        // Build the email
        $from = new SendGrid\Email('Company Name', "example@company.com");
        $subject = "Subject";
        $to = new SendGrid\Email(null, $recipient);
        $content = new SendGrid\Content("text/html", YOUR HTML TEMPLATE CODE HERE);
    
        $mail = new SendGrid\Mail($from, $subject, $to, $content);
    
        // Send the email
        $emailResponse = $sg->client->mail()->send()->post($mail);
    
        // And finally add recipient to a contact list
        $list_id = "123456";
        $recipient_id = base64_encode($recipient);
    
        $listResponse = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post($request_body);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 2022-06-14
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2018-05-12
      相关资源
      最近更新 更多