2017-04-19 76 views
0

試圖創建使用Sendgrid API將收件人添加到聯繫人列表中的自定義聯繫人窗體,下面從https://github.com/sendgrid/sendgrid-php/blob/master/examples/contactdb/contactdb.php的例子,目前我有:Sendgrid PHP API V3聯繫人列表更新錯誤

require("sendgrid-php.php"); 

// Send an Email 
$from = new SendGrid\Email(null, "[email protected]"); 
$subject = "Hello World from the SendGrid PHP Library!"; 
$to = new SendGrid\Email(null, "[email protected]"); 
$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("[email protected]"); 
$listResponse = $sg->client->contactdb()->lists()->_($list_id)->recipients()->_($recipient_id)->post(); 
echo $listResponse->statusCode(); 
echo $listResponse->body(); 
echo $listResponse->headers(); 

但我m到處錯誤:

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

回答

0

那麼文檔不說的是,用戶在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', "[email protected]"); 
    $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);