diff --git a/README.md b/README.md index ee57cc8..e17cb25 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,13 @@ $MailChimp->new_batch($batch_id); $result = $Batch->check_status(); ``` +You can also get the errors from your batch: + +```php +$MailChimp->new_batch($batch_id); +$result = $Batch->get_errors(); +``` + When your batch is finished, you can download the results from the URL given in the response. In the JSON, the result of each operation will be keyed by the ID you used as the first argument for the request. Webhooks diff --git a/src/Batch.php b/src/Batch.php index b8a5c87..18f9af3 100644 --- a/src/Batch.php +++ b/src/Batch.php @@ -167,4 +167,53 @@ private function queueOperation($http_verb, $id, $method, $args = null) $this->operations[] = $operation; } + + /** + * Get batch errors + * + * @return bool|mixed|null + * @throws \Exception + */ + public function get_errors() + { + if (!extension_loaded('zip')) { + throw new \Exception('get_errors() method need php-zip extension to be installed'); + } + + $status = $this->check_status(); + + if (!isset($status['response_body_url'])) { + return null; + } + + $url = $status['response_body_url']; + $pathBase = '/tmp/archive_'.sha1(time()); + $pathArchive = $pathBase.'.tar.gz'; + $pathZip = $pathBase.'.zip'; + + file_put_contents( $pathArchive, file_get_contents($url) ); + + $p = new \PharData($pathArchive, \RecursiveDirectoryIterator::SKIP_DOTS); + $p->convertToData(\Phar::ZIP); + + $zip = new \ZipArchive; + $res = $zip->open($pathZip); + if ($res === TRUE) { + $zip->extractTo($pathBase); + $zip->close(); + } + + $dir = scandir($pathBase); + $filename = $dir[2]; + + $data = file_get_contents($pathBase.'/'.$filename); + + $response = json_decode($data, true); + + foreach ($response as $i => $r) { + $response[$i]['response'] = json_decode($r['response'], true); + } + + return $response; + } } diff --git a/src/MailChimp.php b/src/MailChimp.php index 87102de..d57551d 100644 --- a/src/MailChimp.php +++ b/src/MailChimp.php @@ -46,7 +46,7 @@ public function __construct($api_key, $api_endpoint = null) if ($api_endpoint === null) { if (strpos($this->api_key, '-') === false) { - throw new \Exception("Invalid MailChimp API key supplied."); + throw new \Exception("Invalid MailChimp API key `{$api_key}` supplied."); } list(, $data_center) = explode('-', $this->api_key); $this->api_endpoint = str_replace('', $data_center, $this->api_endpoint);