Overview

Amazon Simple Notification Service (SNS) is a cloud-based service for managing push messages from applications to subscribing endpoints and clients. Amazon SNS allows users to push messages to various services and app via APIs or the AWS Management Console. Once a message is published to a service, the message can be sent multiple times to different recipients.

To get started with Amazon SNS, you first create a topic, which is an access point for subscribers to receive notifications. You publish a message to a topic when you have an update for subscribers. This ensures that Amazon SNS distributes the message to all subscribers.

For more information, see Amazon SNS.

Get started

Install awssns package

Adobe ColdFusion (2021 release) is modularized. By default, the module for AWS SNS is not installed. The first step is to install the SNS package in ColdFusion.

The package for SNS is called awssns.

To install the package awssns, follow the steps below:

  1. Navigate to <CF_HOME>/cfusion/bin.

  2. Enter the command:

    • Windows: cfpm.bat
    • Linux: cfpm.sh
  3. Enter the command, install awssns.

    Wait for the AWS SNS package to get installed.

For more information, see ColdFusion Package Manager.

Get credentials to access AWS SNS

When you interact with AWS, you specify your AWS security credentials to verify your credentials and check whether you have permission to access the resources that you are requesting.

AWS uses the security credentials to authenticate and authorize your requests.

You must get the AWS Access Key ID and the AWS Secret Access Key. For more information, see Access Keys.

Add cloud service credentials and configuration

In ColdFusion (2021 release), there is a method getCloudService() that gives you a handle to create objects for accessing various cloud services.

The syntax of the service handle is as follows:

service=getCloudService(cloudCred,cloudConfig), where:

  • cloudCred: Defines the credentials for the cloud service. It could either be a struct or a string (also known as credential alias).
  • cloudConfig: Defines the cloud service configuration details. It could either be a struct or a string (also known as config alias).

After you've acquired the AWS credentials, you must declare these credentials in one of the following ways. Only then you can use these credentials to create a SNS object, after which you can use the object to make calls to the various SNS methods.

ColdFusion Administrator

Set credentials

In the ColdFusion Administrator, click Data & Services > Cloud Credentials

An alias is a named representation of a cloud service and its configuration details. You can set the config alias through ColdFusion Administrator.

Add cloud credentials
Add cloud credentials

After entering the details, click Add Credential.

Set configuration options

In the ColdFusion Administrator, click Data & Services > Cloud Configuration

Enter the following details, like configuration Alias, Vendor, and the name of the service.

Add cloud configuration
Add cloud configuration options

After adding the configuration options, you may need to add a few more options. You can do so in the next screen. The following are a few options that you may need to add:

  • Request config
  • Client config
  • Proxy settings
  • Retry policy
  • Retry conditions

For more information, see Cloud configuration options.

Create the object

Once you've created the aliases for SNS credential and configuration options, you can create the object by using the cloudService API, and include the following in your CFM. 

snsObject= getCloudService("snsCred", "snsConf")

Application.cfc

You can specify the SNS credentials and configuration options in Application.cfc. For example,

component
{ 
    this.name="AWS_STD_Queue";
    void function onApplicationStart(){
        application.awsCred  = {
                                "alias" : "aws_std_queue",
                                "vendorName" : "AWS",
                                "region" : "us-east-1",
                                "secretAccessKey" : "xxxxxxxxxxxxxxxxx",
                                "accessKeyId" : "xxxxxxxxxxxxxxxx"
                             }
            
        application.snsConf  = {
                                "serviceName" : "SNS"
                             }

        application.sqsConf ={
                                 "serviceName" : "SQS"
                             }        

    }
}

Create the object

snsObject = getCloudService(application.awsCred, application.snsConf)

On CFM page

On a CFM page, you can specify the SNS credentials and configuration options in one of the four methods, specified below:

Credential alias and configuration alias

After you've created the aliases for SNS credential and configuration options, you can use these aliases in the getCloudService handle as shown below:

<cfscript>
  // define the credential and the configuration aliases in the ColdFusion Admin
  sns=cloudService("awsCred","snsConf")
  // code below.
  ...........
</cfscript>

Credential Alias and Struct for configuration options

<cfscript>
    // Using credential alias and struct for service config
    snsConf = {
            "alias":"snsConf",
            "serviceName" : "SNS",
            "clientOverrideConfig":{
                "retryPolicy":{
                  "numRetries":4
                }
            },
            "httpClientConfig":{
                "maxConnections":50
            }
 
    }
    sns= cloudService("snsCred", snsConf)
 
    // code below
    .....................
</cfscript>

Configuration alias and struct for credentials

<cfscript>
    // Using config alias and struct for service credentials
    // sns credentials
    snsCreds={
      "vendorName":"AWS",
      "alias": "snsCred",
      "region":"us-east-2",
      "accessKeyId": "access key",
      "secretAccessKey": "secret access"
    }
    sns= cloudService(snsCreds, "snsConf")
    // code below
    .....................................
</cfscript>

Structs for both credential and configuration options

<cfscript>
  // Using Structs for both cloud credential and config
  snsCred={
    "vendorName":"AWS",
    "alias": "sns_cred_alias",
    "region":"us-east-2",
    "accessKeyId": "access key",
    "secretAccessKey": "secret access key"
  }
 
  snsConf = {
          "alias":"sns_conf_alias",
          "serviceName" : "SNS",
          "clientOverrideConfig":{
              "retryPolicy":{
                "numRetries":4
              }
          },
          "httpClientConfig":{
              "maxConnections":50
          }
 
  }
  sns = cloudService(snsCred, snsConf )
 
  // code below
  ...................................................................
</cfscript>

Admin API

You can also add SNS credentials and configuration options by using the Admin APIs. The methods to add credentials and configuration are available in cloud.cfc.

The examples below demonstrate the usage of the methods addCredential(struct credential) and addServiceConfig(struct config).

