Sample code for 30+ languages & platforms
PHP ActiveX Requires Chilkat v11.6.0+

Amazon SNS: Publish a Batch and Handle Partial Failures

See more Amazon SNS Examples

Uses the current Amazon SNS Query API (Version=2010-03-31) through Chilkat.Rest and AuthAws, with HTTPS, Signature Version 4, and service sns. The API version date remains current. Action and input parameters are URL-encoded into a POST body, avoiding message text and recipient addresses in the URL. Set the actual region once; other AWS partitions need their documented endpoint suffix and ARN partition.

Load private qa_data/aws/sns.json with nonempty string fields access_key, secret_key, and session_token when using temporary credentials. Prefer short-lived role credentials. This sample does not discover profiles, obtain credentials, or refresh them automatically. The session token is included in the signed form body on every request. A Socket explicitly enables TLS certificate verification before passing the connection to Rest.

Checks setup calls, transport completion, HTTP status, XML parsing, result root, and required fields. Normal output includes identifiers, not full messages or headers. Keep detailed diagnostics private. For retryable failures, use bounded backoff with jitter in the application; these examples do not automatically retry writes. A Publish timeout can leave an accepted message and retrying a standard-topic/SMS publish can duplicate it. A returned MessageId confirms SNS acceptance, not subscriber or handset delivery.

Sends two uniquely identified messages (the API allows at most ten). Checks both Successful and Failed collections even on HTTP 200, rejects unknown/duplicate/missing result IDs, and reports SenderFault. No attributes are included; their sizes would also count against the combined limit. Retry only appropriate failed entries with bounded backoff, never the successful entries. A transport timeout or malformed response has uncertain outcomes and can cause duplicates on a standard topic.

Required IAM actions: sns:PublishBatch. Related SQS/KMS permissions are separate.

AWS references: PublishBatch

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?php

$success = 0;

$stringCompare = new COM("Chilkat.StringBuilder");
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Private credentials; do not put this file in public web content or source control.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/sns.json');
if ($success != 1) {
    print 'Could not load private SNS credentials.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
    print 'Missing or invalid access_key.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
    print 'Missing or invalid secret_key.' . "\n";
    exit;
}

$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('sns.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $credentials->stringOf('access_key');
$aws->SecretKey = $credentials->stringOf('secret_key');
$aws->Region = $region;
$aws->ServiceName = 'sns';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$rest->VerboseLogging = 0;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
    print 'Could not configure AWS signing.' . "\n";
    exit;
}

if ($credentials->HasMember('session_token') == 1) {
    $stringCompare->SetString($credentials->stringOf('session_token'));
    $stringMatch3 = $stringCompare->ContentsEqual('',1);
    if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
        print 'session_token must be a nonempty string when supplied.' . "\n";
        exit;
    }

}

$xml = new COM("Chilkat.Xml");
$xml->Strict = 1;

$topicArn = 'arn:aws:sns:us-west-2:123456789012:chilkat-standard-example';
$topic = new COM("Chilkat.StringBuilder");
$topic->Append($topicArn);
$arnPrefix = new COM("Chilkat.StringBuilder");
$arnPrefix->Append('arn:aws:sns:');
$arnPrefix->Append($region);
$arnPrefix->Append(':');
if ($topic->StartsWith($arnPrefix->getAsString(),1) != 1) {
    print 'Select an SNS topic ARN in the configured region and commercial AWS partition.' . "\n";
    exit;
}

if ($topic->EndsWith('.fifo',1) == 1) {
    print 'This example uses a standard topic. FIFO publishing needs group/deduplication handling.' . "\n";
    exit;
}

$firstMessage = 'Order 123 created.';
$secondMessage = 'Order 124 created.';
$payloadBytes = new COM("Chilkat.BinData");
$success = $payloadBytes->AppendString($firstMessage,'utf-8');
if ($success != 1) {
    print 'Could not encode payload.' . "\n";
    exit;
}

$success = $payloadBytes->AppendString($secondMessage,'utf-8');
if ($success != 1) {
    print 'Could not encode payload.' . "\n";
    exit;
}

if (($payloadBytes->NumBytes == 0) or ($payloadBytes->NumBytes > 262144)) {
    print 'This example requires a nonempty payload within 256 KiB; the topic may impose a lower limit.' . "\n";
    exit;
}

