PHP Requires Chilkat v11.0.0+
PHP
SendGrid: Report daily requests, deliveries, bounces, and blocks
See more SendGrid Examples
Retrieve seven completed UTC dates and print one row per date. The counts are account-level aggregates; a day’s delivered count does not identify which messages sent that day were delivered.
Chilkat PHP Downloads
<?php
use Chilkat2\DateTime;
use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonArray;
use Chilkat2\JsonObject;
$success = false;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = false;
$http = new Http();
$http->RequireSslCertVerify = true;
// Supply your API key from protected configuration; AuthToken adds the Bearer prefix.
$http->AuthToken = 'SENDGRID_API_KEY';
$resp = new HttpResponse();
$day = new DateTime();
$day->SetFromCurrentSystemTime();
$day->AddDays(-1);
$http->SetUrlVar('end', $day->GetAsIso8601('YYYY-MM-DD', false));
$day->AddDays(-6);
$http->SetUrlVar('start', $day->GetAsIso8601('YYYY-MM-DD', false));
try {
$http->HttpNoBody('GET', 'https://api.sendgrid.com/v3/stats?start_date={$start}&end_date={$end}&aggregated_by=day', $resp);
} catch (\Chilkat2\Exception $e) {
if ($resp->StatusCode == 0) {
echo $e->getMessage(), "\n";
} else {
echo 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
}
exit;
}
if ($resp->StatusCode != 200) {
echo 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
exit;
}
$days = new JsonArray();
try {
$days->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Unexpected response: expected JSON.\n";
exit;
}
echo "Date,Requests,Delivered,Bounces,Blocks\n";
$row = new JsonObject();
$i = 0;
while ($i < $days->Size) {
$days->ObjectAt2($i, $row);
echo $row->StringOf('date'), ',', $row->IntOf('stats[0].metrics.requests'), ',', $row->IntOf('stats[0].metrics.delivered'), ',', $row->IntOf('stats[0].metrics.bounces'), ',', $row->IntOf('stats[0].metrics.blocks'), "\n";
$i = $i + 1;
}