Add credentials

<cfscript>
  // Create an object of administrator component and call the login method
  adminObj = createObject("component","cfide.adminapi.administrator")
  adminObj.login("admin")
 
  // Create an object of cloud component
  cloudObj = createObject("component","cfide.adminapi.cloud")
 
  // define credentials struct
  credentialStruct={
    "alias" : "CredSNS",
    "vendorName" : "AWS",
    "region" : "us-east-2",
    "secretAccessKey" : "secret access key",
    "accessKeyId" : "access key"
  }
 
  // add credential credentialStruct
  try{
    cloudObj.addCredential(credentialStruct)
    writeOutput("Credentials added successfully")
  }
  catch(any e){
      writeDump(e)
  }
</cfscript>

Add configuration

<cfscript>
  // Create an object of administrator component and call the login method
  adminObj = createObject("component","cfide.adminapi.administrator")
  adminObj.login("admin")
 
  // Create an object of cloud component
  cloudObj = createObject("component","cfide.adminapi.cloud")
 
  // define configuration struct
  configStruct={
      "alias":"ConfSNS",
      "serviceName":"SNS",
      "clientOverrideConfig":{
          "retryPolicy":{
              "numRetries":4
          }
      },
      "httpClientConfig":{
          "maxConnections":50
      }
  }
 
  // add config configStruct
  try{
    cloudObj.addServiceConfig(configStruct)
    writeOutput("Configuration service added successfully")
  }
  catch(any e){
    writeDump(e)
  }
</cfscript>

CFSetup

You can also set up SNS credential and configuration via the CFSetup configuration utility.

Add cloud credential

add cloudcredential credentialAlias=snscred accesskeyid=<access> secretaccesskey=<secret> region=ap-southeast-1 vendorname=AWS

Set credential

set cloudcredential snscred secretaccesskey=awssecret

Add cloud configuration

add cloudconfiguration serviceName=SNS alias=snsConfig

Set configuration

set cloudconfiguration conf1 alias=conf2

List of SNS APIs

SNSClient APIs SNSTopic APIs SNSSubscription APIs
  1. Struct listTopics();
  2. Struct publish(Map message);
  3. SNSTopic createTopic(String topicName, Map topicCreateOptions);
  4. SNSTopic createTopic(String topicName);
  5. Struct deleteTopic(String topicArn);
  6. SNSSubscription subscribe(Map subscription);
  7. Struct unsubscribe(Object subscription);
  8. Struct setSubscriptionAttributes(Map subscriptionAttributes);
  9. Struct getTopicAttributes(String topicArn);
  10. Struct setTopicAttributes(Map topicAttributes);
  11. Struct tagTopic(String topicArn, Map tags);
  12. Struct untagTopic(String topicArn, Map tags);
  13. Struct listTopicTags(String topicArn);
  14. Struct listTopicSubscriptions(String topicArn);
  15. Struct setSMSAttributes(Map smsAttributes);
  16. Struct getSMSAttributes();
  17. Struct addPermission(String topicArn, Map permission);
  18. Struct removePermission(String topicArn, String permissionLabel);
  19. Struct confirmSubscription(String topicArn, Map subscription);
  20. Struct listTopics(String nextToken);
  21. Struct listTopicSubscriptions(String topicArn, String nextToken);
  22. Struct listSubscriptions();
  23. Struct listSubscriptions(String nextToken);
  24. Struct createPlatformEndpoint(Map platformEndpoint);
  25. Struct deleteEndpoint(String endpointArn);
  26. Struct getEndpointAttributes(String endpointArn);
  27. Struct createPlatformApplication(Map platformApplication);
  28. Struct deletePlatformApplication(String platformApplicationArn);
  29. Struct listTagsForResource(String resourceArn);
  30. Struct optInPhoneNumber(String phoneNumber);
  31. Struct listPhoneNumbersOptedOut();
  32. Struct listPhoneNumbersOptedOut(String nextToken);
  33. Struct checkIfPhoneNumberIsOptedOut(String phoneNumber);
  34. Struct getSubscriptionAttributes(Object subscription);
  1. String getTopicArn();
  2. Struct publish(Map message);
  3. SNSSubscription subscribe(Map subscription);
  4. Struct getAttributes();
  5. Struct setAttributes(Map attributes);
  6. Struct tag(Map tags);
  7. Struct untag(Map tags);
  8. public Struct listTags();
  9. Struct listSubscriptions();
  10. Struct addPermission(Map permission);
  11. Struct removePermission(String permissionLabel);
  12. Struct confirmSubscription(Map subscription);
  13. Struct listSubscriptions(String nextToken);
  1. String getSubscriptionArn();
  2. Struct setAttributes(Map attributes);
  3. Struct getAttributes(Object subscription);

 

Create a topic

In SNS, a topic is a logical access point that helps in communication. In a topic, you can combine multiple endpoints, like, Amazon SQS, HTTPS, or email address. To broadcast messages of a producer to various consumers, you typically create a topic for the producer.

For more information, see Create a topic.

Syntax

createTopic(topicName, topicAttributes)

Parameters

Parameter Description Type Required
topicName The name of the topic to be created. String Yes
topicAttributes

Key-value pairs of the following:

  • DeliveryPolicy: Defines how SNS retries failed deliveries to HTTP/S endpoints.
  • DisplayName: The display name for the topic.
  • Policy: Access policy for your topic. 

The following attribute applies only to server-side-encryption:

  • KmsMasterKeyId: The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. For more information, see Key Terms
Struct No

For more information, see request parameters.

Example

<cfscript>
  sns = getCloudService(application.awsCred, application.snsConf)
  // define topic attributes
	createTopicMetadata = {			
			"tags" = [
        {"key" = "key1","value" = "value1"},
        {"key" = "key2","value" = "value2"}
      ],
			"attributes" = {
					"DisplayName" = "This is a sample display name."
			}
	}	
  try{
    topicResponse = sns.createTopic("NewTopic",createTopicMetadata)
    writeOutput("Successfully created an SNS topic")
    writeDump(topicResponse)
  }
  catch(any e){
    writeDump(e)
  }
