PHP Requires Chilkat v11.0.0+
PHP
SendGrid: Save and verify a topic opt-out
See more SendGrid Examples
Use this when a signed-in reader turns off Product updates. Look up the configured group before submitting: SendGrid warns that a nonexistent or deleted group can cause a global suppression instead. Keep the group active while processing preferences. Deleting a marketing contact is not a substitute for recording an opt-out.
Add group suppressions ยท Check specific addresses
Chilkat PHP Downloads
<?php
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();
// Take the address from the authenticated account and the group ID from configuration.
$address = 'reader@example.com';
$http->SetUrlVar('group', '12345');
try {
$http->HttpNoBody('GET', 'https://api.sendgrid.com/v3/asm/groups/{$group}', $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;
}
$groupInfo = new JsonObject();
try {
$groupInfo->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Unexpected response: expected JSON.\n";
exit;
}
if (!$groupInfo->StringOfEquals('name', 'Product updates', true)) {
echo "Unexpected unsubscribe group; no preference was changed.\n";
exit;
}
$addresses = new JsonObject();
$addresses->UpdateString('recipient_emails[0]', $address);
try {
$http->HttpJson('POST', 'https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions', $addresses, 'application/json', $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 != 201) {
echo 'HTTP ', $resp->StatusCode, ': ', $resp->BodyStr, "\n";
exit;
}
try {
$http->HttpJson('POST', 'https://api.sendgrid.com/v3/asm/groups/{$group}/suppressions/search', $addresses, 'application/json', $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;
}
$matches = new JsonArray();
try {
$matches->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
echo "Unexpected response: expected JSON.\n";
exit;
}
if ($matches->Size == 1) {
echo 'Confirmed opt-out: ', $matches->StringAt(0), "\n";
} else {
echo "Opt-out not confirmed. Recheck this group.\n";
}