//  Explicit certificate verification; keep this Socket alive while Rest uses it.
$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
    print 'TLS connection failed; inspect diagnostics privately.' . "\n";
    exit;
}

$success = $rest->UseConnection($connection,1);
if ($success != 1) {
    print 'Could not attach TLS connection.' . "\n";
    exit;
}

$success = $rest->ClearAllQueryParams();
if ($success != 1) {
    print 'Could not clear parameters from the previous request.' . "\n";
    exit;
}

//  Build a fresh form for each request; do not retain parameters from a previous action.
//  AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
$success = $rest->AddQueryParam('Action','PublishBatch');
if ($success != 1) {
    print 'Could not set Action.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('Version','2010-03-31');
if ($success != 1) {
    print 'Could not set Version.' . "\n";
    exit;
}

//  Include temporary credentials in the signed form body on every request.
if ($credentials->HasMember('session_token') == 1) {
    $success = $rest->AddQueryParam('X-Amz-Security-Token',$credentials->stringOf('session_token'));
    if ($success != 1) {
        print 'Could not set X-Amz-Security-Token.' . "\n";
        exit;
    }

}

$success = $rest->AddQueryParam('TopicArn',$topicArn);
if ($success != 1) {
    print 'Could not set TopicArn.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('PublishBatchRequestEntries.member.1.Id','entry-1');
if ($success != 1) {
    print 'Could not set PublishBatchRequestEntries.member.1.Id.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('PublishBatchRequestEntries.member.1.Message',$firstMessage);
if ($success != 1) {
    print 'Could not set PublishBatchRequestEntries.member.1.Message.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('PublishBatchRequestEntries.member.2.Id','entry-2');
if ($success != 1) {
    print 'Could not set PublishBatchRequestEntries.member.2.Id.' . "\n";
    exit;
}

$success = $rest->AddQueryParam('PublishBatchRequestEntries.member.2.Message',$secondMessage);
if ($success != 1) {
    print 'Could not set PublishBatchRequestEntries.member.2.Message.' . "\n";
    exit;
}

$responseXml = $rest->fullRequestFormUrlEncoded('POST','/');
if ($rest->LastMethodSuccess != 1) {
    print 'Request did not complete. Its outcome may be uncertain; reconcile before retrying.' . "\n";
    exit;
}

$success = $xml->LoadXml($responseXml);
if ($rest->ResponseStatusCode != 200) {
    print 'SNS HTTP status: ' . $rest->ResponseStatusCode . "\n";
    if ($success == 1) {
        $value = $xml->getChildContent('Error|Code');
        if ($xml->LastMethodSuccess == 1) {
            print 'AWS error code: ' . $value . "\n";
        }

        $value = $xml->getChildContent('RequestId');
        if ($xml->LastMethodSuccess == 1) {
            print 'AWS request ID: ' . $value . "\n";
        }

    }

    //  Full messages, headers, and signing diagnostics may contain private data.
    exit;
}

if ($success != 1) {
    print 'Expected a well-formed XML response.' . "\n";
    exit;
}

$stringCompare->SetString($xml->Tag);
$stringMatch4 = $stringCompare->ContentsEqual('PublishBatchResponse',1);
if ($stringMatch4 != 1) {
    print 'Unexpected SNS response element.' . "\n";
    exit;
}

$value = $xml->getChildContent('ResponseMetadata|RequestId');
$stringCompare->SetString($value);
$stringMatch5 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch5 == 1)) {
    print 'Missing or empty ResponseMetadata|RequestId.' . "\n";
    exit;
}

print 'AWS request ID: ' . $value . "\n";
$outcomes = new COM("Chilkat.Hashtable");
$batchIndex = 0;
$failedCount = 0;
$batchIndex = 0;
while (($batchIndex < $xml->NumChildrenAt('PublishBatchResult|Successful'))) {
    $xml->I = $batchIndex;
    $value = $xml->getChildContent('PublishBatchResult|Successful|member[i]|Id');
    $stringCompare->SetString($value);
    $stringMatch6 = $stringCompare->ContentsEqual('',1);
    if (($xml->LastMethodSuccess != 1) or ($stringMatch6 == 1)) {
        print 'Missing or empty PublishBatchResult|Successful|member[i]|Id.' . "\n";
        exit;
    }

    $entryId = $value;
    $stringCompare->SetString($entryId);
    $stringMatch7 = $stringCompare->ContentsEqual('entry-1',1);
    $stringCompare->SetString($entryId);
    $stringMatch8 = $stringCompare->ContentsEqual('entry-2',1);
    if (($stringMatch7 != 1) and ($stringMatch8 != 1)) {
        print 'Unknown batch result ID; outcome requires reconciliation.' . "\n";
        exit;
    }

    if ($outcomes->Contains($entryId) == 1) {
        print 'Duplicate batch result ID; outcome requires reconciliation.' . "\n";
        exit;
    }

    $success = $outcomes->AddStr($entryId,'seen');
    if ($success != 1) {
        print 'Could not track batch result.' . "\n";
        exit;
    }

    $value = $xml->getChildContent('PublishBatchResult|Successful|member[i]|MessageId');
    $stringCompare->SetString($value);
    $stringMatch9 = $stringCompare->ContentsEqual('',1);
    if (($xml->LastMethodSuccess != 1) or ($stringMatch9 == 1)) {
        print 'Missing or empty PublishBatchResult|Successful|member[i]|MessageId.' . "\n";
        exit;
    }

    print 'Successful entry: ' . $entryId . ' / ' . $value . "\n";
    $batchIndex = $batchIndex + 1;
}

$batchIndex = 0;
while (($batchIndex < $xml->NumChildrenAt('PublishBatchResult|Failed'))) {
    $xml->I = $batchIndex;
    $value = $xml->getChildContent('PublishBatchResult|Failed|member[i]|Id');
    $stringCompare->SetString($value);
    $stringMatch10 = $stringCompare->ContentsEqual('',1);
    if (($xml->LastMethodSuccess != 1) or ($stringMatch10 == 1)) {
        print 'Missing or empty PublishBatchResult|Failed|member[i]|Id.' . "\n";
        exit;
    }

    $entryId = $value;
    $stringCompare->SetString($entryId);
    $stringMatch11 = $stringCompare->ContentsEqual('entry-1',1);
    $stringCompare->SetString($entryId);
    $stringMatch12 = $stringCompare->ContentsEqual('entry-2',1);
    if (($stringMatch11 != 1) and ($stringMatch12 != 1)) {
        print 'Unknown batch result ID; outcome requires reconciliation.' . "\n";
        exit;
    }

    if ($outcomes->Contains($entryId) == 1) {
        print 'Duplicate batch result ID; outcome requires reconciliation.' . "\n";
        exit;
    }

    $success = $outcomes->AddStr($entryId,'seen');
    if ($success != 1) {
        print 'Could not track batch result.' . "\n";
        exit;
    }

    $value = $xml->getChildContent('PublishBatchResult|Failed|member[i]|Code');
    $stringCompare->SetString($value);
    $stringMatch13 = $stringCompare->ContentsEqual('',1);
    if (($xml->LastMethodSuccess != 1) or ($stringMatch13 == 1)) {
        print 'Missing or empty PublishBatchResult|Failed|member[i]|Code.' . "\n";
        exit;
    }

    print 'Failed entry: ' . $entryId . ' / ' . $value . "\n";
    $value = $xml->getChildContent('PublishBatchResult|Failed|member[i]|SenderFault');
    $stringCompare->SetString($value);
    $stringMatch14 = $stringCompare->ContentsEqual('',1);
    if (($xml->LastMethodSuccess != 1) or ($stringMatch14 == 1)) {
        print 'Missing or empty PublishBatchResult|Failed|member[i]|SenderFault.' . "\n";
        exit;
    }

    $stringCompare->SetString($value);
    $stringMatch15 = $stringCompare->ContentsEqual('true',1);
    $stringCompare->SetString($value);
    $stringMatch16 = $stringCompare->ContentsEqual('false',1);
    if (($stringMatch15 != 1) and ($stringMatch16 != 1)) {
        print 'Invalid SenderFault value.' . "\n";
        exit;
    }

    print 'Sender fault: ' . $value . "\n";
    $failedCount = $failedCount + 1;
    $batchIndex = $batchIndex + 1;
}

if (($outcomes->Contains('entry-1') != 1) or ($outcomes->Contains('entry-2') != 1)) {
    print 'Missing batch outcomes; reconcile before retrying.' . "\n";
    exit;
}

print 'Failed entries: ' . $failedCount . "\n";
print 'Example completed.' . "\n";

?>