</cfscript>

Create a topic with Server-Side Encryption

Server-side encryption (SSE) lets you transmit sensitive data in encrypted topics. SSE protects the contents of messages in Amazon SNS topics using keys managed in AWS Key Management Service (AWS KMS).

SSE encrypts messages as soon as Amazon SNS receives them. The messages are stored in encrypted form and Amazon SNS decrypts messages only when they are sent. For more information, see Protect SNS data with SSE.

When you create a topic in SNS, there is one attribute, KmsMasterKeyId, that you must specify in the topic creation metadata. For more information, see Key Terms. For more examples, see KeyId in the AWS Key Management Service API Reference.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf);	
	// create the topic
    myTopic = sns.createTopic("TopicSSE")
    // set SSE metadata
	setTopicAttribsMetadata = {
		"attributeName" = "KmsMasterKeyId",
		"attributeValue" = "arn:aws:kms:us-east-1:xxxxxxxx:key/xxxxxxxxxxx"
    }
    // set the SSE attributes to the topic
    setTopicAttribsResponse=myTopic.setAttributes(setTopicAttribsMetadata)
    writeDump(setTopicAttribsResponse)
</cfscript>

Get the ARN of a topic

After creating a topic, you can retrieve its Amazon Resource Names (ARN), which will uniquely identify the topic.

For more information, see ARNs.

Syntax

getTopicArn()

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf);	
	// create the topic
    myTopic = sns.createTopic("TopicARN")
    myArn=myTopic.getTopicArn()
    writeOutput("The ARN of the topic is: " & myArn)
</cfscript>

Delete a topic

When you no longer need a subscription or topic, you must first unsubscribe from the topic before you can delete the topic.

For more information, see Delete subscription and topic.

Syntax

deleteTopic(topicArn)

Parameters

Parameter Description Type Required
topicArn The ARN of the topic that you want to delete.
String Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("DeleteTopic")
    // get topic ARN
	topicArn = topic.getTopicArn()
    try{
        // delete topic
        deleteTopicResponse = sns.deleteTopic(topicArn)
        writeOutput("Topic deleted successfully")
        writeDump(deleteTopicResponse)
    }
	catch(any e){
        writeDump(e)
    }	
</cfscript>

List topics

Get a list of all the topics that were created. Each function call returns a list of up to 100 topics. If there are more topics, a NextToken is also returned. Use the NextToken parameter in a ListTopics call to get further results.

For more information, see ListTopics.

Syntax

listTopics(nextToken)

Parameters

Parameter Description Type Required
nextToken The token returned by the previous ListTopics call.
String No

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf);	
    // list all topics
    topicObj = snsObj.listTopics();
    writeDump(topicObj)	
    // get nextToken
    nextTokenVal = topicObj.nextToken; 
    // list all topics with nextToken
    listNextTopicObj = snsObj.listTopics(nextTokenVal)
    writeDump(listNextTopicObj)
</cfscript>

Set topic attributes

Set an attribute of the topic to a new value.

For more information, see SetTopicAttributes.

Syntax

setTopicAttributes(topicAttributes)

Parameters

Parameter Description Type Required
topicAttributes

Key-value pairs of the following:

  • DeliveryPolicy: Defines how SNS retries failed deliveries to HTTP/S endpoints.
  • DisplayName: The display name for the topic.
  • Policy: Access policy for your topic. 

The following attribute applies only to server-side-encryption:

  • KmsMasterKeyId: The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. For more information, see Key Terms
Struct Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // define topic attributes
	createTopicMetadata = {			
		"tags" = [
            {"key" = "key1","value" = "value1"},
            {"key" = "key2","value" = "value2"}
        ],
		"attributes" = {
			"DisplayName" = "This is a sample display name."
		}
    }
    
    // create topic
    topicObj=sns.createTopic("NewTopic",createTopicMetadata)

    // get topic Arn
    topicArn = topicObj.getTopicArn()
    // metadata for set attributes
    setTopicAttribsMetadata = { 
        "topicArn"= topicArn,
        "attributeName" = "DisplayName",
        "attributeValue" = "value"
    }
    try{
        setTopicAttrResponse = sns.setTopicAttributes(setTopicAttribsMetadata)
        writeOutput("Topic attributes set successfully")
        writeDump(setTopicAttrResponse)
    }
    catch(any e){
        writeDump(e)
    }
</cfscript>

Get topic attributes

Retrieve all of properties of a topic. 

For moe information, see GetTopicAttributes.

Syntax

getTopicAttributes(topicARN)

Parameters

Parameter Description Type Required
topicArn The ARN of the topic, whose attributes you want to retrieve. String Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    
    // define topic attributes
	createTopicMetadata = {			
		"tags" = [
            {"key" = "key1","value" = "value1"},
            {"key" = "key2","value" = "value2"}
        ],
		"attributes" = {
			"DisplayName" = "This is a sample display name."
		}
    }
    
    // create topic
    topicObj=sns.createTopic("TopicAttributes",createTopicMetadata)

    // get topic Arn
    topicArn = topicObj.getTopicArn()
    
    // metadata for set attributes
    setTopicAttribsMetadata = { 
        "topicArn"= topicArn,
        "attributeName" = "DisplayName",
        "attributeValue" = "value"
    }
    
    // set topic attributes
    sns.setTopicAttributes(setTopicAttribsMetadata)

    // get topic attributes
    getTopicAttributeResponse=sns.getTopicAttributes(topicArn)
    
    writeDump(getTopicAttributeResponse)
</cfscript>

Tag a topic

Track your Amazon SNS resources (for example, resource tracking) by adding, removing, and listing metadata tags for Amazon SNS topics.

