Sample code for 30+ languages & platforms
Delphi DLL Requires Chilkat v11.6.0+

Amazon SNS: Subscribe an HTTPS Notification Endpoint

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.

Replace the placeholder with an HTTPS endpoint you control. SNS sends a confirmation envelope; verify its signature and expected topic before submitting its token with ConfirmSubscription. ReturnSubscriptionArn=false makes pending status explicit. Keep raw delivery disabled when using the signed-envelope verifier. This sample creates the subscription request, not a web server.

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

AWS references: Subscribe

Chilkat Delphi DLL Downloads

Delphi DLL
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
region: PWideChar;
endpoint: HCkStringBuilder;
aws: HCkAuthAws;
rest: HCkRest;
stringMatch3: Boolean;
xml: HCkXml;
value: PWideChar;
responseXml: PWideChar;
topicArn: PWideChar;
topic: HCkStringBuilder;
arnPrefix: HCkStringBuilder;
connection: HCkSocket;
stringMatch4: Boolean;
stringMatch5: Boolean;
stringMatch6: Boolean;

begin
success := False;

stringCompare := CkStringBuilder_Create();
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Private credentials; do not put this file in public web content or source control.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/sns.json');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not load private SNS credentials.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'access_key'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (stringMatch1 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid access_key.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'secret_key'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (stringMatch2 = True)) then
  begin
    Memo1.Lines.Add('Missing or invalid secret_key.');
    Exit;
  end;
region := 'us-west-2';
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'sns.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
aws := CkAuthAws_Create();
CkAuthAws_putAccessKey(aws,CkJsonObject__stringOf(credentials,'access_key'));
CkAuthAws_putSecretKey(aws,CkJsonObject__stringOf(credentials,'secret_key'));
CkAuthAws_putRegion(aws,region);
CkAuthAws_putServiceName(aws,'sns');
CkAuthAws_putSignatureVersion(aws,4);
rest := CkRest_Create();
CkRest_putConnectTimeoutMs(rest,20000);
CkRest_putIdleTimeoutMs(rest,60000);
CkRest_putVerboseLogging(rest,False);
success := CkRest_SetAuthAws(rest,aws);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not configure AWS signing.');
    Exit;
  end;
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
    stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
    if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch3 = True)) then
      begin
        Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
        Exit;
      end;
  end;
xml := CkXml_Create();
CkXml_putStrict(xml,True);

topicArn := 'arn:aws:sns:us-west-2:123456789012:chilkat-standard-example';
topic := CkStringBuilder_Create();
CkStringBuilder_Append(topic,topicArn);
arnPrefix := CkStringBuilder_Create();
CkStringBuilder_Append(arnPrefix,'arn:aws:sns:');
CkStringBuilder_Append(arnPrefix,region);
CkStringBuilder_Append(arnPrefix,':');
if (CkStringBuilder_StartsWith(topic,CkStringBuilder__getAsString(arnPrefix),True) <> True) then
  begin
    Memo1.Lines.Add('Select an SNS topic ARN in the configured region and commercial AWS partition.');
    Exit;
  end;
if (CkStringBuilder_EndsWith(topic,'.fifo',True) = True) then
  begin
    Memo1.Lines.Add('This example uses a standard topic. FIFO publishing needs group/deduplication handling.');
    Exit;
  end;
//  Explicit certificate verification; keep this Socket alive while Rest uses it.
connection := CkSocket_Create();
CkSocket_putRequireSslCertVerify(connection,True);
CkSocket_putMaxReadIdleMs(connection,60000);
CkSocket_putMaxSendIdleMs(connection,60000);
success := CkSocket_Connect(connection,CkStringBuilder__getAsString(endpoint),443,True,20000);
if (success <> True) then
  begin
    Memo1.Lines.Add('TLS connection failed; inspect diagnostics privately.');
    Exit;
  end;
success := CkRest_UseConnection(rest,connection,True);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not attach TLS connection.');
    Exit;
  end;
success := CkRest_ClearAllQueryParams(rest);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not clear parameters from the previous request.');
    Exit;
  end;
//  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 := CkRest_AddQueryParam(rest,'Action','Subscribe');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Action.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Version','2010-03-31');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Version.');
    Exit;
  end;
//  Include temporary credentials in the signed form body on every request.
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
  begin
    success := CkRest_AddQueryParam(rest,'X-Amz-Security-Token',CkJsonObject__stringOf(credentials,'session_token'));
    if (success <> True) then
      begin
        Memo1.Lines.Add('Could not set X-Amz-Security-Token.');
        Exit;
      end;
  end;
success := CkRest_AddQueryParam(rest,'TopicArn',topicArn);
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set TopicArn.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Protocol','https');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Protocol.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'Endpoint','https://notifications.example.com/sns');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set Endpoint.');
    Exit;
  end;
success := CkRest_AddQueryParam(rest,'ReturnSubscriptionArn','false');
if (success <> True) then
  begin
    Memo1.Lines.Add('Could not set ReturnSubscriptionArn.');
    Exit;
  end;
responseXml := CkRest__fullRequestFormUrlEncoded(rest,'POST','/');
if (CkRest_getLastMethodSuccess(rest) <> True) then
  begin
    Memo1.Lines.Add('Request did not complete. Its outcome may be uncertain; reconcile before retrying.');
    Exit;
  end;
success := CkXml_LoadXml(xml,responseXml);
if (CkRest_getResponseStatusCode(rest) <> 200) then
  begin
    Memo1.Lines.Add('SNS HTTP status: ' + IntToStr(CkRest_getResponseStatusCode(rest)));
    if (success = True) then
      begin
        value := CkXml__getChildContent(xml,'Error|Code');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS error code: ' + value);
          end;
        value := CkXml__getChildContent(xml,'RequestId');
        if (CkXml_getLastMethodSuccess(xml) = True) then
          begin
            Memo1.Lines.Add('AWS request ID: ' + value);
          end;
      end;
    //  Full messages, headers, and signing diagnostics may contain private data.
    Exit;
  end;
if (success <> True) then
  begin
    Memo1.Lines.Add('Expected a well-formed XML response.');
    Exit;
  end;
CkStringBuilder_SetString(stringCompare,CkXml__tag(xml));
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'SubscribeResponse',True);
if (stringMatch4 <> True) then
  begin
    Memo1.Lines.Add('Unexpected SNS response element.');
    Exit;
  end;
value := CkXml__getChildContent(xml,'ResponseMetadata|RequestId');
CkStringBuilder_SetString(stringCompare,value);
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch5 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty ResponseMetadata|RequestId.');
    Exit;
  end;
Memo1.Lines.Add('AWS request ID: ' + value);
value := CkXml__getChildContent(xml,'SubscribeResult|SubscriptionArn');
CkStringBuilder_SetString(stringCompare,value);
stringMatch6 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkXml_getLastMethodSuccess(xml) <> True) or (stringMatch6 = True)) then
  begin
    Memo1.Lines.Add('Missing or empty SubscribeResult|SubscriptionArn.');
    Exit;
  end;
Memo1.Lines.Add('Subscription result: ' + value);
Memo1.Lines.Add('Example completed.');

CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkStringBuilder_Dispose(endpoint);
CkAuthAws_Dispose(aws);
CkRest_Dispose(rest);
CkXml_Dispose(xml);
CkStringBuilder_Dispose(topic);
CkStringBuilder_Dispose(arnPrefix);
CkSocket_Dispose(connection);