Using Simple Notification Service (SNS) in CFML: Subscribing to Topics

Posted 18 June 2018

Subscribing to topics in CFML via the AWS Java SDK is a two-step process.

  1. Make the subscription request.
  2. Confirm that you (the client) actually wants to subscribe.

If you haven’t already read the entry on the basic setup needed to access AWS from CFML, please do so now.

The AWSPlaybox app contains code that shows you how to make a subscription request programmatically. It follows the same pattern as described in the previous post in this series:

  1. Make a connection to SNS with a SNS client.
  2. Create a SubscribeRequest object.
  3. Use the SubscribeRequest’s fluent (“with X”) interface to set the topic ARN, protocol, and endpoint of the subscription.
  4. Tell the SNS client to subscribe() using the SubscribeRequest.

Here’s the relevant code from /sns.cfm in the AWSPlaybox app:

sns = application.awsServiceFactory.createServiceObject('sns');

subscribeRequest = CreateObject('java', 'com.amazonaws.services.sns.model.SubscribeRequest').withTopicARN(application.awsResources.currentSNSTopicARN).withProtocol("email").withEndpoint(Trim(FORM.emailAddress));

sns.subscribe(subscribeRequest);

Breaking this down:

subscribeResult = sns.subscribe(subscribeRequest);
storeInDatabase(subscribeResult.getSubscriptionArn());

That’s the first part of subscribing to a SNS topic.

The second step of the process is the endpoint (email address, phone number, etc) accepting the subcription. Opting in to a subscription important because malicious applications could otherwise automatically spam SNS or email messages to unwilling (and unhappy) subscribers. It’s also the law under GDPR.

If your SNS topic sends messages via email or SNS, the recipient simply needs to respond to a “Do you want to subscribe to this topic?” message that’s automatically generated by SNS when you subscribe to a topic. That part of the process is fully controlled by AWS and isn’t something you can customize.

If you want the example in the AWSPlaybox app to work, you’ll need to submit your email address to the provided form, and then respond to the email message sent from AWS to subscribe to the topic that you just created. If you want to subscribe to this topic via SMS, you’ll need to sign in to the AWS Console and add that subscription manually within the SNS management console. You could also add that code to /sns.cfm in the AWSPlaybox app and submit a pull request! :)

If you want your CFML application to act as a subscriber to an SNS topic, you need to follow the steps outlined in the documentation on sending SNS messages to HTTP/S endpoints. This requires that your CFML application be able to confirm that it wants to subscribe to a SNS topic via a GET HTTP request and then process individual SNS messages as they come in.

Now that we’ve subscribed to a topic, we can send (and receive!) messages. That’s the subject of the next post.

Categories: AWS ColdFusion