For more information, see AWS SNS tags.

Syntax

tagTopic(topicArn,tags)

Parameters

Parameter Description Type Required
topicArn The ARN of the topic, which you want to add tags. String Yes
tags The list of tags to add to the topic.
Struct Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic			
    topic = sns.createTopic("TagTopic")
    // get topic ARN
    topicArn= topic.getTopicArn()
    // set tag metadata
	tagTopicMetadata = {				
		"tags" = [
			{"key" = "Team","value" = "Development"},
			{"key" = "Environment","value" = "Production"}
		]
    }
    // tag the topic	
    try{
        tagTopicResponse = sns.tagTopic(topicArn,tagTopicMetadata)
        writeOutput("Topic has been tagged successfully")
        writeDump(tagTopicResponse)
    }
    catch (any e){
        writeDump(e)
    }
</cfscript>

List topic tags

List all tags of a specified topic.

For more information, see List tags of a topic.

Syntax

listTopicTags(topicArn)

Parameters

Parameter Description Type Required
topicArn The ARN of the topic whose tags you want to list.
String Yes

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("UntagTopic")
    // get topic ARN
    topicArn=topic.getTopicArn()
    // tag metadata
    tagTopicMetadata = {				
        "tags" = [
            {"key" = "Team","value" = "Development"},
            {"key" = "Environment","value" = "Production"}
        ]
    }
    // tag topic
    sns.tagTopic(topicArn,tagTopicMetadata)
    // list topic tags
    res=sns.listTopicTags(topicArn)
    writeOutput("The list of tags are:")
    writeDump(res.tags)
</cfscript>

Untag a topic

Remove tags from the specified Amazon SNS topic.

For more information, see Untag a topic.

Syntax

untagTopic(topicArn,tags)

Parameters

Parameter Description Type Required
topicArn The ARN of the topic, from which you want to remove tags. String Yes
tags The list of tag keys to remove from the specified topic.
Array Yes

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("UntagTopic")
    // get topic ARN
    topicArn=topic.getTopicArn()
    // tag metadata
    tagTopicMetadata = {				
        "tags" = [
            {"key" = "Team","value" = "Development"},
            {"key" = "Environment","value" = "Production"}
        ]
    }
    // tag topic
    sns.tagTopic(topicArn,tagTopicMetadata)
    // untag metadata
    untagTopicMetadata = { 
        "tagKeys" = ["Team"]
    }
    try{
        res = sns.untagTopic(topicArn,untagTopicMetadata)
        writeOutput("Topic untagged successfully" & "<br/>")
        writeOutput("Tags left after untagging are:")
        writeDump(topic.listTags().tags)
    }
    catch(any e){
        writeDump(e)
    }
</cfscript>

Subscribe to a topic

When you subscribe an endpoint to a topic and confirm the subscription, the endpoint begins to receive messages published to the associated topic. To receive messages published to a topic, you must subscribe an endpoint (such as AWS Lambda, Amazon SQS, HTTP/S, or an email address) to the topic. When you subscribe an endpoint to a topic and confirm the subscription, the endpoint begins to receive messages published to the associated topic.

For more information, see Subscribe an endpoint to an SNS topic.

Syntax

subscribe(subscription)

Parameters

Parameter Description Type Required
subscription

Attributes map

Key-value pairs of the following:

  • DeliveryPolicy: Defines how SNS retries failed deliveries to HTTP/S endpoints.
  • FilterPolicy: The JSON object that defines the messages that your subscribe will receive.
  • RawMessageDelivery: When TRUE, your subscriber gets only the raw version of a message, without any formatting. 
  • RedrivePolicy: When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue.

Endpoints

The following endpoints are supported:

  • http/https
  • email
  • email-json
  • sms
  • sqs
  • application
  • lambda

Protocol

The following protocols are supported:

  • http/https
  • email
  • email-json
  • sms
  • sqs
  • application
  • lambda

ReturnSubscriptionArn: When TRUE, returns the subscription ARN with the subscription request.

TopicARN: The ARN of the topic you want to subscribe to.

 

Struct Yes

For more information, see request parameters.

Example 1

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    topic = sns.createTopic("SMSSubscription");
	subscribeMetadata = {
	   "topicArn" = topic.getTopicArn(),
	   "endpoint" = "<your phone number>",
	   "protocol" = "sms"
    }
    try{
        subscription= topic.subscribe(subscribeMetadata)
        writeOutput("Subscribed to the topic successfully")
        writeDump(subscription)
    }
    catch (any e){
        writeDump(e)
    } 
</cfscript>

Example 2

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    topic = sns.createTopic("EmailSubscription");
	subscribeMetadata = {
	   "topicArn" = topic.getTopicArn(),
	   "endpoint" = "johndoe@email.com",
	   "protocol" = "email"
    }
    try{
        subscription= topic.subscribe(subscribeMetadata)
        writeOutput("Subscribed to the topic successfully")
        writeDump(subscription)
    }
    catch (any e){
        writeDump(e)
    } 
</cfscript>

Example 3

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    topic = sns.createTopic("EmailSubscription");
	subscribeMetadata = {
	   "topicArn" = topic.getTopicArn(),
	   "endpoint" = "https://coldfusion.adobe.com/",
	   "protocol" = "https"
    }
    try{
        subscription= topic.subscribe(subscribeMetadata)
        writeOutput("Subscribed to the topic successfully")
        writeDump(subscription)
    }
    catch (any e){
        writeDump(e)
    } 
</cfscript>

Confirm subscription

Using this function, you can verify if an endpoint owner can receive messages by validating the token sent to the endpoint by an earlier Subscribe action. If the token is valid, the action creates a new subscription and returns its Amazon Resource Name (ARN).

For more information, see ConfirmSubscription.

Syntax

confirmSubscription(topicArn, subscription)

Parameters

