From 627265b02d4ceb138fd27bcc2e7bcf38781df180 Mon Sep 17 00:00:00 2001 From: Sander Bol Date: Tue, 30 Jul 2013 15:27:20 +0200 Subject: [PATCH] Fix for submitting multiple recipients to a list simultaneously. --- src/SendGridPHP/Connect.php | 13 ++++++++++++- src/SendGridPHP/Newsletter.php | 16 ++++++++++++++-- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/SendGridPHP/Connect.php b/src/SendGridPHP/Connect.php index f8afb18..28d659d 100644 --- a/src/SendGridPHP/Connect.php +++ b/src/SendGridPHP/Connect.php @@ -107,7 +107,18 @@ protected function makeApiCall($url, $postData = NULL, $method = 'POST') { //Set to FALSE to stop cURL from verifying the peer's certificate (needed for local hosts development mostly) if(!$this->_curl_ssl_verify) curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false); - // Tell curl to use HTTP POST + $postData = http_build_query($postData); + + $this->debugCall('DEBUG - Original post querystring: ', urldecode($postData)); + + // Replace numerically indexed arrays, such as data[1], data[2], etc. with data[], data[], data[]. + // This is needed, for instance, when we try to submit multiple email addresses to a List. + // The postdata is url_encoded at this point, so replace using %5B = [, %5D = ]. + $postData = preg_replace('/%5B\d+%5D/', '%5B%5D', $postData); + + $this->debugCall('DEBUG - Replaced post querystring: ', urldecode($postData)); + + // Tell curl to use HTTP POST curl_setopt ( $session, CURLOPT_CUSTOMREQUEST, strtoupper ( $method ) ); // Tell curl that this is the body of the POST curl_setopt ($session, CURLOPT_POSTFIELDS, $postData); diff --git a/src/SendGridPHP/Newsletter.php b/src/SendGridPHP/Newsletter.php index 1465923..5df3fef 100644 --- a/src/SendGridPHP/Newsletter.php +++ b/src/SendGridPHP/Newsletter.php @@ -200,10 +200,22 @@ public function newsletter_lists_delete($list) { public function newsletter_lists_email_add($list , $data) { $url = "newsletter/lists/email/add"; + /** + * SendGrid, in their wisdom, requires that we submit each recipient in the list + * as a separate parameter. + * + * Since PHP does not support multiple params with the same name, we stuff them into an array. + * + * SendGridPHP\Connect's makeApiCall method removes the numerical indexes in the generated querystring. + */ + array_walk($data, function(&$row) { + $row = json_encode($row); + }); + $postData = array( 'list' => $list, - 'data' => json_encode($data), - ); + 'data' => $data, + ); $results = $this->makeApiCall ( $url , $postData );