Amazon SNS: Publish a UTF-8 Message to a Standard Topic
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.
Publishes one text message to a standard topic, with a fixed valid email Subject. Subject must have fewer than 100 characters and no line breaks or control characters. The sample validates a nonempty body and a 256 KiB UTF-8 byte ceiling; it does not set MessageStructure or message attributes. The topic may impose a lower configured limit.
The current topic MaximumMessageSize attribute supports up to 1 MiB, with restrictions on subscription count and supported protocols for values above 256 KiB. The default remains 256 KiB, and message attributes also count toward the limit. This sample's conservative ceiling is not a claim that every SNS topic is limited to 256 KiB. FIFO publishing needs MessageGroupId and appropriate deduplication handling; it is a separate example. A successful response confirms acceptance, not individual delivery or filtering results.
Required IAM action: sns:Publish. Grant only the intended resource access; direct SMS does not have a topic ARN resource. Topic policies and KMS key access can also affect requests.
Chilkat AutoIt Downloads
Local $bSuccess = False
$oStringCompare = ObjCreate("Chilkat.StringBuilder")
; Assumes Chilkat is unlocked. See Global Unlock Sample.
; Private credentials; do not put this file in public web content or source control.
$oCredentials = ObjCreate("Chilkat.JsonObject")
$oCredentials.Strict = True
$bSuccess = $oCredentials.LoadFile("qa_data/aws/sns.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not load private SNS credentials." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("access_key"))
Local $bStringMatch1 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("access_key") <> 1) Or ($bStringMatch1 = True)) Then
ConsoleWrite("Missing or invalid access_key." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oCredentials.StringOf("secret_key"))
Local $bStringMatch2 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("secret_key") <> 1) Or ($bStringMatch2 = True)) Then
ConsoleWrite("Missing or invalid secret_key." & @CRLF)
Exit
EndIf
Local $sRegion = "us-west-2"
$oEndpoint = ObjCreate("Chilkat.StringBuilder")
$oEndpoint.Append("sns.")
$oEndpoint.Append($sRegion)
$oEndpoint.Append(".amazonaws.com")
$oAws = ObjCreate("Chilkat.AuthAws")
$oAws.AccessKey = $oCredentials.StringOf("access_key")
$oAws.SecretKey = $oCredentials.StringOf("secret_key")
$oAws.Region = $sRegion
$oAws.ServiceName = "sns"
$oAws.SignatureVersion = 4
$oRest = ObjCreate("Chilkat.Rest")
$oRest.ConnectTimeoutMs = 20000
$oRest.IdleTimeoutMs = 60000
$oRest.VerboseLogging = False
$bSuccess = $oRest.SetAuthAws($oAws)
If ($bSuccess <> True) Then
ConsoleWrite("Could not configure AWS signing." & @CRLF)
Exit
EndIf
If ($oCredentials.HasMember("session_token") = True) Then
$oStringCompare.SetString($oCredentials.StringOf("session_token"))
Local $bStringMatch3 = $oStringCompare.ContentsEqual("",True)
If (($oCredentials.JsonTypeOf("session_token") <> 1) Or ($bStringMatch3 = True)) Then
ConsoleWrite("session_token must be a nonempty string when supplied." & @CRLF)
Exit
EndIf
EndIf
$oXml = ObjCreate("Chilkat.Xml")
$oXml.Strict = True
Local $sValue
Local $sTopicArn = "arn:aws:sns:us-west-2:123456789012:chilkat-standard-example"
$oTopic = ObjCreate("Chilkat.StringBuilder")
$oTopic.Append($sTopicArn)
$oArnPrefix = ObjCreate("Chilkat.StringBuilder")
$oArnPrefix.Append("arn:aws:sns:")
$oArnPrefix.Append($sRegion)
$oArnPrefix.Append(":")
If ($oTopic.StartsWith($oArnPrefix.GetAsString(),True) <> True) Then
ConsoleWrite("Select an SNS topic ARN in the configured region and commercial AWS partition." & @CRLF)
Exit
EndIf
If ($oTopic.EndsWith(".fifo",True) = True) Then
ConsoleWrite("This example uses a standard topic. FIFO publishing needs group/deduplication handling." & @CRLF)
Exit
EndIf
Local $subject = "Test message from Amazon SNS"
Local $sMessage = "This is a test message from Amazon SNS."
; Check bytes, not characters. This sample chooses a 256 KiB body ceiling.
$oMessageBytes = ObjCreate("Chilkat.BinData")
$bSuccess = $oMessageBytes.AppendString($sMessage,"utf-8")
If ($bSuccess <> True) Then
ConsoleWrite("Could not encode message as UTF-8." & @CRLF)
Exit
EndIf
If (($oMessageBytes.NumBytes = 0) Or ($oMessageBytes.NumBytes > 262144)) Then
ConsoleWrite("Use a nonempty message of at most 262144 UTF-8 bytes for this sample." & @CRLF)
Exit
EndIf
; Explicit certificate verification; keep this Socket alive while Rest uses it.
$oConnection = ObjCreate("Chilkat.Socket")
$oConnection.RequireSslCertVerify = True
$oConnection.MaxReadIdleMs = 60000
$oConnection.MaxSendIdleMs = 60000
$bSuccess = $oConnection.Connect($oEndpoint.GetAsString(),443,True,20000)
If ($bSuccess <> True) Then
ConsoleWrite("TLS connection failed; inspect diagnostics privately." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.UseConnection($oConnection,True)
If ($bSuccess <> True) Then
ConsoleWrite("Could not attach TLS connection." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.ClearAllQueryParams()
If ($bSuccess <> True) Then
ConsoleWrite("Could not clear parameters from the previous request." & @CRLF)
Exit
EndIf
; Build a fresh form for each request; do not retain previous parameters.
; AddQueryParam encodes raw values into the POST body. Do not pre-encode them.
$bSuccess = $oRest.AddQueryParam("Action","Publish")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Action." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("Version","2010-03-31")
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Version." & @CRLF)
Exit
EndIf
; Include temporary credentials in the signed form body on every request.
If ($oCredentials.HasMember("session_token") = True) Then
$bSuccess = $oRest.AddQueryParam("X-Amz-Security-Token",$oCredentials.StringOf("session_token"))
If ($bSuccess <> True) Then
ConsoleWrite("Could not set X-Amz-Security-Token." & @CRLF)
Exit
EndIf
EndIf
$bSuccess = $oRest.AddQueryParam("TopicArn",$sTopicArn)
If ($bSuccess <> True) Then
ConsoleWrite("Could not set TopicArn." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("Subject",$subject)
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Subject." & @CRLF)
Exit
EndIf
$bSuccess = $oRest.AddQueryParam("Message",$sMessage)
If ($bSuccess <> True) Then
ConsoleWrite("Could not set Message." & @CRLF)
Exit
EndIf
Local $sResponseXml = $oRest.FullRequestFormUrlEncoded("POST","/")
If ($oRest.LastMethodSuccess <> True) Then
ConsoleWrite("Request did not complete. Its outcome may be uncertain; reconcile before retrying." & @CRLF)
Exit
EndIf
$bSuccess = $oXml.LoadXml($sResponseXml)
If ($oRest.ResponseStatusCode <> 200) Then
ConsoleWrite("SNS HTTP status: " & $oRest.ResponseStatusCode & @CRLF)
If ($bSuccess = True) Then
$sValue = $oXml.GetChildContent("Error|Code")
If ($oXml.LastMethodSuccess = True) Then
ConsoleWrite("AWS error code: " & $sValue & @CRLF)
EndIf
$sValue = $oXml.GetChildContent("RequestId")
If ($oXml.LastMethodSuccess = True) Then
ConsoleWrite("AWS request ID: " & $sValue & @CRLF)
EndIf
EndIf
; Full messages, headers, and signing diagnostics may contain private data.
Exit
EndIf
If ($bSuccess <> True) Then
ConsoleWrite("Expected a well-formed XML response." & @CRLF)
Exit
EndIf
$oStringCompare.SetString($oXml.Tag)
Local $bStringMatch4 = $oStringCompare.ContentsEqual("PublishResponse",True)
If ($bStringMatch4 <> True) Then
ConsoleWrite("Unexpected SNS response element." & @CRLF)
Exit
EndIf
$sValue = $oXml.GetChildContent("ResponseMetadata|RequestId")
$oStringCompare.SetString($sValue)
Local $bStringMatch5 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch5 = True)) Then
ConsoleWrite("Missing or empty ResponseMetadata|RequestId." & @CRLF)
Exit
EndIf
ConsoleWrite("AWS request ID: " & $sValue & @CRLF)
$sValue = $oXml.GetChildContent("PublishResult|MessageId")
$oStringCompare.SetString($sValue)
Local $bStringMatch6 = $oStringCompare.ContentsEqual("",True)
If (($oXml.LastMethodSuccess <> True) Or ($bStringMatch6 = True)) Then
ConsoleWrite("Missing or empty PublishResult|MessageId." & @CRLF)
Exit
EndIf
ConsoleWrite("Message ID: " & $sValue & @CRLF)
ConsoleWrite("Topic message accepted by SNS; delivery is not confirmed." & @CRLF)