Parameter Description Type Required

AuthenticateOnUnsubscribe

Indicates whether unsubscription to a subscription requires authentication.

String No

Token

The token sent to an endpoint.

String Yes

TopicArn

The ARN of the topic for which you wish to confirm a subscription.

String Yes

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    topicObj = snsObj.createTopic("confirmSubscription");
	topicARN = topicObj.getTopicArn();
	subscribeMetadata = {
		"topicArn" = topicARN,
		"endpoint" = "john@example.com",
        "protocol" = "email"			
    }
	// manually fetch token value from email
	tokenVal = "token value";
	metadata = {
		"token" = tokenVal
	}
    try{
        confirmationObj = snsObj.confirmSubscription(topicARN,metadata)
        writeOutput("Subscription confirmed successfully")
        writeoutput(confirmationObj.subscriptionArn)
    }
    catch(any e){
        writeDump(e)
    }			
</cfscript>

Unsubscribe from a topic

Delete a subscription. Only the owner of the subscription or the topic's owner can unsubscribe from the topic.

For more information, see Unsubscribe.

Syntax

unsubscribe(subscriptionArn)

Parameters

Parameter Description Type Required
subscriptionArn The ARN of the subscription to be deleted.
String Yes

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create the topic
    topic = sns.createTopic("UnsubTopic")
    // subscription metadata
    subscribeMetadata = {
        "topicArn" = topic.getTopicArn(),
        "endpoint" = "johndoe@email.com",
        "protocol" = "email"
    }
    // subscribe to the topic
    subscription = topic.subscribe(subscribeMetadata)
    // get subscription Arn
    //subscriptionArn = subscription.getSubscriptionArn()
    // After confirming subscription, you get a subscription Arn
    subscriptionArn="arn:aws:sns:us-east-1:534385124010:UnsubTopic:6b35449d-90e7-4e63-aaf6-990da9cd1a51"
    try{
        unsubResponse= sns.unsubscribe(subscriptionArn)
        writeOutput("Unsubscribed from topic successfully")
        writeDump(unsubResponse)
    }
    catch(any e){
        writeDump(e)
    }
</cfscript>

List subscriptions by topic

Return a list of the subscriptions to a specific topic.

For more information, see ListSubscriptionsByTopic.

Syntax

listTopicSubscriptions(topicArn)

listTopicSubscriptions(String topicArn, String nextToken)

Parameters

Parameter Description Type Required
topicArn The Arn of the topic from which you want to unsubscribe. String Yes
nextToken
The token returned by the previous call.
String No

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create the topic
    topic = sns.createTopic("EmailSubscription")
    // get topic ARN
    topicARN = topic.getTopicArn()
    // set subscription metadata
	subscribeMetadata = {
	   "topicArn" = topicARN,
	   "endpoint" = "john@example.com",
	   "protocol" = "email"
    }
    // subscribe to the topic
    subscription= topic.subscribe(subscribeMetadata)
    // get the subscriptions
    resp=sns.listTopicSubscriptions(topicARN)
    writeOutput("List of subscriptions:")
    writeDump(resp.subscriptions)
</cfscript>

List subscriptions

Display a list of the requester's subscriptions. Each function call returns a list of 100 subscriptions.

For more information, see List Subscriptions.

Syntax

listSubscriptions(nextToken)

Parameters

Parameter Description Type Required
nextToken The token returned by the previous ListSubscriptions call.
String No

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    // create the topic
    topicObj = snsObj.createTopic("ListSubs")
    // get topic ARN
    topicARN = topicObj.getTopicArn()
    // set subscription metadata
	subscribeMetadata = {
	   "topicArn" = topicARN,
	   "endpoint" = application.emailId,
	   "protocol" = "email"
    }
    // subscribe to the topic
    topicObj.subscribe(subscribeMetadata)
    // list subscriptions without nextToken parameter
    subsObj = snsObj.listSubscriptions()
    // get nextToken
    nextToken=subsObj.nextToken
    // list subscriptions with nextToken parameter
    ntObj=snsObj.listSubscriptions(nextToken)
    writeDump(ntObj)
</cfscript>

Set subscription attributes

Set an attribute of the subscription to a new value.

For more information, see SetSubscriptionAttributes.

Syntax

setSubscriptionAttributes(subscriptionAttributes)

Parameters

Parameter Description Type Required
subscriptionAttributes
  • DeliveryPolicy: Defines how SNS retries failed deliveries to HTTP/S endpoints.
  • FilterPolicy: The JSON object that defines the messages that your subscribe will receive.
  • RawMessageDelivery: When TRUE, your subscriber gets only the raw version of a message, without any formatting. 
  • RedrivePolicy: When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue.
Struct Yes
attributeValue The new value for the attribute in JSON format.
String No
subscriptionArn The ARN of the subscription to modify.
String Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    topic = sns.createTopic("SubscriptionAttrib")
    // get topic ARN
    topicARN = topic.getTopicArn()
    // set subscription metadata
	subscribeMetadata = {
	   "topicArn" = topicARN,
	   "endpoint" = "john@email.com",
	   "protocol" = "email"
    }
    // subscribe to the topic
    subscription= topic.subscribe(subscribeMetadata)
    // get the subscription ARN
    // subsARN = subscription.getSubscriptionArn()
    // After confirming subscription, you get a subscription Arn
    subsARN="arn:aws:sns:us-east-1:534385124010:SubscriptionAttrib:735e692e-b085-48a6-ac01-42a1211bf86d"
    // set filter policy
    filterPolicy = {
        "OrderType" = ["Retail"]
    }
    // set subscription attribute metadata
    setSubscribeMetadata = {
        "attributeName" = "FilterPolicy",
        "attributeValue" = serializeJson(filterPolicy),							
        "subscriptionArn"=subsARN
    }
    try{
        setSubsObj = sns.setSubscriptionAttributes(setSubscribeMetadata)
        writeOutput("Attributes have been set successfully")
        writeDump(setSubsObj)
    }
    catch(any e){
        writeDump(e)
    }
</cfscript>

Get subscription attributes

Retrieve the properties of a subscription.

For more information, see getSubscriptionAttributes.

Syntax

getSubscriptionAttributes(subscriptionArn)

Parameters

Parameter Description Type Required
subscriptionArn The ARN of the subscription whose properties you want to return.
String Yes

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    topic = sns.createTopic("GetSubscriptionAttrib")
    // get topic ARN
    topicARN = topic.getTopicArn()
    // set subscription metadata
	subscribeMetadata = {
	   "topicArn" = topicARN,
	   "endpoint" = "john@example.com",
	   "protocol" = "email"
    }
    // subscribe to the topic
    subscription= topic.subscribe(subscribeMetadata)
    // get the subscription ARN
    // subsARN = subscription.getSubscriptionArn()
    // After confirming subscription, you get a subscription Arn
    subsARN="arn:aws:sns:us-east-1:534385124010:GetSubscriptionAttrib:482d04e0-f5d6-4f4e-b6f9-9f721212a5c4"
    // set filter policy
    filterPolicy = {
        "OrderType" = ["Retail"]
    }
    // set subscription attribute metadata
    setSubscribeMetadata = {
        "attributeName" = "FilterPolicy",
        "attributeValue" = serializeJson(filterPolicy),							
        "subscriptionArn"=subsARN
    }
    // set subscription attributes
    sns.setSubscriptionAttributes(setSubscribeMetadata)
    // get subscription attributes
    getSubsObj = sns.getSubscriptionAttributes(subsARN)
    writeOutput("The attributes are:")
    writeDump(getSubsObj.attributes)
</cfscript>

Publish messages to a topic

When the message is published, Amazon SNS attempts to deliver the message to every endpoint (such as AWS Lambda, Amazon SQS, HTTP/S, or an email address) subscribed to the topic.

For more information, see Publish a message to a topic.

Syntax

publish(Struct message)

Parameters

Parameter Description Type Required
message

The message you want to send.

SMS messages

  • Must be UTF-8 encoded strings and at most 256 KB in size.
  • Must contain 140 characters.
  • Others (see request parameters)

JSON messages

  • Empty values are allowed.
  • Duplicate keys are ot allowed.
  • Others (see request parameters)
String Yes
messageAttributes Message attributes for Publish action. For more information, see Message attribute values.
Struct No
messageStructure Set MessageStructure to json if you want to send a different message for each protocol. Valid value is json.
String No
phoneNumber The phone number to which you want to deliver an SMS message.
String No
subject The subject line of the message. String No
topicArn The topic you want to publish to.
String No

For more information, see request parameters.

Example 1

student.json

{
    "student": 
    [ 
      { 
          "id":"01", 
          "name": "Tom", 
          "lastname": "Price" 
      }, 
      
      { 
          "id":"02", 
          "name": "Nick", 
          "lastname": "Thameson" 
      } 
   ],
   "default" : "sample default JSON message"
}

publish.cfm

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("PubMessageJSON")
    // get topic Arn
    topicARN = topic.getTopicArn()
    subscribeMetadata = {
        "topicArn" = topicARN,
        "endpoint" = "john@example.com",
        "protocol" = "email"
    }
    subscriptionObj = topic.subscribe(subscribeMetadata);
	studentFile = fileRead(expandPath('student.json'));
		// "messageStructure" = "json" is defined then only default msg will be published
	publishMetadata = {
		"messageBody" = studentFile,
		"messageStructure" = "json"
	}
    
    try{
        publishResponse = topic.publish(publishMetadata)
        writeOutput("Message published successfully")
        writeDump(publishResponse)
    }
    catch(any e){
        writeOutput("Failed to publish message")
        writeDump(e)
    }
</cfscript>

Example 2

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("PubMessageSMS")
    // get topic Arn
    topicARN = topic.getTopicArn()
    subscribeMetadata = {
        "topicArn" = topicARN,
        "endpoint" = "<your phone number>",
        "protocol" = "sms"
    }
    subscriptionObj = topic.subscribe(subscribeMetadata);
	studentFile = fileRead(expandPath('student.json'));
		// "messageStructure" = "json" is defined then only default msg will be published
	publishMetadata = {
		"messageBody" = studentFile,
		"messageStructure" = "json"
	}
    
    try{
        publishResponse = topic.publish(publishMetadata)
        writeOutput("Message published successfully")
        writeDump(publishResponse)
    }
    catch(any e){
        writeOutput("Failed to publish message")
        writeDump(e)
    }
</cfscript>

Example 3

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    // create a topic
    topic = sns.createTopic("PubMessageEmail")
    // get topic Arn
    topicARN = topic.getTopicArn()
    // set subscribe metadata
    subscribeMetadata = {
        "topicArn" = topicARN,
        "endpoint" = "john@email.com",
        "protocol" = "email"
    }
    subscriptionObj = topic.subscribe(subscribeMetadata)
    // publish metadata
    publishMetadata = {
        "messageBody" = "Publish Email message from John",
        "messageStructure" = "String",
        "Subject"= "Subscription Notification"						
    }
    try{
        publishResponse = topic.publish(publishMetadata)
        writeOutput("Message published sucessfully")
        writeDump(publishResponse)
    }
    catch(any e){
        writeOutput("Failed to publish message")
        writeDump(e)
    }
</cfscript>

Set SMS attributes

Set the default settings for sending SMS messages and receiving daily SMS usage reports.

For more information, see Set SMS Attributes.

Syntax

setSMSAttributes(smsAttributes)

Parameters

Parameter Description Type Required
smsAttributes

Key-value pair of the following:

  • MonthlySpendLimit: The maximum amount in USD that you want to spend each month for sending SMS messages.
  • DeliveryStatusIAMRole: The ARN of the IAM role that allows Amazon SNS to write SMS delivery logs.
  • DeliveryStatusSuccessSamplingRate: The percentage of successful SMS deliveries for which Amazon SNS will write logs.
  • DefaultSenderID: The sender on the receiving device.
  • DefaultSMSType: The type of SMS message that you will send by default. The following values are supported:
    • Promotional
    • Transactional
  • UsageReportS3Bucket: The name of the Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. The report is a CSV and contains the following fields:
    • Time that the message was published (in UTC)
    • Message ID
    • Destination phone number
    • Message type
    • Delivery status
    • Message price (in USD)
    • Part number
Struct Yes

For more information, see request parameters.

Example

<cfscript>
    sns = getCloudService(application.awsCred, application.snsConf)
    smsAttributes ={ "
        attributes":{
            "DeliveryStatusIAMRole":"",
            "DeliveryStatusSuccessSamplingRate":"",
            "DefaultSenderID":"",
            "DefaultSMSType":"Transactional",
            "UsageReportS3Bucket":"",
            "MonthlySpendLimit":2
        }
    }
    res =sns.setSMSAttributes(smsAttributes)
    writeDump(res)
</cfscript>

Get SMS attributes

Retrieve the settings, that were defined in the earlier section,  for sending SMS messages from your account.

For more information, see Get SMS Attributes.

Syntax

getSMSAttributes(attribute)

Parameters

Parameter Description Type Required
attribute Attribute that you'd set in setSMSAttributes, for which you want to get the value. Array of string No

Example

<cfscript>
		sns = getCloudService(application.awsCred, application.snsConf)
		// get the SMS attributes
	   	response=sns.getSMSAttributes()
	   	writeDump(response)
	   	writeoutput(response.attributes.DefaultSMSType)
</cfscript> 	

Add permission

This function adds a permission to a topic's access control policy, granting access for the specified AWS accounts to the specified actions.

For more information, see AddPermisison.

Syntax

addPermission(String topicArn, Struct permission)

Parameters

Parameter Description Type Required

label

Unique Id for the policy.

String Yes

actions

The actions that users can execute.

Array of strings Yes

awsaccountIds

The AWS account IDs of the users who will be granted access to the specified actions.

Array of strings Yes

topicArn

The ARN of the topic whose access control policy you wish to modify.

String Yes

Example

<cfscript>
    snsObj = cloudService(application.awsCred, application.snsConf)
    // create a topic
    topicObj = snsObj.createTopic("AddPermission")	
    // Add permission struct
    addPermissionAttribute = {							     
        "label" : "NewPermission",
        "actions": ["Publish"],
        "awsaccountIds": ["xxxxxxxxxxxx"]	
    };
    res = snsObj.addPermission(topicArn,addPermissionAttribute)
    writeDump(res)
    writeoutput(res.sdkHttpResponse.statusCode)
</cfscript>

Remove permission

This function removes a permission from a policy.

For more information, see RemovePermission.

Syntax

removePermission(String topicArn, String permissionLabel)

Parameters

Parameter Description Type Required

permissionLabel

Unique Id of the statement to be removed.

String Yes

topicArn

The ARN of the topic whose access control policy that you want to remove.

String Yes

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    // topic arn
    topicArn="arn:aws:sns:us-east-1:xxxxxxxxxxx:AddPermission"
    label = "NewPermission"
    try{
        res = snsObj.removePermission(topicArn,label)
        writeOutput("Permission removed successfully")
        writeDump(res)
    }
	catch(any e){
        writeDump(e)
    }
</cfscript>

Create platform application

Using this function, you can create an application for a push notification service, such as, Firebase Cloud Messaging. You must specify PlatformPrincipal and PlatformCredential attributes when using the CreatePlatformApplication action.

For more information, see CreatePlatformApplication.

Syntax

createPlatformApplication(Struct platformApplication)

Parameters

Parameter Decription Type Required

attributes

Struct containing the following keys:

  • PlatformCredential
  • PlatformPrincipal
  • EventEndpointCreated
  • EventEndpointDeleted
  • EventEndpointUpdated
  • EventDeliveryFailure
  • SuccessFeedbackRoleArn
  • SuccessFeedbackSampleRate

For more information, see Platform application attributes.

Struct Yes

name

The name of the application.

String Yes

platform

The following platforms are supported:

  • ADM (Amazon Device Messaging)
  • APNS (Apple Push Notification Service)
  • APNS_SANDBOX
  • GCM (Firebase Cloud Messaging)
String Yes

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    platformMetadata ={
        "attributes" : {
                        "PlatformCredential": application.GCMServerKey,
                        "PlatformPrincipal":""
                       },
        "name" : "CFgcmpushapp",
        "platform" : "GCM"
      }				
    resp = snsObj.createPlatformApplication(platformMetadata);
    writeDump(resp)
    writeoutput(resp.platformApplicationArn)
</cfscript>

Delete platform application

Delete a platform application object for one of the supported push notification services, such as APNS and GCM.

For more information, see Using Amazon SNS Mobile Push Notifications.

Syntax

deletePlatformApplication(platformApplicationArn)

Parameters

Parameter Description Type Required
PlatformApplicationArn
PlatformApplicationArn of platform application object to delete.
String Yes

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    // create the platform application
    platformMetadata ={
        "attributes" : {
                        "PlatformCredential": application.GCMServerKey,
                        "PlatformPrincipal":""
                       },
        "name" : "PushAppForCF",
        "platform" : "GCM"
      }				
    resp = snsObj.createPlatformApplication(platformMetadata)
    // get the platform ARN
    platformArn=resp.platformApplicationArn
    // delete the platform application
    try{
        deletePltAppRes = snsObj.deletePlatformApplication(platformArn)
        writeOutput("Platform application deleted successfully")
        writeDump(deletePltAppRes)
    }
    catch(any e){
        writeDump(e)
    }
</cfscript>

Create platform endpoint

Create an endpoint for a device and/or mobile app on a push notification service, such as GCM (Firebase Cloud Messaging) or APNS. This function requires the PlatformApplicationArn that is returned from a CreatePlatformApplication call. You can use the ARN to send a message to a device or an app or subscribe to a topic. If the requester already owns an endpoint with the same device token and attributes, the ARN is returned without creating an endpoint. 

For more information, see Using Amazon SNS Mobile Push Notifications.

Syntax

createPlatformEndpoint(Struct platformEndpoint)

Parameters

Parameter Description Type Required
attributes

Key-value pair of the following:

  • CustomUserData: The user data associated with the endpoint.
  • Enabled: Flag that enables/disables delivery to the endpoint.
  • Token: This is the device token.

For more information, see endpoint attributes.

Struct Yes

PlatformApplicationArn

The platform application ARN obtained from a CreatePlatformApplication call.

String Yes

Token

Unique identifier created by the notification service for an app on a device.

String Yes

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    // platform endpoint struct
    platformMetadata ={
        "PlatformApplicationArn" : application.PlatformApplicationArn,
        "Token" : application.FCMToken
    }
    createResp = snsObj.createPlatformEndpoint(platformMetadata)
    writeDump(createResp)	
</cfscript>

Delete an endpoint

Delete an endpoint for a device and mobile app from Amazon SNS. When you delete an endpoint that also subscribes to a topic, then you must also unsubscribe the endpoint from the topic.

For more information, see Using Amazon SNS Mobile Push Notifications.

Read the official DeleteEndpoint docs for more information.

Syntax

deleteEndpoint(endpointArn)

Parameters

Parameter Description Type Required
endpointArn
EndpointArn of endpoint to delete.
String Yes

For more information, see request parameters.

Example

<cfscript>
    snsObj = getCloudService(application.awsCred, application.snsConf)
    // platform endpoint struct
    platformMetadata ={
        "PlatformApplicationArn" : application.PlatformApplicationArn,
        "Token" : application.FCMToken
    }
    createResp = snsObj.createPlatformEndpoint(platformMetadata)
    // get endpoint arn
    endpointArn = createResp.endpointArn;
    try{
        deleteResp= snsObj.deleteEndpoint(endpointArn)
        writeOutput("Endpoint deleted successfully")
        writeDump(deleteResp)
    }
	catch(any e){
        writeDump(e)
    }
</cfscript>

Get endpoint attributes

Get the attributes of an endpoint for a device on one of the push notification services, such as GCM (Firebase Cloud Messaging) and APNS.

For more information, see Get endpoint attributes.

Syntax

getEndpointAttributes(endpointArn)

Parameters

Parameter Description Type Required
endpointArn Endpoint ARN to get the attributes of. String Yes

For more information, see request parameters.

Example

<cfscript>
		snsObj = getCloudService(application.awsCred, application.snsConf);
		platformMetadata ={
							"PlatformApplicationArn" : application.PlatformApplicationArn,
							"Token" : application.FCMToken
						  }				
		createResp = snsObj.createPlatformEndpoint(platformMetadata);		
		endpointArn = createResp.endpointArn;
		getResp = snsObj.getEndpointAttributes(endpointArn);	
		//writedump(getResp);
		writeoutput(getResp.attributes.Enabled);
</cfscript>

Opt in phone number

This function enables you to choose a phone number to send SMS messages to.

For more information, see OptInPhoneNumber.

Syntax

optInPhoneNumber(phoneNumber)

Parameters

Parameter Description Type Required
phoneNumber The phone number to opt in.
String Yes

For more information, see request parameters.

Example

<cfscript>
	snsObj = getCloudService(application.awsCred, application.snsConf);	
	optInResp = snsObj.optInPhoneNumber(application.phoneNum);
	writeoutput(optInResp.sdkHttpResponse.statusCode);		
</cfscript>

List phone numbers opted out

Get a list of phone numbers, where you can no longer send SMS messages to. The result is paginated, and each page returns up to 100 phone numbers. If there are phone numbers after the first page of results, then a NextToken string is returned.

For more information, see ListPhoneNumbersOptedOut.

Syntax

listPhoneNumbersOptedOut(nextToken)

Parameters

Parameter Description Type Required
nextToken String to use when you call this function to get list of phone numbers that are available after the first page of results.
String Yes

For more information, see ListPhoneNumbersOptedOut.

Example

<cfscript>
	snsObj = getCloudService(application.awsCred, application.snsConf);	
	phoneNumOptedOut = snsObj.listPhoneNumbersOptedOut();
	writeoutput(phoneNumOptedOut.sdkHttpResponse.statusCode);
</cfscript>

Check if phone number is opted out

Check if a phone can receive SMS messages from an account, because the holder has opted out of receiving messages.

To resume sending messages, opt in the number by using the OptInPhoneNumber method.

For more information, see CheckIfPhoneNumberIsOptedOut.

Syntax

checkIfPhoneNumberIsOptedOut(phoneNumber)

Parameters

Parameter Description Type Required
phoneNumber
The phone number for which you want to check the opt out status.
String Yes

For more information, see request parameters.

Example

<cfscript>
		snsObj = getCloudService(application.awsCred, application.snsConf);	
		topicObj = snsObj.createTopic("checkIfPhoneNumberIsOptedOut");
		topicARN = topicObj.getTopicArn();

		subscribeMetadata = {
			"topicArn" = topicARN,
			"endpoint" = application.phoneNum,
			"protocol" = "sms"			
		};
		subsResp = topicObj.subscribe(subscribeMetadata);
		phoneNumOptedOut =         snsObj.checkIfPhoneNumberIsOptedOut(application.phoneNum);
		writeoutput(phoneNumOptedOut.isOptedOut);
</cfscript>