id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
sns-dg-121
|
sns-dg.pdf
| 121 |
message appears as: MYTOPIC> Hello World! 6. Choose Create topic. The topic's name and Amazon Resource Name (ARN) appear on the Topics page. To create an SMS subscription You can use subscriptions to send an SMS message to multiple recipients by publishing the message only once to your topic. Note When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox. The SMS sandbox provides a safe environment for you to try Amazon SNS features without risking your reputation as an SMS sender. While your account is in the SMS sandbox, you can use all of the features of Amazon SNS, but you can send SMS messages Configurations 429 Amazon Simple Notification Service Developer Guide only to verified destination phone numbers. For more information, see Using the Amazon SNS SMS sandbox. 1. 2. Sign in to the Amazon SNS console. In the navigation pane, choose Subscriptions. 3. On the Subscriptions page, choose Create subscription. 4. On the Create subscription page, under Details, do the following: a. b. c. For Topic ARN, enter or choose the Amazon Resource Name (ARN) of the topic to which you want to send SMS messages. For Protocol, choose SMS. For Endpoint, enter the phone number that you want to subscribe to your topic. 5. Choose Create subscription. The subscription information appears on the Subscriptions page. To add more phone numbers, repeat these steps. You can also add other types of subscriptions, such as email. To send a message When you publish a message to a topic, Amazon SNS attempts to deliver that message to every phone number that is subscribed to the topic. 1. In the Amazon SNS console, on the Topics page, choose the name of the topic to which you want to send SMS messages. 2. On the topic details page, choose Publish message. 3. On the Publish message to topic page, under Message details, do the following: a. b. For Subject, keep the field blank unless your topic contains email subscriptions and you want to publish to both email and SMS subscriptions. Amazon SNS uses the Subject that you enter as the email subject line. (Optional) For Time to Live (TTL), enter a number of seconds that Amazon SNS has to send your SMS message to any mobile application endpoint subscribers. 4. Under Message body, do the following: Configurations 430 Amazon Simple Notification Service Developer Guide a. For Message structure, choose Identical payload for all delivery protocols to send the same message to all protocol types subscribed to your topic. Or, choose Custom payload for each delivery protocol to customize the message for subscribers of different protocol types. For example, you can enter a default message for phone number subscribers and a custom message for email subscribers. b. For Message body to send to the endpoint, enter your message, or your custom messages per delivery protocol. If your topic has a display name, Amazon SNS adds it to the message, which increases the message length. The display name length is the number of characters in the name plus two characters for the right angle bracket (>) and the space that Amazon SNS adds. For information about the size quotas for SMS messages, see Publishing SMS messages to a mobile phone using Amazon SNS. 5. (Optional) For Message attributes, add message metadata such as timestamps, signatures, and IDs. 6. Choose Publish message. Amazon SNS sends the SMS message and displays a success message. Sending a message to a topic using the AWS SDKs To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. The following code example shows how to: • Create an Amazon SNS topic. • Subscribe phone numbers to the topic. • Publish SMS messages to the topic so that all subscribed phone numbers receive the message at once. Configurations 431 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a topic and return its ARN. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Configurations 432 Amazon Simple Notification Service Developer Guide String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName);
|
sns-dg-122
|
sns-dg.pdf
| 122 |
import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Configurations 432 Amazon Simple Notification Service Developer Guide String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } Subscribe an endpoint to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * Configurations 433 Amazon Simple Notification Service Developer Guide * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeTextSMS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <phoneNumber> Where: topicArn - The ARN of the topic to subscribe. phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100). """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subTextSNS(snsClient, topicArn, phoneNumber); snsClient.close(); } public static void subTextSNS(SnsClient snsClient, String topicArn, String phoneNumber) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("sms") .endpoint(phoneNumber) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); Configurations 434 Amazon Simple Notification Service Developer Guide System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Set attributes on the message, such as the ID of the sender, the maximum price, and its type. Message attributes are optional. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } Configurations 435 Amazon Simple Notification Service Developer Guide public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Publish a message to a topic. The message is sent to every subscriber. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTextSMS { public static void main(String[] args) { final String usage = """ Configurations 436 Amazon Simple Notification Service Developer Guide Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Configurations 437 Amazon Simple Notification Service Developer Guide Publishing SMS messages to a mobile phone using Amazon SNS You can use Amazon SNS to send SMS messages directly to a mobile phone without subscribing the phone number to an Amazon SNS topic. Note Subscribing phone numbers to a topic is useful if you want to send one message to multiple phone numbers at once. For instructions on publishing an SMS message to a topic, see Publishing SMS messages to an Amazon SNS topic. When you send a message, you can control whether the message is optimized for cost or reliable delivery. You can also specify a sender ID or origination number. If you send the message programmatically using the Amazon SNS API or the AWS SDKs, you can specify a maximum price for the message delivery. Each SMS message
|
sns-dg-123
|
sns-dg.pdf
| 123 |
Amazon SNS topic. Note Subscribing phone numbers to a topic is useful if you want to send one message to multiple phone numbers at once. For instructions on publishing an SMS message to a topic, see Publishing SMS messages to an Amazon SNS topic. When you send a message, you can control whether the message is optimized for cost or reliable delivery. You can also specify a sender ID or origination number. If you send the message programmatically using the Amazon SNS API or the AWS SDKs, you can specify a maximum price for the message delivery. Each SMS message can contain up to 140 bytes, and the character quota depends on the encoding scheme. For example, an SMS message can contain: • 160 GSM characters • 140 ASCII characters • 70 UCS-2 characters If you publish a message that exceeds the size quota, Amazon SNS sends it as multiple messages, each fitting within the size quota. Messages are not cut off in the middle of a word, but instead on whole-word boundaries. The total size quota for a single SMS publish action is 1,600 bytes. When you send an SMS message, you specify the phone number using the E.164 format, a standard phone numbering structure used for international telecommunication. Phone numbers that follow this format can have a maximum of 15 digits along with the prefix of a plus sign (+) and the country code. For example, a US phone number in E.164 format appears as +1XXX5550100. Sending a message (console) 1. 2. 3. Sign in to the Amazon SNS console. In the console menu, choose a region that supports SMS messaging. In the navigation pane, choose Text messaging (SMS). Configurations 438 Amazon Simple Notification Service Developer Guide 4. On the Mobile text messaging (SMS) page, choose Publish text message. 5. On the Publish SMS message page, for Message type, choose one of the following: • Promotional – Non-critical messages, such as marketing messages. • Transactional – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Note This message-level setting overrides your account-level default message type. You can set an account-level default message type from the Text messaging preferences section of the Mobile text messaging (SMS) page. For pricing information for promotional and transactional messages, see Worldwide SMS Pricing. For Destination phone number, enter the phone number to which you want to send the message. For Message, enter the message to send. (Optional) Under Origination identities, specify how to identify yourself to your recipients: 6. 7. 8. • To specify a Sender ID, type a custom ID that contains 3-11 alphanumeric characters, including at least one letter and no spaces. The sender ID is displayed as the message sender on the receiving device. For example, you can use your business brand to make the message source easier to recognize. Support for sender IDs varies by country and/or region. For example, messages delivered to U.S. phone numbers will not display the sender ID. For the countries and regions that support sender IDs, see Supported countries and regions for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. If you do not specify a sender ID, one of the following is displayed as the originating identity: • In countries that support long codes, the long code is shown. • In countries where only sender IDs are supported, NOTICE is shown. Configurations 439 Amazon Simple Notification Service Developer Guide This message-level sender ID overrides your default sender ID, which you set on the Text messaging preferences page. • To specify an Origination number, enter a string of 5-14 numbers to display as the sender's phone number on the receiver's device. This string must match an origination number that is configured in your AWS account for the destination country. The origination number can be a 10DLC number, toll-free number, person-to-person long code, or short codes. For more information, see Origination identities for Amazon SNS SMS messages. If you don't specify an origination number, Amazon SNS selects an origination number to use for the SMS text message, based on your AWS account configuration. 9. If you're sending SMS messages to recipients in India, expand Country-specific attributes, and specify the following attributes: • Entity ID – The entity ID or principal entity (PE) ID for sending SMS messages to recipients in India. This ID is a unique string of 1–50 characters that the Telecom Regulatory Authority of India (TRAI) provides to identify the entity that you registered with the TRAI. • Template ID – The template ID for sending SMS messages to recipients in India. This ID is a unique, TRAI-provided string of 1–50 characters that identifies the template that you registered with the TRAI. The template ID must be associated with the
|
sns-dg-124
|
sns-dg.pdf
| 124 |
India, expand Country-specific attributes, and specify the following attributes: • Entity ID – The entity ID or principal entity (PE) ID for sending SMS messages to recipients in India. This ID is a unique string of 1–50 characters that the Telecom Regulatory Authority of India (TRAI) provides to identify the entity that you registered with the TRAI. • Template ID – The template ID for sending SMS messages to recipients in India. This ID is a unique, TRAI-provided string of 1–50 characters that identifies the template that you registered with the TRAI. The template ID must be associated with the sender ID that you specified for the message. For more information on sending SMS messages to recipients in India, India sender ID registration process in the AWS End User Messaging SMS User Guide. 10. Choose Publish message. Tip To send SMS messages from an origination number, you can also choose Origination numbers in the Amazon SNS console navigation panel. Choose an origination number that includes SMS in the Capabilities column, and then choose Publish text message. Sending a message (AWS SDKs) To send an SMS message using one of the AWS SDKs, use the API operation in that SDK that corresponds to the Publish request in the Amazon SNS API. With this request, you can send an Configurations 440 Amazon Simple Notification Service Developer Guide SMS message directly to a phone number. You can also use the MessageAttributes parameter to set values for the following attribute names: AWS.SNS.SMS.SenderID A custom ID that contains 3–11 alphanumeric characters or hyphen (-) characters, including at least one letter and no spaces. The sender ID appears as the message sender on the receiving device. For example, you can use your business brand to help make the message source easier to recognize. Support for sender IDs varies by country or region. For example, messages delivered to US phone numbers don't display the sender ID. For a list of the countries or regions that support sender IDs, see Supported countries and regions for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. If you don't specify a sender ID, a long code appears as the sender ID in supported countries or regions. For countries or regions that require an alphabetic sender ID, NOTICE appears as the sender ID. This message-level attribute overrides the account-level attribute DefaultSenderID, which you can set using the SetSMSAttributes request. AWS.MM.SMS.OriginationNumber A custom string of 5–14 numbers, which can include an optional leading plus sign (+). This string of numbers appears as the sender's phone number on the receiving device. The string must match an origination number that's configured in your AWS account for the destination country. The origination number can be a 10DLC number, toll-free number, person-to-person (P2P) long code, or short code. For more information, see Phone numbers in the AWS End User Messaging SMS User Guide. If you don't specify an origination number, Amazon SNS chooses an origination number based on your AWS account configuration. AWS.SNS.SMS.MaxPrice The maximum price in USD that you're willing to spend to send the SMS message. If Amazon SNS determines that sending the message would incur a cost that exceeds your maximum price, it doesn't send the message. Configurations 441 Amazon Simple Notification Service Developer Guide This attribute has no effect if your month-to-date SMS costs have already exceeded the quota set for the MonthlySpendLimit attribute. You can set the MonthlySpendLimit attribute using the SetSMSAttributes request. If you're sending the message to an Amazon SNS topic, the maximum price applies to each message delivery to each phone number that is subscribed to the topic. AWS.SNS.SMS.SMSType The type of message that you're sending: • Promotional (default) – Non-critical messages, such as marketing messages. • Transactional – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. This message-level attribute overrides the account-level attribute DefaultSMSType, which you can set using the SetSMSAttributes request. AWS.MM.SMS.EntityId This attribute is required only for sending SMS messages to recipients in India. This is your entity ID or principal entity (PE) ID for sending SMS messages to recipients in India. This ID is a unique string of 1–50 characters that the Telecom Regulatory Authority of India (TRAI) provides to identify the entity that you registered with the TRAI. AWS.MM.SMS.TemplateId This attribute is required only for sending SMS messages to recipients in India. This is your template for sending SMS messages to recipients in India. This ID is a unique, TRAI-provided string of 1–50 characters that identifies the template that you registered with the TRAI. The template ID must be associated with the sender ID that you specified for the message. Sending a message The following code examples show how to publish SMS messages using Amazon SNS. Configurations 442 Amazon Simple
|
sns-dg-125
|
sns-dg.pdf
| 125 |
the Telecom Regulatory Authority of India (TRAI) provides to identify the entity that you registered with the TRAI. AWS.MM.SMS.TemplateId This attribute is required only for sending SMS messages to recipients in India. This is your template for sending SMS messages to recipients in India. This ID is a unique, TRAI-provided string of 1–50 characters that identifies the template that you registered with the TRAI. The template ID must be associated with the sender ID that you specified for the message. Sending a message The following code examples show how to publish SMS messages using Amazon SNS. Configurations 442 Amazon Simple Notification Service Developer Guide .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. namespace SNSMessageExample { using System; using System.Threading.Tasks; using Amazon; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; public class SNSMessage { private AmazonSimpleNotificationServiceClient snsClient; /// <summary> /// Initializes a new instance of the <see cref="SNSMessage"/> class. /// Constructs a new SNSMessage object initializing the Amazon Simple /// Notification Service (Amazon SNS) client using the supplied /// Region endpoint. /// </summary> /// <param name="regionEndpoint">The Amazon Region endpoint to use in /// sending test messages with this object.</param> public SNSMessage(RegionEndpoint regionEndpoint) { snsClient = new AmazonSimpleNotificationServiceClient(regionEndpoint); } /// <summary> /// Sends the SMS message passed in the text parameter to the phone number /// in phoneNum. /// </summary> /// <param name="phoneNum">The ten-digit phone number to which the text Configurations 443 Amazon Simple Notification Service Developer Guide /// message will be sent.</param> /// <param name="text">The text of the message to send.</param> /// <returns>Async task.</returns> public async Task SendTextMessageAsync(string phoneNum, string text) { if (string.IsNullOrEmpty(phoneNum) || string.IsNullOrEmpty(text)) { return; } // Now actually send the message. var request = new PublishRequest { Message = text, PhoneNumber = phoneNum, }; try { var response = await snsClient.PublishAsync(request); } catch (Exception ex) { Console.WriteLine($"Error sending message: {ex}"); } } } } • For API details, see Publish in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Configurations 444 Amazon Simple Notification Service Developer Guide /** * Publish SMS: use Amazon Simple Notification Service (Amazon SNS) to send an SMS text message to a phone number. * Note: This requires additional AWS configuration prior to running example. * * NOTE: When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox and you can only * use verified destination phone numbers. See https://docs.aws.amazon.com/sns/ latest/dg/sns-sms-sandbox.html. * NOTE: If destination is in the US, you also have an additional restriction that you have use a dedicated * origination ID (phone number). You can request an origination number using Amazon Pinpoint for a fee. * See https://aws.amazon.com/blogs/compute/provisioning-and-using-10dlc- origination-numbers-with-amazon-sns/ * for more information. * * <phone_number_value> input parameter uses E.164 format. * For example, in United States, this input value should be of the form: +12223334444 */ //! Send an SMS text message to a phone number. /*! \param message: The message to publish. \param phoneNumber: The phone number of the recipient in E.164 format. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishSms(const Aws::String &message, const Aws::String &phoneNumber, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetPhoneNumber(phoneNumber); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with message id, '" Configurations 445 Amazon Simple Notification Service Developer Guide << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see Publish in AWS SDK for C++ API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTextSMS { public static void main(String[] args) { Configurations 446 Amazon Simple Notification Service Developer Guide final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status
|
sns-dg-126
|
sns-dg.pdf
| 126 |
main(String[] args) { Configurations 446 Amazon Simple Notification Service Developer Guide final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Configurations 447 Amazon Simple Notification Service Developer Guide • For API details, see Publish in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun pubTextSMS( messageVal: String?, phoneNumberVal: String?, ) { val request = PublishRequest { message = messageVal phoneNumber = phoneNumberVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } } • For API details, see Publish in AWS SDK for Kotlin API reference. Configurations 448 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Sends a text message (SMS message) directly to a phone number using Amazon SNS. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $phone = '+1XXX5550100'; try { $result = $SnSclient->publish([ 'Message' => $message, 'PhoneNumber' => $phone, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails Configurations 449 Amazon Simple Notification Service Developer Guide error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Publish in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def publish_text_message(self, phone_number, message): """ Publishes a text message directly to a phone number without need for a subscription. :param phone_number: The phone number that receives the message. This must be in E.164 format. For example, a United States phone number might be +12065550101. :param message: The message to send. :return: The ID of the message. """ try: Configurations 450 Amazon Simple Notification Service Developer Guide response = self.sns_resource.meta.client.publish( PhoneNumber=phone_number, Message=message ) message_id = response["MessageId"] logger.info("Published message to %s.", phone_number) except ClientError: logger.exception("Couldn't publish message to %s.", phone_number) raise else: return message_id • For API details, see Publish in AWS SDK for Python (Boto3) API Reference. Setting SMS messaging preferences in Amazon SNS Use Amazon SNS to specify preferences for SMS messaging. For example, you can specify whether to optimize deliveries for cost or reliability, your monthly spending limit, how deliveries are logged, and whether to subscribe to daily SMS usage reports. These preferences take effect for every SMS message that you send from your account, but you can override some of them when you send an individual message. For more information, see Publishing SMS messages to a mobile phone using Amazon SNS. Setting SMS messaging preferences using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. Choose a region that supports SMS messaging. 3. On the navigation panel, choose Mobile and then Text messaging (SMS). 4. On the Mobile text messaging (SMS) page, in the Text messaging preferences section, choose Edit. 5. On the Edit text messaging preferences page, in the Details section, do the following: a. For Default message type, choose one of the following: • Promotional – Non-critical messages (for example, marketing). Amazon SNS optimizes message delivery to incur the lowest cost. Configurations 451 Amazon Simple Notification Service Developer Guide • Transactional (default) – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Amazon SNS optimizes message delivery to achieve the highest reliability. For pricing information for promotional and transactional messages, see Global SMS Pricing. b. (Optional) For Account spend limit, enter the amount (in USD) that you want to spend on SMS messages each calendar month. Important • By default, the spend quota is set to 1.00 USD. If you
|
sns-dg-127
|
sns-dg.pdf
| 127 |
Promotional – Non-critical messages (for example, marketing). Amazon SNS optimizes message delivery to incur the lowest cost. Configurations 451 Amazon Simple Notification Service Developer Guide • Transactional (default) – Critical messages that support customer transactions, such as one-time passcodes for multi-factor authentication. Amazon SNS optimizes message delivery to achieve the highest reliability. For pricing information for promotional and transactional messages, see Global SMS Pricing. b. (Optional) For Account spend limit, enter the amount (in USD) that you want to spend on SMS messages each calendar month. Important • By default, the spend quota is set to 1.00 USD. If you want to raise the service quota, submit a request. • If the amount set in the console exceeds your service quota, Amazon SNS stops publishing SMS messages. • Because Amazon SNS is a distributed system, it stops sending SMS messages within minutes of the spend quota being exceeded. During this interval, if you continue to send SMS messages, you might incur costs that exceed your quota. 6. (Optional) For Default sender ID, enter a custom ID, such as your business brand, which is displayed as the sender of the receiving device. Note Support for sender IDs varies by country. 7. (Optional) Enter the name of the Amazon S3 bucket name for usage reports. Note The Amazon S3 bucket policy must grant write access to Amazon SNS. 8. Choose Save changes. Configurations 452 Amazon Simple Notification Service Developer Guide Setting preferences (AWS SDKs) To set your SMS preferences using one of the AWS SDKs, use the action in that SDK that corresponds to the SetSMSAttributes request in the Amazon SNS API. With this request, you assign values to the different SMS attributes, such as your monthly spend quota and your default SMS type (promotional or transactional). For all SMS attributes, see SetSMSAttributes in the Amazon Simple Notification Service API Reference. The following code examples show how to use SetSMSAttributes. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. How to use Amazon SNS to set the DefaultSMSType attribute. //! Set the default settings for sending SMS messages. /*! \param smsType: The type of SMS message that you will send by default. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::setSMSType(const Aws::String &smsType, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SetSMSAttributesRequest request; request.AddAttributes("DefaultSMSType", smsType); const Aws::SNS::Model::SetSMSAttributesOutcome outcome = snsClient.SetSMSAttributes( request); if (outcome.IsSuccess()) { std::cout << "SMS Type set successfully " << std::endl; Configurations 453 Amazon Simple Notification Service } Developer Guide else { std::cerr << "Error while setting SMS Type: '" << outcome.GetError().GetMessage() << "'" << std::endl; } return outcome.IsSuccess(); } • For API details, see SetSMSAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To set SMS message attributes The following set-sms-attributes example sets the default sender ID for SMS messages to MyName. aws sns set-sms-attributes \ --attributes DefaultSenderID=MyName This command produces no output. • For API details, see SetSMSAttributes in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; Configurations 454 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } Configurations 455 Amazon Simple Notification Service Developer Guide } } • For API details, see SetSMSAttributes in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {"Transactional" | "Promotional"} defaultSmsType */ export const setSmsType = async (defaultSmsType
|
sns-dg-128
|
sns-dg.pdf
| 128 |
how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {"Transactional" | "Promotional"} defaultSmsType */ export const setSmsType = async (defaultSmsType = "Transactional") => { const response = await snsClient.send( new SetSMSAttributesCommand({ attributes: { // Promotional – (Default) Noncritical messages, such as marketing messages. // Transactional – Critical messages that support customer transactions, Configurations 456 Amazon Simple Notification Service Developer Guide // such as one-time passcodes for multi-factor authentication. DefaultSMSType: defaultSmsType, }, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '1885b977-2d7e-535e-8214-e44be727e265', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SetSMSAttributes in AWS SDK for JavaScript API Reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->SetSMSAttributes([ Configurations 457 Amazon Simple Notification Service Developer Guide 'attributes' => [ 'DefaultSMSType' => 'Transactional', ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see SetSMSAttributes in AWS SDK for PHP API Reference. Setting SMS messaging preferences for country-specific delivery You can manage and control your SMS traffic by sending messages only to specific destination countries. This ensures that your messages are sent only to approved countries, avoiding unwanted SMS charges. The following instructions use Amazon Pinpoint's Protect configuration to specify the countries you want to allow or block. 1. Open the AWS SMS console at https://console.aws.amazon.com/sms-voice/. 2. In the navigation pane, under Overview, in the Quick start section, choose Create a protect configuration. 3. Under Protect configuration details, enter a business-friendly name for your protect configuration (for example, Allow-Only-AU). 4. Under SMS country rules, select the Region/Country checkbox to block sending messages to all supported countries. 5. Deselect the checkboxes for the countries where you want to send messages. For example, to allow messages only to Australia, deselect the checkbox for Australia. 6. In the Protect configuration associations section, under Association type, select Account default. This will ensure that the AWS End User Messaging SMS Protect configuration affects all messages sent through Amazon SNS, Amazon Cognito, and the Amazon Pinpoint SendMessages API call. 7. Choose Create protect configuration to save your settings. The following confirmation message is displayed: Configurations 458 Amazon Simple Notification Service Developer Guide Success Protect configuration protect-abc0123456789 has been created. 8. Sign in to the Amazon SNS console. 9. Publish a message to one of the blocked countries, such as India. The message will not be delivered. You can verify this in the delivery failure logs using CloudWatch. Search for log group sns/region/AccountID/DirectPublishToPhoneNumber/ Failure for a response similar to the following example: { "notification": { "messageId": "bd59a509-XXXX-XXXX-82f8-fbdb8cb68217", "timestamp": "YYYY-MM-DD XX:XX:XX.XXXX“ }, "delivery": { "destination": "+91XXXXXXXXXX", "smsType": "Transactional", "providerResponse": "Cannot deliver message to the specified destination country", "dwellTimeMs": 85 }, "status": "FAILURE" } Managing Amazon SNS phone numbers and subscriptions Amazon SNS provides several options for managing who receives SMS messages from your account. With a limited frequency, you can opt in phone numbers that have opted out of receiving SMS messages from your account. To stop sending messages to SMS subscriptions, you can remove subscriptions or the topics that publish to them. Opting out of receiving SMS messages Where required by local laws and regulations (such as the US and Canada), SMS recipients can use their devices to opt-out by replying to the message with any of the following: • ARRET (French) • CANCEL • END Configurations 459 Amazon Simple Notification Service Developer Guide • OPT-OUT • OPTOUT • QUIT • REMOVE • STOP • TD • UNSUBSCRIBE To opt-out, the recipient must reply to the same origination number that Amazon SNS used to deliver the message. After opting-out, the recipient will no longer receive SMS messages delivered from your AWS account unless you opt-in the phone number. If the phone number is subscribed to an Amazon SNS topic, opting-out does not remove the subscription, but SMS messages will fail to deliver to that subscription unless you opt-in the phone number.
|
sns-dg-129
|
sns-dg.pdf
| 129 |
(French) • CANCEL • END Configurations 459 Amazon Simple Notification Service Developer Guide • OPT-OUT • OPTOUT • QUIT • REMOVE • STOP • TD • UNSUBSCRIBE To opt-out, the recipient must reply to the same origination number that Amazon SNS used to deliver the message. After opting-out, the recipient will no longer receive SMS messages delivered from your AWS account unless you opt-in the phone number. If the phone number is subscribed to an Amazon SNS topic, opting-out does not remove the subscription, but SMS messages will fail to deliver to that subscription unless you opt-in the phone number. Managing phone numbers and subscriptions using the Amazon SNS console You can use the Amazon SNS console to control which phone numbers receive SMS messages from your account. Opting-in a phone number that has been opted-out the Amazon SNS console You can view which phone numbers have been opted-out of receiving SMS messages from your account, and you can opt-in these phone numbers to resume sending messages to them. You can opt-in a phone number only once every 30 days. 1. 2. Sign in to the Amazon SNS console. In the console menu, set the region selector to a region that supports SMS messaging. 3. On the navigation panel, choose Text messaging (SMS). 4. On the Mobile text messaging (SMS) page, in the Opted-out phone numbers section, opted- out phone numbers are displayed. 5. Select the check box for the phone number that you want to opt-in, and choose Opt in. The phone number is no longer opted-out and will receive SMS messages that you send to it. Configurations 460 Amazon Simple Notification Service Developer Guide Deleting an SMS subscription the Amazon SNS console Delete an SMS subscription to stop sending SMS messages to that phone number when you publish to your topics. 1. On the navigation panel, choose Subscriptions. 2. 3. Select the check boxes for the subscriptions that you want to delete. Then choose Actions, and choose Delete Subscriptions. In the Delete window, choose Delete. Amazon SNS deletes the subscription and displays a success message. Deleting a topic the Amazon SNS console Delete a topic when you no longer want to publish messages to its subscribed endpoints. 1. On the navigation panel, choose Topics. 2. 3. Select the check boxes for the topics that you want to delete. Then choose Actions, and choose Delete Topics. In the Delete window, choose Delete. Amazon SNS deletes the topic and displays a success message. Managing phone numbers and subscriptions using the AWS SDK You can use the AWS SDKs to make programmatic requests to Amazon SNS and manage which phone numbers can receive SMS messages from your account. To use an AWS SDK, you must configure it with your credentials. For more information, see Shared config and credentials files in the AWS SDKs and Tools Reference Guide. Viewing all opted-out phone numbers using the AWS SDK To view all opted-out phone numbers, submit a ListPhoneNumbersOptedOut request with the Amazon SNS API. The following code examples show how to use ListPhoneNumbersOptedOut. Configurations 461 Amazon Simple Notification Service Developer Guide CLI AWS CLI To list SMS message opt-outs The following list-phone-numbers-opted-out example lists the phone numbers opted out of receiving SMS messages. aws sns list-phone-numbers-opted-out Output: { "phoneNumbers": [ "+15555550100" ] } • For API details, see ListPhoneNumbersOptedOut in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutRequest; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** Configurations 462 Amazon Simple Notification Service Developer Guide * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class ListOptOut { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listOpts(snsClient); snsClient.close(); } public static void listOpts(SnsClient snsClient) { try { ListPhoneNumbersOptedOutRequest request = ListPhoneNumbersOptedOutRequest.builder().build(); ListPhoneNumbersOptedOutResponse result = snsClient.listPhoneNumbersOptedOut(request); System.out.println("Status is " + result.sdkHttpResponse().statusCode() + "\n\nPhone Numbers: \n\n" + result.phoneNumbers()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListPhoneNumbersOptedOut in AWS SDK for Java 2.x API Reference. Configurations 463 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Returns a list of phone numbers that are opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' =>
|
sns-dg-130
|
sns-dg.pdf
| 130 |
ListPhoneNumbersOptedOut in AWS SDK for Java 2.x API Reference. Configurations 463 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Returns a list of phone numbers that are opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listPhoneNumbersOptedOut(); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. Configurations 464 Amazon Simple Notification Service Developer Guide • For API details, see ListPhoneNumbersOptedOut in AWS SDK for PHP API Reference. Checking whether a phone number is opted-out using the AWS SDK To check whether a phone number is opted-out, submit a CheckIfPhoneNumberIsOptedOut request with the Amazon SNS API. The following code examples show how to use CheckIfPhoneNumberIsOptedOut. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example shows how to use the Amazon Simple Notification Service /// (Amazon SNS) to check whether a phone number has been opted out. /// </summary> public class IsPhoneNumOptedOut { public static async Task Main() { string phoneNumber = "+15551112222"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await CheckIfOptedOutAsync(client, phoneNumber); } /// <summary> /// Checks to see if the supplied phone number has been opted out. Configurations 465 Amazon Simple Notification Service Developer Guide /// </summary> /// <param name="client">The initialized Amazon SNS Client object used /// to check if the phone number has been opted out.</param> /// <param name="phoneNumber">A string representing the phone number /// to check.</param> public static async Task CheckIfOptedOutAsync(IAmazonSimpleNotificationService client, string phoneNumber) { var request = new CheckIfPhoneNumberIsOptedOutRequest { PhoneNumber = phoneNumber, }; try { var response = await client.CheckIfPhoneNumberIsOptedOutAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { string optOutStatus = response.IsOptedOut ? "opted out" : "not opted out."; Console.WriteLine($"The phone number: {phoneNumber} is {optOutStatus}"); } } catch (AuthorizationErrorException ex) { Console.WriteLine($"{ex.Message}"); } } } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for .NET API Reference. CLI AWS CLI To check SMS message opt-out for a phone number Configurations 466 Amazon Simple Notification Service Developer Guide The following check-if-phone-number-is-opted-out example checks whether the specified phone number is opted out of receiving SMS messages from the current AWS account. aws sns check-if-phone-number-is-opted-out \ --phone-number +1555550100 Output: { "isOptedOut": false } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutRequest; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * Configurations 467 Amazon Simple Notification Service Developer Guide * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CheckOptOut { public static void main(String[] args) { final String usage = """ Usage: <phoneNumber> Where: phoneNumber - The mobile phone number to look up (for example, +1XXX5550100). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String phoneNumber = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); checkPhone(snsClient, phoneNumber); snsClient.close(); } public static void checkPhone(SnsClient snsClient, String phoneNumber) { try { CheckIfPhoneNumberIsOptedOutRequest request = CheckIfPhoneNumberIsOptedOutRequest.builder() .phoneNumber(phoneNumber) .build(); CheckIfPhoneNumberIsOptedOutResponse result = snsClient.checkIfPhoneNumberIsOptedOut(request); System.out.println( result.isOptedOut() + "Phone Number " + phoneNumber + " has Opted Out of receiving sns messages." + "\n\nStatus was " + result.sdkHttpResponse().statusCode()); Configurations 468 Amazon Simple Notification Service Developer Guide } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", ) => { Configurations 469 Amazon Simple Notification Service Developer Guide const command =
|
sns-dg-131
|
sns-dg.pdf
| 131 |
Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", ) => { Configurations 469 Amazon Simple Notification Service Developer Guide const command = new CheckIfPhoneNumberIsOptedOutCommand({ phoneNumber, }); const response = await snsClient.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // isOptedOut: false // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for JavaScript API Reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; Configurations 470 Amazon Simple Notification Service /** Developer Guide * Indicates whether the phone number owner has opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $phone = '+1XXX5550100'; try { $result = $SnSclient->checkIfPhoneNumberIsOptedOut([ 'phoneNumber' => $phone, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for PHP API Reference. Opting-in a phone number that has been opted-out using the Amazon SNS API To opt-in a phone number, submit an OptInPhoneNumber request with the Amazon SNS API. You can opt-in a phone number only once every 30 days. Deleting an SMS subscription using the AWS SDK To delete an SMS subscription from an Amazon SNS topic, get the subscription ARN by submitting a ListSubscriptions request with the Amazon SNS API, and then pass the ARN to an Unsubscribe request. Configurations 471 Amazon Simple Notification Service Developer Guide The following code examples show how to use Unsubscribe. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Unsubscribe from a topic by a subscription ARN. /// <summary> /// Unsubscribe from a topic by a subscription ARN. /// </summary> /// <param name="subscriptionArn">The ARN of the subscription.</param> /// <returns>True if successful.</returns> public async Task<bool> UnsubscribeByArn(string subscriptionArn) { var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync( new UnsubscribeRequest() { SubscriptionArn = subscriptionArn }); return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see Unsubscribe in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Configurations 472 Amazon Simple Notification Service Developer Guide //! Delete a subscription to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param subscriptionARN: The Amazon Resource Name (ARN) for an Amazon SNS topic subscription. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::unsubscribe(const Aws::String &subscriptionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::UnsubscribeRequest request; request.SetSubscriptionArn(subscriptionARN); const Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request); if (outcome.IsSuccess()) { std::cout << "Unsubscribed successfully " << std::endl; } else { std::cerr << "Error while unsubscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see Unsubscribe in AWS SDK for C++ API Reference. CLI AWS CLI To unsubscribe from a topic The following unsubscribe example deletes the specified subscription from a topic. Configurations 473 Amazon Simple Notification Service Developer Guide aws sns unsubscribe \ --subscription-arn arn:aws:sns:us-west-2:0123456789012:my- topic:8a21d249-4329-4871-acc6-7be709c6ea7f This command produces no output. • For API details, see Unsubscribe in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class Unsubscribe { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of the subscription to delete. Configurations 474 Amazon Simple Notification Service Developer Guide """; if (args.length < 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient
|
sns-dg-132
|
sns-dg.pdf
| 132 |
and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class Unsubscribe { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of the subscription to delete. Configurations 474 Amazon Simple Notification Service Developer Guide """; if (args.length < 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); unSub(snsClient, subscriptionArn); snsClient.close(); } public static void unSub(SnsClient snsClient, String subscriptionArn) { try { UnsubscribeRequest request = UnsubscribeRequest.builder() .subscriptionArn(subscriptionArn) .build(); UnsubscribeResponse result = snsClient.unsubscribe(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription was removed for " + request.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see Unsubscribe in AWS SDK for Java 2.x API Reference. Configurations 475 Amazon Simple Notification Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { UnsubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} subscriptionArn - The ARN of the subscription to cancel. */ const unsubscribe = async ( subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx- xxxx-xxxx-xxxxxxxxxxxx", ) => { const response = await snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0178259a-9204-507c-b620-78a7570a44c6', Configurations 476 Amazon Simple Notification Service Developer Guide // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Unsubscribe in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun unSub(subscriptionArnVal: String) { val request = UnsubscribeRequest { subscriptionArn = subscriptionArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.unsubscribe(request) println("Subscription was removed for ${request.subscriptionArn}") } } • For API details, see Unsubscribe in AWS SDK for Kotlin API reference. Configurations 477 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Deletes a subscription to an Amazon SNS topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $subscription = 'arn:aws:sns:us-east-1:111122223333:MySubscription'; try { $result = $SnSclient->unsubscribe([ 'SubscriptionArn' => $subscription, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Configurations 478 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Unsubscribe in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_subscription(subscription): """ Unsubscribes and deletes a subscription. """ try: subscription.delete() logger.info("Deleted subscription %s.", subscription.arn) except ClientError: logger.exception("Couldn't delete subscription %s.", subscription.arn) raise • For API details, see Unsubscribe in AWS SDK for Python (Boto3) API Reference. Configurations 479 Amazon Simple Notification Service SAP ABAP SDK for SAP ABAP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->unsubscribe( iv_subscriptionarn = iv_subscription_arn ). MESSAGE 'Subscription deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Subscription does not exist.' TYPE 'E'. CATCH /aws1/cx_snsinvalidparameterex. MESSAGE 'Subscription with "PendingConfirmation" status cannot be deleted/unsubscribed. Confirm subscription before performing unsubscribe operation.' TYPE 'E'. ENDTRY. • For API details, see Unsubscribe in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try
|
sns-dg-133
|
sns-dg.pdf
| 133 |
and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->unsubscribe( iv_subscriptionarn = iv_subscription_arn ). MESSAGE 'Subscription deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Subscription does not exist.' TYPE 'E'. CATCH /aws1/cx_snsinvalidparameterex. MESSAGE 'Subscription with "PendingConfirmation" status cannot be deleted/unsubscribed. Confirm subscription before performing unsubscribe operation.' TYPE 'E'. ENDTRY. • For API details, see Unsubscribe in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.unsubscribe( Configurations 480 Amazon Simple Notification Service Developer Guide input: UnsubscribeInput( subscriptionArn: arn ) ) print("Unsubscribed.") • For API details, see Unsubscribe in AWS SDK for Swift API reference. Deleting a topic using the AWS SDK To delete a topic and all of its subscriptions, get the topic ARN by submitting a ListTopics request with the Amazon SNS API, and then pass the ARN to the DeleteTopic request. The following code examples show how to use DeleteTopic. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Delete a topic by its topic ARN. /// <summary> /// Delete a topic by its topic ARN. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteTopicByArn(string topicArn) { var deleteResponse = await _amazonSNSClient.DeleteTopicAsync( new DeleteTopicRequest() { TopicArn = topicArn }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; Configurations 481 Amazon Simple Notification Service } Developer Guide • For API details, see DeleteTopic in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Delete an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl; } else { std::cerr << "Error deleting topic " << topicARN << ":" << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); Configurations 482 Amazon Simple Notification Service Developer Guide } • For API details, see DeleteTopic in AWS SDK for C++ API Reference. CLI AWS CLI To delete an SNS topic The following delete-topic example deletes the specified SNS topic. aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" This command produces no output. • For API details, see DeleteTopic in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) Configurations 483 Amazon Simple Notification Service Developer Guide // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // DeleteTopic delete an Amazon SNS topic. func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error { _, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{ TopicArn: aws.String(topicArn)}) if err != nil { log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err) } return err } • For API details, see DeleteTopic in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. Configurations 484 Amazon Simple Notification Service Developer Guide * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class DeleteTopic { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); Configurations 485 Amazon Simple Notification Service Developer Guide } } } • For API details, see DeleteTopic in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set
|
sns-dg-134
|
sns-dg.pdf
| 134 |
System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); Configurations 485 Amazon Simple Notification Service Developer Guide } } } • For API details, see DeleteTopic in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { DeleteTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to delete. */ export const deleteTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { Configurations 486 Amazon Simple Notification Service Developer Guide // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteTopic in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteSNSTopic(topicArnVal: String) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was successfully deleted.") } } • For API details, see DeleteTopic in AWS SDK for Kotlin API reference. Configurations 487 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Deletes an SNS topic and all its subscriptions. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->deleteTopic([ 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Configurations 488 Amazon Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_topic(topic): """ Deletes a topic. All subscriptions to the topic are also deleted. """ try: topic.delete() logger.info("Deleted topic %s.", topic.arn) except ClientError: logger.exception("Couldn't delete topic %s.", topic.arn) raise • For API details, see DeleteTopic in AWS SDK for Python (Boto3) API Reference. Configurations 489 Amazon Simple Notification Service SAP ABAP SDK for SAP ABAP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->deletetopic( iv_topicarn = iv_topic_arn ). MESSAGE 'SNS topic deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see DeleteTopic in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: arn) ) Configurations 490 Amazon Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for Swift API reference. Amazon SNS SMS activity monitoring By monitoring your SMS activity, you can keep track of destination phone numbers, successful or failed deliveries, reasons for failure, costs, and other information. Amazon SNS helps by summarizing statistics in the console, sending information to Amazon CloudWatch, and sending daily SMS usage reports to an Amazon S3 bucket that you specify. Viewing Amazon SNS SMS delivery statistics You can use the Amazon SNS console to view statistics about your recent SMS deliveries. 1. 2. Sign in
|
sns-dg-135
|
sns-dg.pdf
| 135 |
Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for Swift API reference. Amazon SNS SMS activity monitoring By monitoring your SMS activity, you can keep track of destination phone numbers, successful or failed deliveries, reasons for failure, costs, and other information. Amazon SNS helps by summarizing statistics in the console, sending information to Amazon CloudWatch, and sending daily SMS usage reports to an Amazon S3 bucket that you specify. Viewing Amazon SNS SMS delivery statistics You can use the Amazon SNS console to view statistics about your recent SMS deliveries. 1. 2. Sign in to the Amazon SNS console. In the console menu, set the region selector to a region that supports SMS messaging. 3. On the navigation panel, choose Text messaging (SMS). 4. On the Text messaging (SMS) page, in the Account stats section, view the charts for your transactional and promotional SMS message deliveries. Each chart shows the following data for the preceding 15 days: • Delivery rate (percentage of successful deliveries) • Sent (number of delivery attempts) • Failed (number of delivery failures) On this page, you can also choose the Usage button to go to the Amazon S3 bucket where you store your daily usage reports. For more information, see Subscribing to Amazon SNS daily SMS usage reports. Amazon SNS SMS delivery monitoring with Amazon CloudWatch metrics and logs You can use Amazon CloudWatch and Amazon CloudWatch Logs to monitor your SMS message deliveries. Viewing Amazon CloudWatch metrics Amazon SNS automatically collects metrics about your SMS message deliveries and pushes them to Amazon CloudWatch. You can use CloudWatch to monitor these metrics and create alarms to alert Configurations 491 Amazon Simple Notification Service Developer Guide you when a metric crosses a threshold. For example, you can monitor CloudWatch metrics to learn your SMS delivery rate and your month-to-date SMS charges. For information about monitoring CloudWatch metrics, setting CloudWatch alarms, and the types of metrics available, see Monitoring Amazon SNS topics using CloudWatch. Viewing CloudWatch Logs You can collect information about successful and unsuccessful SMS message deliveries by enabling Amazon SNS to write to Amazon CloudWatch Logs. For each SMS message that you send, Amazon SNS writes a log that includes the message price, the success or failure status, the reason for failure (if the message failed), the message dwell time, and other information. To enable and view CloudWatch Logs for your SMS messages 1. 2. Sign in to the Amazon SNS console. In the console menu, set the region selector to a region that supports SMS messaging. 3. On the navigation panel, choose Text messaging (SMS). 4. On the Mobile text messaging (SMS) page, in the Text messaging preferences section, choose Edit. 5. On the next page, expand the Delivery status logging section. 6. For Success sample rate, specify the percentage of successful SMS deliveries for which Amazon SNS will write logs in CloudWatch Logs. For example: • To write logs only for failed deliveries, set this value to 0. • To write logs for 10% of your successful deliveries, set it to 10. If you don't specify a percentage, Amazon SNS writes logs for all successful deliveries. 7. To provide the required permissions, do one of the following: • To create a new service role, choose Create new service role and then Create new roles. On the next page, choose Allow to give Amazon SNS write access to your account's resources. • To use an existing service role, choose Use existing service role and then paste the ARN name in the IAM role for successful and failed deliveries box. The service role you specify must allow write access to your account's resources. For more information on creating IAM roles, see Creating a role for an AWS service in the IAM User Guide. Configurations 492 Amazon Simple Notification Service 8. Choose Save changes. Developer Guide 9. Back on the Mobile text messaging (SMS) page, go to the Delivery status logs section to view any available logs. Note Depending on the destination phone number's carrier, it can take up to 72 hours for delivery logs to appear in the Amazon SNS console. Example log for successful SMS delivery The delivery status log for a successful SMS delivery will resemble the following example: { "notification": { "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf", "timestamp": "2016-06-28 00:40:34.558" }, "delivery": { "phoneCarrier": "My Phone Carrier", "mnc": 270, "numberOfMessageParts": 1, "destination": "+1XXX5550100", "priceInUSD": 0.00645, "smsType": "Transactional", "mcc": 310, "providerResponse": "Message has been accepted by phone carrier", "dwellTimeMs": 599, "dwellTimeMsUntilDeviceAck": 1344 }, "status": "SUCCESS" } Example log for failed SMS delivery The delivery status log for a failed SMS delivery will resemble the following example: { "notification": { "messageId": "1077257a-92f3-5ca3-bc97-6a915b310625", Configurations 493 Amazon Simple Notification Service Developer Guide "timestamp": "2016-06-28 00:40:34.559" }, "delivery": { "mnc": 0, "numberOfMessageParts": 1, "destination": "+1XXX5550100", "priceInUSD":
|
sns-dg-136
|
sns-dg.pdf
| 136 |
log for a successful SMS delivery will resemble the following example: { "notification": { "messageId": "34d9b400-c6dd-5444-820d-fbeb0f1f54cf", "timestamp": "2016-06-28 00:40:34.558" }, "delivery": { "phoneCarrier": "My Phone Carrier", "mnc": 270, "numberOfMessageParts": 1, "destination": "+1XXX5550100", "priceInUSD": 0.00645, "smsType": "Transactional", "mcc": 310, "providerResponse": "Message has been accepted by phone carrier", "dwellTimeMs": 599, "dwellTimeMsUntilDeviceAck": 1344 }, "status": "SUCCESS" } Example log for failed SMS delivery The delivery status log for a failed SMS delivery will resemble the following example: { "notification": { "messageId": "1077257a-92f3-5ca3-bc97-6a915b310625", Configurations 493 Amazon Simple Notification Service Developer Guide "timestamp": "2016-06-28 00:40:34.559" }, "delivery": { "mnc": 0, "numberOfMessageParts": 1, "destination": "+1XXX5550100", "priceInUSD": 0.00645, "smsType": "Transactional", "mcc": 0, "providerResponse": "Unknown error attempting to reach phone", "dwellTimeMs": 1420, "dwellTimeMsUntilDeviceAck": 1692 }, "status": "FAILURE" } SMS delivery failure reasons The reason for a failure is provided with the providerResponse attribute. SMS messages might fail to deliver for the following reasons: • Blocked as spam by phone carrier • Destination is on a blocked list • Invalid phone number • Message body is invalid • Phone carrier has blocked this message • Phone carrier is currently unreachable/unavailable • Phone has blocked SMS • Phone is on a blocked list • Phone is currently unreachable/unavailable • Phone number is opted out • This delivery would exceed max price • Unknown error attempting to reach phone Subscribing to Amazon SNS daily SMS usage reports You can monitor your SMS deliveries by subscribing to daily usage reports from Amazon SNS. For each day that you send at least one SMS message, Amazon SNS delivers a usage report as a CSV Configurations 494 Amazon Simple Notification Service Developer Guide file to the specified Amazon S3 bucket. It takes 24 hours for the SMS usage report to be available in the Amazon S3 bucket. Daily usage report information The usage report includes the following information for each SMS message that you send from your account. Note that the report does not include messages that are sent to recipients who have opted out. • Time of publication for message (in UTC) • Message ID • Destination phone number • Message type • Delivery status • Message price (in USD) • Part number (a message is split into multiple parts if it is too long for a single message) • Total number of parts Note If Amazon SNS did not receive the part number, we set its value to zero. Subscribing to daily usage reports To subscribe to daily usage reports, you must create an Amazon S3 bucket with the appropriate permissions. To create an Amazon S3 bucket for your daily usage reports 1. From the AWS account that sends SMS messages, sign in to the Amazon S3 console. 2. Choose Create Bucket. 3. For Bucket Name, we recommend that you enter a name that is unique for your account and your organization. For example, use the pattern <my-bucket-prefix>-<account_id>- <org-id>. Configurations 495 Amazon Simple Notification Service Developer Guide For information about conventions and restrictions for bucket names, see Rules for Bucket Naming in the Amazon Simple Storage Service User Guide. 4. Choose Create. 5. 6. 7. In the All Buckets table, choose the bucket. In the Permissions tab, choose Bucket policy. In the Bucket Policy Editor window, provide a policy that allows the Amazon SNS service principal to write to your bucket. For an example, see Example bucket policy. If you use the example policy, remember to replace my-s3-bucket with the bucket name that you chose in Step 3. 8. Choose Save. To subscribe to daily usage reports 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Text messaging (SMS). 3. On the Text messaging (SMS) page, in the Text messaging preferences section, choose Edit. 4. On the Edit text messaging preferences page, in the Details section, specify the Amazon S3 bucket name for usage reports. 5. Choose Save changes. Configurations 496 Amazon Simple Notification Service Example bucket policy Developer Guide The following policy allows the Amazon SNS service principal to perform the s3:PutObject, s3:GetBucketLocation, and s3:ListBucket actions. AWS provides tools for all services with service principals that have been given access to resources in your account. When the principal in an Amazon S3 bucket policy statement is an confused deputy problem. To limit which region and account from which the bucket can receive daily usage reports, use aws:SourceArn as shown in the example below. If you do not wish to limit which regions can generate these reports, use aws:SourceAccount to limit based on which account is generating the reports. If you don't know the ARN of the resource, use aws:SourceAccount. Use the following example that includes confused deputy protection when you create an Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPutObject", "Effect": "Allow", "Principal": {
|
sns-dg-137
|
sns-dg.pdf
| 137 |
an confused deputy problem. To limit which region and account from which the bucket can receive daily usage reports, use aws:SourceArn as shown in the example below. If you do not wish to limit which regions can generate these reports, use aws:SourceAccount to limit based on which account is generating the reports. If you don't know the ARN of the resource, use aws:SourceAccount. Use the following example that includes confused deputy protection when you create an Amazon S3 bucket to receive daily SMS usage reports from Amazon SNS. { "Version": "2008-10-17", "Statement": [ { "Sid": "AllowPutObject", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "s3:PutObject", "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*", "Condition": { "StringEquals": { "aws:SourceAccount": "account_id" }, "ArnLike": { "aws:SourceArn": "arn:aws:sns:region:account_id:*" } } }, { "Sid": "AllowGetBucketLocation", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "s3:GetBucketLocation", Configurations 497 Amazon Simple Notification Service Developer Guide "Resource": "arn:aws:s3:::amzn-s3-demo-bucket", "Condition": { "StringEquals": { "aws:SourceAccount": "account_id" }, "ArnLike": { "aws:SourceArn": "arn:aws:sns:region:account_id:*" } } }, { "Sid": "AllowListBucket", "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::amzn-s3-demo-bucket", "Condition": { "StringEquals": { "aws:SourceAccount": "account_id" }, "ArnLike": { "aws:SourceArn": "arn:aws:sns:region:account_id:*" } } } ] } Note You can publish usage reports to Amazon S3 buckets that are owned by the AWS account that's specified in the Condition element in the Amazon S3 policy. To publish usage reports to an Amazon S3 bucket that another AWS account owns, see How can I copy Amazon S3 objects from another AWS account?. Example daily usage report After you subscribe to daily usage reports, each day, Amazon SNS puts a CSV file with usage data in the following location: Configurations 498 Amazon Simple Notification Service Developer Guide <my-s3-bucket>/SMSUsageReports/<region>/YYYY/MM/DD/00x.csv.gz Each file can contain up to 50,000 records. If the records for a day exceed this quota, Amazon SNS will add multiple files. The following shows an example report: PublishTimeUTC,MessageId,DestinationPhoneNumber,MessageType,DeliveryStatus,PriceInUSD,PartNumber,TotalParts 2016-05-10T03:00:29.476Z,96a298ac-1458-4825- a7eb-7330e0720b72,1XXX5550100,Promotional,Message has been accepted by phone carrier,0.90084,0,1 2016-05-10T03:00:29.561Z,1e29d394- d7f4-4dc9-996e-26412032c344,1XXX5550100,Promotional,Message has been accepted by phone carrier,0.34322,0,1 2016-05-10T03:00:30.769Z,98ba941c-afc7-4c51- ba2c-56c6570a6c08,1XXX5550100,Transactional,Message has been accepted by phone carrier,0.27815,0,1 Requesting support for Amazon SNS SMS messaging Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. Certain SMS options with Amazon SNS aren't available for your AWS account until you contact Support. Create a case in the AWS Support Center to request any of the following: • An increase to your monthly SMS spending threshold By default, the monthly spending threshold is $1.00 (USD). Your spending threshold determines the volume of messages that you can send with Amazon SNS. You can request a spending threshold that meets the expected monthly message volume for your SMS use case. • A move from the SMS sandbox so that you can send SMS messages without restrictions. For more information, see Moving out of the Amazon SNS SMS sandbox. • A dedicated origination number Configurations 499 Amazon Simple Notification Service Developer Guide • A dedicated sender ID. A sender ID is a custom ID that is shown as the sender on the recipient's device. For example, you can use your business brand to make the message source easier to recognize. Support for sender IDs varies by country or region. For more information, see Supported countries and regions for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. Requesting increases to your monthly Amazon SNS SMS spending quota Amazon SNS provides spending quotas to help you manage the maximum per-month cost incurred by sending SMS using your account. The spending quota limits your risk in case of malicious attack, and prevents your upstream application from sending more messages than expected. You can configure Amazon SNS to stop publishing SMS messages when it determines that sending an SMS message will incur a cost that exceeds your spending quota for the current month. To ensure your operations are not impacted, we recommend requesting a spending quota high enough to support your production workloads. For more information, see Step 1: Open an Amazon SNS SMS case. Once you have received the quota, you can manage your risk by applying the full quota, or a smaller value, as described in Step 2: Update your SMS settings. By applying a smaller value, you can control your monthly spending with the option to scale up if necessary. Important Because Amazon SNS is a distributed system, it stops sending SMS messages within minutes if the spending quota is exceeded. During this period, if you continue to send SMS messages, you might incur costs that exceed your quota. We set the spending quota for all new accounts at $1.00 (USD) per month. This quota is intended to let you test
|
sns-dg-138
|
sns-dg.pdf
| 138 |
your risk by applying the full quota, or a smaller value, as described in Step 2: Update your SMS settings. By applying a smaller value, you can control your monthly spending with the option to scale up if necessary. Important Because Amazon SNS is a distributed system, it stops sending SMS messages within minutes if the spending quota is exceeded. During this period, if you continue to send SMS messages, you might incur costs that exceed your quota. We set the spending quota for all new accounts at $1.00 (USD) per month. This quota is intended to let you test the message-sending capabilities of Amazon SNS. To request an increase to the SMS spending quota for your account, open a quota increase case in the AWS Support Center. Topics • Step 1: Open an Amazon SNS SMS case • Step 2: Update your SMS settings on the Amazon SNS console Configurations 500 Amazon Simple Notification Service Developer Guide Step 1: Open an Amazon SNS SMS case You can request an increase to your monthly spending quota by opening a quota increase case in the AWS Support Center. Note Some of the fields on the request form are marked as "optional." However, Support requires all of the information that's mentioned in the following steps in order to process your request. If you don't provide all of the required information, you may experience delays in processing your request. 1. Sign in to the AWS Management Console at https://console.aws.amazon.com/. 2. On the Support menu, choose Support Center. 3. On the Your support cases pane, choose Create case. 4. Choose the Looking for service limit increases? link, then complete the following: • For Limit type, choose SNS Text Messaging. • (Optional) For Provide a link to the site or app which will be sending SMS messages, provide information about the website, application, or service that will send SMS messages. • (Optional) For What type of messages do you plan to send, choose the type of message that you plan to send using your long code: • One Time Password – Messages that provide passwords that your customers use to authenticate with your website or application. • Promotional – Noncritical messages that promote your business or service, such as special offers or announcements. • Transactional – Important informational messages that support customer transactions, such as order confirmations or account alerts. Transactional messages must not contain promotional or marketing content. • (Optional) For Which AWS Region will you be sending messages from, choose the region that you'll be sending messages from. • (Optional) For Which countries do you plan to send messages to, enter the country or region that you want to purchase short codes in. • (Optional) In the How do your customers opt to receive messages from you, provide details about your opt-in process. Configurations 501 Amazon Simple Notification Service Developer Guide • (Optional) In the Please provide the message template that you plan to use to send messages to your customers field, include the template that you will be using. 5. Under Requests, complete the following sections: • For the Region, choose the Region from which you'll be sending messages. Note The Region is required in the Requests section. Even if you provided this information in the Case details section you must also include it here. • For Resource Type, choose General Limits. • For Limit, choose Account Spend Threshold Increase. 6. For New limit value, enter the maximum amount (in USD) that you can spend on SMS each calendar month. 7. Under Case description, for Use case description, provide the following details: • The website or app of the company or service that's sending SMS messages. • The service that's provided by your website or app, and how your SMS messages contribute to that service. • How users sign up to voluntarily receive your SMS messages on your website, app, or other location. If your requested spending quota (the value you specified for New quota value) exceeds $10,000 (USD), provide the following additional details for each country that you're messaging: • Whether you're using a sender ID or short code. If you're using a sender ID, provide: • The sender ID. • Whether the sender ID is registered with wireless carriers in the country. • The maximum expected transactions-per-second (TPS) for your messaging. • The average message size. • The template for the messages that you send to the country. • (Optional) Character encoding needs, if any. Configurations 502 Amazon Simple Notification Service Developer Guide 8. (Optional) If you want to submit any further requests, choose Add another request. If you include multiple requests, provide the required information for each. For the required information, see the other sections within Requesting support for Amazon SNS SMS messaging. 9. Under Contact options, for Preferred
|
sns-dg-139
|
sns-dg.pdf
| 139 |
Whether the sender ID is registered with wireless carriers in the country. • The maximum expected transactions-per-second (TPS) for your messaging. • The average message size. • The template for the messages that you send to the country. • (Optional) Character encoding needs, if any. Configurations 502 Amazon Simple Notification Service Developer Guide 8. (Optional) If you want to submit any further requests, choose Add another request. If you include multiple requests, provide the required information for each. For the required information, see the other sections within Requesting support for Amazon SNS SMS messaging. 9. Under Contact options, for Preferred contact language, choose the language in which you want to receive communications for this case. 10. When you finish, choose Submit. The Support team provides an initial response to your request within 24 hours. To prevent our systems from being used to send unsolicited or malicious content, we consider each request carefully. If we can, we will grant your request within this 24-hour period. However, if we need additional information from you, it might take longer to resolve your request. If your use case doesn't align with our policies, we might be unable to grant your request. Step 2: Update your SMS settings on the Amazon SNS console After we notify you that your monthly spending quota has been increased, you have to adjust the spending quota for your account on the Amazon SNS console. Important You must complete the following steps or your SMS spend limit will not be increased. To adjust your spending quota on the console 1. Sign in to the Amazon SNS console. 2. Open the left navigation menu, expand Mobile, and then choose Text messaging (SMS). 3. On the Mobile text messaging (SMS) page, in the Text messaging preferences section, choose Edit. 4. On the Edit text messaging preferences page, in the Details section, enter your new SMS spend limit in the Account spend limit field. Configurations 503 Amazon Simple Notification Service Developer Guide Note You might receive a warning that the entered value is larger than the default spend limit. You can ignore this. 5. Choose Save changes. Note If you get an "Invalid Parameter" error, check the contact from AWS Support and confirm that you entered the correct new SMS spend limit. If you still experience a problem, open a case in the AWS Support Center. When you create your case in the Support Center, be sure to include all the required information for the type of request that you're submitting. Otherwise, Support must contact you to obtain this information before proceeding. By submitting a detailed case, you help ensure that your case is fulfilled without delays. For the required details for specific types of SMS requests, see the following topics. For more information on sender IDs, see the following documentation in the AWS End User Messaging SMS User Guide: AWS End User Messaging SMS Topic Description Requesting a spending quota increase Open a case in support center for a sender ID Your spending quota determines how much money you can spend sending SMS messages through AWS End User Messaging SMS each month. If you plan to send messages to recipients a country where sender IDs are required, you can request a sender ID by creating a new case in the Support Center. Configurations 504 Amazon Simple Notification Service Developer Guide Best practices for Amazon SNS SMS messaging Important The Amazon SNS SMS Developer Guide has been updated. Amazon SNS has integrated with AWS End User Messaging SMS for the delivery of SMS messages. This guide contains the latest information on how to create, configure, and manage your Amazon SNS SMS messages. Mobile phone users tend to have a very low tolerance for unsolicited SMS messages. Response rates for unsolicited SMS campaigns will almost always be low, and therefore the return on your investment will be poor. Additionally, mobile phone carriers continuously audit bulk SMS senders. They throttle or block messages from numbers that they determine to be sending unsolicited messages. Sending unsolicited content is also a violation of the AWS acceptable use policy. The Amazon SNS team routinely audits SMS campaigns, and might throttle or block your ability to send messages if it appears that you're sending unsolicited messages. Finally, in many countries, regions, and jurisdictions, there are severe penalties for sending unsolicited SMS messages. For example, in the United States, the Telephone Consumer Protection Act (TCPA) states that consumers are entitled to $500–$1,500 in damages (paid by the sender) for each unsolicited message that they receive. This section describes several best practices that might help you improve your customer engagement and avoid costly penalties. However, note that this section doesn't contain legal advice. Always consult an attorney to obtain legal advice. Comply with laws, regulations, and carrier requirements You can face
|
sns-dg-140
|
sns-dg.pdf
| 140 |
it appears that you're sending unsolicited messages. Finally, in many countries, regions, and jurisdictions, there are severe penalties for sending unsolicited SMS messages. For example, in the United States, the Telephone Consumer Protection Act (TCPA) states that consumers are entitled to $500–$1,500 in damages (paid by the sender) for each unsolicited message that they receive. This section describes several best practices that might help you improve your customer engagement and avoid costly penalties. However, note that this section doesn't contain legal advice. Always consult an attorney to obtain legal advice. Comply with laws, regulations, and carrier requirements You can face significant fines and penalties if you violate the laws and regulations of the places where your customers reside. For this reason, it's vital to understand the laws related to SMS messaging in each country or region where you do business. The following list includes links to key laws that apply to SMS communications in major markets around the world. Best practices for SMS messaging 505 Amazon Simple Notification Service Developer Guide • United States: The Telephone Consumer Protection Act of 1991, also known as TCPA, applies to certain types of SMS messages. For more information, see the rules and regulations at the Federal Communications Commission website. • United Kingdom: The Privacy and Electronic Communications (EC Directive) Regulations 2003, also known as PECR, applies to certain types of SMS messages. For more information, see What are PECR? at the website of the UK Information Commissioner's Office. • European Union: The Privacy and Electronic Communications Directive 2002, sometimes known as the ePrivacy Directive, applies to some types of SMS messages. For more information, see the full text of the law at the Europa.eu website. • Canada: The Fighting Internet and Wireless Spam Act, more commonly known as Canada's Anti- Spam Law or CASL, applies to certain types of SMS messages. For more information, see the full text of the law at the website of the Parliament of Canada. • Japan: The Act on Regulation of Transmission of Specific Electronic Mail may apply to certain types of SMS messages. For more information, see Japan's countermeasures against spam at the website of the Japanese Ministry of Internal Affairs and Communications. As a sender, these laws may apply to you even if your company or organization isn't based in one of these countries. Some of the laws in this list were originally created to address unsolicited email or telephone calls, but have been interpreted or expanded to apply to SMS messages as well. Other countries and regions may have their own laws related to the transmission of SMS messages. Consult an attorney in each country or region where your customers are located to obtain legal advice. In many countries, the local carriers ultimately have the authority to determine what kind of traffic flows over their networks. This means that the carriers might impose restrictions on SMS content that exceed the minimum requirements of local laws. Obtain permission Never send messages to recipients who haven't explicitly asked to receive the specific types of messages that you plan to send. Don't share opt-in lists, even among organizations within the same company. If recipients can sign up to receive your messages by using an online form, add systems that prevent automated scripts from subscribing people without their knowledge. You should also limit the number of times a user can submit a phone number in a single session. Best practices for SMS messaging 506 Amazon Simple Notification Service Developer Guide When you receive an SMS opt-in request, send the recipient a message that asks them to confirm that they want to receive messages from you. Don't send that recipient any additional messages until they confirm their subscription. A subscription confirmation message might resemble the following example: Text YES to join ExampleCorp alerts. 2 msgs/month. Msg & data rates may apply. Reply HELP for help, STOP to cancel. Maintain records that include the date, time, and source of each opt-in request and confirmation. This might be useful if a carrier or regulatory agency requests it, and can also help you perform routine audits of your customer list. Opt-in workflow In some cases (like US Toll-Free or Short Code registration) mobile carriers require you to provide mockups or screen shot of your entire opt-in workflow. The mockups or screen shot must closely resemble the opt-in workflow that your recipients will complete. Your mockups or screen shot should include all of the required disclosures listed below to maintain the highest level of compliance. Required disclosures • A description of the messaging use case that you will send through your program. • The phrase “Message and data rates may apply.” • An indication of how often recipients will get messages from you. For example, a recurring messaging program might say “one message per
|
sns-dg-141
|
sns-dg.pdf
| 141 |
carriers require you to provide mockups or screen shot of your entire opt-in workflow. The mockups or screen shot must closely resemble the opt-in workflow that your recipients will complete. Your mockups or screen shot should include all of the required disclosures listed below to maintain the highest level of compliance. Required disclosures • A description of the messaging use case that you will send through your program. • The phrase “Message and data rates may apply.” • An indication of how often recipients will get messages from you. For example, a recurring messaging program might say “one message per week.” A one-time password or multi-factor authentication use case might say “message frequency varies” or “one message per login attempt.” • Links to your Terms and Conditions and Privacy Policy documents. Common rejection reasons for non compliant opt-ins • If the provided company name does not match what is provided in the mockup or screen shot. Any non obvious relations should be explained in the opt-in workflow description. • If it appears that a message will be sent to the recipient, but no consent is explicitly gathered before doing so. Explicit consent is a requirement of all messaging. Best practices for SMS messaging 507 Amazon Simple Notification Service Developer Guide • If it appears that receiving a text message is required to sign up for a service. This is not compliant if the workflow doesn’t provide any alternative to receiving an opt-in message in another form like email or a voice call. • If the opt-in language is presented entirely in the Terms of Service. The disclosures should always be presented to the recipient at time of opt-in rather than housed inside a linked policy document. • If a customer provided consent to receive one type of message from you and you send them other types of text messages. For example they consent to receive one-time passwords but are also sent polling and survey messages. • If the required disclosures (listed above) are not presented to the recipients. The following example complies with the mobile carriers’ requirements for a multi-factor authentication use case. Best practices for SMS messaging 508 Amazon Simple Notification Service Developer Guide Mockup of a multi-factor authentication use case It contains finalized text and images, and it shows the entire opt-in flow, complete with annotations. In the opt-in flow, the customer has to take distinct, intentional actions to provide their consent to receive text messages and contains all of the required disclosures. Best practices for SMS messaging 509 Amazon Simple Notification Service Other opt-in workflow types Developer Guide Mobile carriers will also accept opt-in workflows outside of applications and websites like verbal or written opt-in if it complies with what is outlined above. A compliant opt-in workflow and verbal or written script will gather explicit consent from the recipient to receive a specific message type. Examples of this include the verbal script a support agent uses to gather consent before recording into a service database or a phone number listed on a promotional flyer. To provide a mockup of these opt-in workflow types you can provide a screen shot of your opt-in script, marketing material or database where numbers are collected. Mobile carriers may have additional questions around these use cases if an opt-in is not clear or the use case exceed certain volumes. Don't send to old lists People change phone numbers often. A phone number that you gathered consent to contact two years ago might belong to somebody else today. Don't use an old list of phone numbers for a new messaging program; if you do, you're likely to have some messages fail because the number is no longer in service, and some people who opt out because they don't remember giving you their consent in the first place. Audit your customer lists If you send recurring SMS campaigns, audit your customer lists on a regular basis. Auditing your customer lists ensures that the only customers who receive your messages are those who are interested in receiving them. When you audit your list, send each opted-in customer a message that reminds them that they're subscribed, and provides them with information about unsubscribing. A reminder message might resemble the following example: You're subscribed to ExampleCorp alerts. Msg & data rates may apply. Reply HELP for help, STOP to unsubscribe. Keep records Keep records that show when each customer requested to receive SMS messages from you, and which messages you sent to each customer. Many countries and regions around the world require SMS senders to maintain these records in a way that can be easily retrieved. Mobile carriers might also request this information from you at any time. The exact information that you have to provide varies by country or region. For more information about record-keeping requirements,
|
sns-dg-142
|
sns-dg.pdf
| 142 |
might resemble the following example: You're subscribed to ExampleCorp alerts. Msg & data rates may apply. Reply HELP for help, STOP to unsubscribe. Keep records Keep records that show when each customer requested to receive SMS messages from you, and which messages you sent to each customer. Many countries and regions around the world require SMS senders to maintain these records in a way that can be easily retrieved. Mobile carriers might also request this information from you at any time. The exact information that you have to provide varies by country or region. For more information about record-keeping requirements, review the Best practices for SMS messaging 510 Amazon Simple Notification Service Developer Guide regulations about commercial SMS messaging in each country or region where your customers are located. Occasionally, a carrier or regulatory agency asks us to provide proof that a customer opted to receive messages from you. In these situations, Support contacts you with a list of the information that the carrier or agency requires. If you can't provide the necessary information, we may pause your ability to send additional SMS messages. Make your messages clear, honest, and concise SMS is a unique medium. The 160-character-per-message limit means that your messages have to be concise. Techniques that you might use in other communication channels, such as email, might not apply to the SMS channel, and might even seem dishonest or deceptive when used with SMS messages. If the content in your messages doesn't align with best practices, recipients might ignore your messages; in the worst case, the mobile carriers might identify your messages as spam and block future messages from your phone number. This section provides some tips and ideas for creating an effective SMS message body. Identify yourself as the sender Your recipients should be able to immediately tell that a message is from you. Senders who follow this best practice include an identifying name ("program name") at the beginning of each message. Don't do this: Your account has been accessed from a new device. Reply Y to confirm. Try this instead: ExampleCorp Financial Alerts: You have logged in to your account from a new device. Reply Y to confirm, or STOP to opt-out. Don't try to make your message look like a person-to-person message Some marketers are tempted to add a personal touch to their SMS messages by making their messages appear to come from an individual. However, this technique might make your message seem like a phishing attempt. Best practices for SMS messaging 511 Amazon Simple Notification Service Don't do this: Developer Guide Hi, this is Jane. Did you know that you can save up to 50% at Example.com? Click here for more info: https://www.example.com. Try this instead: ExampleCorp Offers: Save 25-50% on sale items at Example.com. Click here to browse the sale: https://www.example.com. Text STOP to opt-out. Be careful when talking about money Scammers often prey upon people's desire to save and receive money. Don't make offers seem too good to be true. Don't use the lure of money to deceive people. Don't use currency symbols to indicate money. Don't do this: Save big $$$ on your next car repair by going to https:// www.example.com. Try this instead: ExampleCorp Offers: Your ExampleCorp insurance policy gets you discounts at 2300+ repair shops nationwide. More info at https://www.example.com. Text STOP to opt-out. Use only the necessary characters Brands are often inclined to protect their trademarks by including trademark symbols such as ™ or ® in their messages. However, these symbols are not part of the standard set of characters (known as the GSM alphabet) that can be included in a 160-character SMS message. When you send a message that contains one of these characters, your message is automatically sent using a different character encoding system, which only supports 70 characters per message part. As a result, your message could be broken into several parts. Because you're billed for each message part that you send, it could cost you more than you expect to spend to send the entire message. Additionally, your recipients might receive several sequential messages from you, rather than one single message. For more information about SMS character encoding, see SMS character limits in Amazon SNS. Best practices for SMS messaging 512 Amazon Simple Notification Service Don't do this: Developer Guide ExampleCorp Alerts: Save 20% when you buy a new ExampleCorp Widget® at example.com and use the promo code WIDGET. Try this instead: ExampleCorp Alerts: Save 20% when you buy a new ExampleCorp Widget(R) at example.com and use the promo code WIDGET. Note The two preceding examples are almost identical, but the first example contains a Registered Trademark symbol (®), which is not part of the GSM alphabet. As a result, the first example is sent as two message parts, while the second example
|
sns-dg-143
|
sns-dg.pdf
| 143 |
Amazon SNS. Best practices for SMS messaging 512 Amazon Simple Notification Service Don't do this: Developer Guide ExampleCorp Alerts: Save 20% when you buy a new ExampleCorp Widget® at example.com and use the promo code WIDGET. Try this instead: ExampleCorp Alerts: Save 20% when you buy a new ExampleCorp Widget(R) at example.com and use the promo code WIDGET. Note The two preceding examples are almost identical, but the first example contains a Registered Trademark symbol (®), which is not part of the GSM alphabet. As a result, the first example is sent as two message parts, while the second example is sent as one message part. Use valid, safe links If your message includes links, double-check the links to make sure that they work. Test your links on a device outside your corporate network to ensure that links resolve properly. Because of the 160-character limit of SMS messages, very long URLs could be split across multiple messages. You should use redirect domains to provide shortened URLs. However, you shouldn't use free link- shortening services such as tinyurl.com or bitly.com, because carriers tend to filter messages that include links on these domains. However, you can use paid link-shortening services as long as your links point to a domain that is dedicated to the exclusive use of your company or organization. Don't do this: Go to https://tinyurl.com/4585y8mr today for a special offer! Try this instead: ExampleCorp Offers: Today only, get an exclusive deal on an ExampleCorp Widget. See https://a.co/cFKmaRG for more info. Text STOP to opt-out. Best practices for SMS messaging 513 Amazon Simple Notification Service Developer Guide Limit the number of abbreviations that you use The 160-character limitation of the SMS channel leads some senders to believe that they need to use abbreviations extensively in their messages. However, the overuse of abbreviations can seem unprofessional to many readers, and could cause some users to report your message as spam. It's completely possible to write a coherent message without using an excessive number of abbreviations. Don't do this: Get a gr8 deal on ExampleCorp widgets when u buy a 4-pack 2day. Try this instead: ExampleCorp Alerts: Today only—an exclusive deal on ExampleCorp Widgets at example.com. Text STOP to opt-out. Respond appropriately When a recipient replies to your messages, make sure that you respond with useful information. For example, when a customer responds to one of your messages with the keyword "HELP", send them information about the program that they're subscribed to, the number of messages you'll send each month, and the ways that they can contact you for more information. A HELP response might resemble the following example: HELP: ExampleCorp alerts: email help@example.com or call 425-555-0199. 2 msgs/month. Msg & data rates may apply. Reply STOP to cancel. When a customer replies with the keyword "STOP", let them know that they won't receive any further messages. A STOP response might resemble the following example: You're unsubscribed from ExampleCorp alerts. No more messages will be sent. Reply HELP, email help@example.com, or call 425-555-0199 for more info. Adjust your sending based on engagement Your customers' priorities can change over time. If customers no longer find your messages to be useful, they might opt out of your messages entirely, or even report your messages as unsolicited. For these reasons, it's important that you adjust your sending practices based on customer engagement. Best practices for SMS messaging 514 Amazon Simple Notification Service Developer Guide For customers who rarely engage with your messages, you should adjust the frequency of your messages. For example, if you send weekly messages to engaged customers, you could create a separate monthly digest for customers who are less engaged. Finally, remove customers who are completely unengaged from your customer lists. This step prevents customers from becoming frustrated with your messages. It also saves you money and helps protect your reputation as a sender. Send at appropriate times Only send messages during normal daytime business hours. If you send messages at dinner time or in the middle of the night, there's a good chance that your customers will unsubscribe from your lists in order to avoid being disturbed. Furthermore, it doesn't make sense to send SMS messages when your customers can't respond to them immediately. If you send campaigns or journeys to very large audiences, double-check the throughput rates for your origination numbers. Divide the number of recipients by your throughput rate to determine how long it will take to send messages to all of your recipients. Avoid cross-channel fatigue In your campaigns, if you use multiple communication channels (such as email, SMS, and push messages), don't send the same message in every channel. When you send the same message at the same time in more than one channel, your customers will probably perceive your sending behavior to be annoying rather than helpful.
|
sns-dg-144
|
sns-dg.pdf
| 144 |
them immediately. If you send campaigns or journeys to very large audiences, double-check the throughput rates for your origination numbers. Divide the number of recipients by your throughput rate to determine how long it will take to send messages to all of your recipients. Avoid cross-channel fatigue In your campaigns, if you use multiple communication channels (such as email, SMS, and push messages), don't send the same message in every channel. When you send the same message at the same time in more than one channel, your customers will probably perceive your sending behavior to be annoying rather than helpful. Use dedicated short codes If you use short codes, maintain a separate short code for each brand and each type of message. For example, if your company has two brands, use a separate short code for each one. Similarly, if you send both transactional and promotional messages, use a separate short code for each type of message. To learn more about requesting short codes, see Requesting short codes for SMS messaging with AWS End User Messaging SMS in the AWS End User Messaging SMS User Guide. Verify your destination phone numbers When you send SMS messages through Amazon SNS, you're billed for each message part you send. The price you pay per message part varies on the recipient's country or region. For more information about SMS pricing, see AWS Worldwide SMS Pricing. Best practices for SMS messaging 515 Amazon Simple Notification Service Developer Guide When Amazon SNS accepts a request to send an SMS message (as the result of a call to the SendMessages API, or as the result of a campaign or journey being launched), you're charged for sending that message. This statement is true even if the intended recipient doesn't actually receive the message. For example, if the recipient's phone number is no longer in service, or if the number that you sent the message to wasn't a valid mobile phone number, you're still billed for sending the message. Amazon SNS accepts valid requests to send SMS messages and attempts to deliver them. For this reason, you should validate that the phone numbers that you send messages to are valid mobile numbers. You can use AWS End User Messaging SMS to send a test message to determine if a phone number is valid and what type of number it is (such as mobile, landline, or VoIP). For more information, see Send a test message with the SMS simulator in the AWS End User Messaging SMS User Guide. Design with redundancy in mind For mission-critical messaging programs, we recommend that you configure Amazon SNS in more than one AWS Region. Amazon SNS is available in several AWS Regions. For a complete list of Regions where Amazon SNS is available, see the AWS General Reference. The phone numbers that you use for SMS messages—including short codes, long codes, toll-free numbers, and 10DLC numbers—can't be replicated across AWS Regions. As a result, in order to use Amazon SNS in multiple Regions, you must request separate phone numbers in each Region where you want to use Amazon SNS. For example, if you use a short code to send text messages to recipients in the United States, you need to request separate short codes in each AWS Region that you plan to use. In some countries, you can also use multiple types of phone numbers for added redundancy. For example, in the United States, you can request short codes, 10DLC numbers, and toll-free numbers. Each of these phone number types takes a different route to the recipient. Having multiple phone number types available—either in the same AWS Region or spread across multiple AWS Regions— provides an additional layer of redundancy, which can help improve resiliency. SMS limits and restrictions For SMS limits and restrictions, see SMS and MMS limits and restrictions in the AWS End User Messaging SMS User Guide. Best practices for SMS messaging 516 Amazon Simple Notification Service Developer Guide Managing opt out keywords SMS recipients can use their devices to opt out of messages by replying with a keyword. For more information, see Opting out of receiving SMS messages. CreatePool Use the CreatePool API action to create a new pool and associate a specified origination identity to the pool. For more information, see CreatePool in AWS End User Messaging SMS API Reference. PutKeyword Use the PutKeyword API action to create or update a keyword configuration on an origination phone number or pool. For more information, see PutKeyword in AWS End User Messaging SMS API Reference. Managing number settings To manage settings for the dedicated short codes and long codes that you requested from AWS Support and assigned to your account, see Change a phone number's capabilities with the AWS CLI in AWS End User Messaging SMS. SMS character limits in
|
sns-dg-145
|
sns-dg.pdf
| 145 |
and associate a specified origination identity to the pool. For more information, see CreatePool in AWS End User Messaging SMS API Reference. PutKeyword Use the PutKeyword API action to create or update a keyword configuration on an origination phone number or pool. For more information, see PutKeyword in AWS End User Messaging SMS API Reference. Managing number settings To manage settings for the dedicated short codes and long codes that you requested from AWS Support and assigned to your account, see Change a phone number's capabilities with the AWS CLI in AWS End User Messaging SMS. SMS character limits in Amazon SNS A single SMS message can contain up to 140 bytes of information. The number of characters you can include in a single SMS message depends on the type of characters the message contains. If your message only uses characters in the GSM 03.38 character set, also known as the GSM 7- bit alphabet, it can contain up to 160 characters. If your message contains any characters that are outside the GSM 03.38 character set, it can have up to 70 characters. When you send an SMS message, Amazon SNS automatically determines the most efficient encoding to use. When a message contains more than the maximum number of characters, the message is split into multiple parts. When messages are split into multiple parts, each part contains additional information about the message part that precedes it. When the recipient's device receives message parts that are separated in this way, it uses this additional information to ensure that all of the message parts are displayed in the correct order. Depending on the recipient's mobile carrier and device, multiple messages might be displayed as a single message, or as a sequence of separate messages. As a result the number of characters in each message part is reduced to 153 (for messages that only contain GSM 03.38 characters) or 67 (for messages that contain other Best practices for SMS messaging 517 Amazon Simple Notification Service Developer Guide characters). You can estimate how many message parts your message contains before you send it by using SMS length calculator tools, several of which are available online. The maximum supported size of any message is 1600 GSM characters or 630 non-GSM characters. For more information about throughput and message size, see SMS character limits in Amazon Pinpoint in the Amazon Pinpoint User Guide. To view the number of message parts for each message that you send, you should first enable Event stream settings. When you do, Amazon SNS produces an _SMS.SUCCESS event when the message is delivered to the recipient's mobile provider. The _SMS.SUCCESS event record contains an attribute called attributes.number_of_message_parts. This attribute specifies the number of message parts that the message contained. Important When you send a message that contains more than one message parts, you're charged for the number of message parts contained in the message. GSM 03.38 character set The following table lists all of the characters that are present in the GSM 03.38 character set. If you send a message that only includes the characters shown in the following table, then the message can contain up to 160 characters. GSM 03.38 standard characters A N a n à Ø 3 B O b o Å ø 4 C P c p å Ö 5 D Q d q Ä ö 6 E R e r ä ù 7 F S f s Ç Ü 8 G T g t É ü 9 H U h u é Æ & I V i v è æ * J W j w ì ß @ K X k x Ñ 0 : L Y l y ñ 1 , M Z m z ò 2 ¤ Best practices for SMS messaging 518 Amazon Simple Notification Service Developer Guide GSM 03.38 standard characters $ £ Λ = ? Ω ! " Π > ) Ψ # § Σ - ; Θ ¡ ' Ξ ¿ / ( _ < ¥ % Δ . Φ + Γ The GSM 03.38 character set includes several symbols in addition to those shown in the preceding table. However, each of these characters is counted as two characters because it also includes an invisible escape character: • ^ • { • } • \ • [ • ] • ~ • | • € Finally, the GSM 03.38 character set also includes the following non-printed characters: • A space character. • A line feed control, which signifies the end of one line of text and the beginning of another. • A carriage return control, which moves to the beginning of a line of text (usually following a line feed character). • An escape control, which is automatically added to the characters in the preceding list. Example messages This section contains
|
sns-dg-146
|
sns-dg.pdf
| 146 |
also includes an invisible escape character: • ^ • { • } • \ • [ • ] • ~ • | • € Finally, the GSM 03.38 character set also includes the following non-printed characters: • A space character. • A line feed control, which signifies the end of one line of text and the beginning of another. • A carriage return control, which moves to the beginning of a line of text (usually following a line feed character). • An escape control, which is automatically added to the characters in the preceding list. Example messages This section contains several example SMS messages. For each example, this section shows the total number of characters, as well as the number of message parts for the message. Best practices for SMS messaging 519 Amazon Simple Notification Service Developer Guide Example 1: A long message that only contains characters in the GSM 03.38 alphabet The following message only contains characters that are in the GSM 03.38 alphabet. Hello Carlos. Your Example Corp. bill of $100 is now available. Autopay is scheduled for next Thursday, April 9. To view the details of your bill, go to https://example.com/bill1. The preceding message contains 180 characters, so it has to be split into multiple message parts. When a message is split into multiple message parts, each part can contain 153 GSM 03.38 characters. As a result, this message is sent as 2 message parts. Example 2: A message that contains multi-byte characters The following message contains several Chinese characters, all of which are outside of the GSM 03.38 alphabet. ###################################################·####1994#7######### The preceding message contains 71 characters. However, because almost all of the characters in the message are outside of the GSM 03.38 alphabet, it's sent as two message parts. Each of these message parts can contain a maximum of 67 characters. Example 3: A message that contains a single non-GSM character The following message contains a single character that isn't part of the GSM 03.38 alphabet. In this example, the character is a closing single quote (’), which is a different character from a regular apostrophe ('). Word processing applications such as Microsoft Word often automatically replace apostrophes with closing single quotes. If you draft your SMS messages in Microsoft Word and paste them into Amazon SNS, you should remove these special characters and replace them with apostrophes. John: Your appointment with Dr. Salazar’s office is scheduled for next Thursday at 4:30pm. Reply YES to confirm, NO to reschedule. The preceding message contains 130 characters. However, because it contains the closing single quote character, which isn't part of the GSM 03.38 alphabet, it's sent as two message parts. If you replace the closing single quote character in this message with an apostrophe (which is part of the GSM 03.38 alphabet), then the message is sent as a single message part. Best practices for SMS messaging 520 Amazon Simple Notification Service Developer Guide Sending mobile push notifications with Amazon SNS You can use Amazon SNS to send push notification messages directly to apps on mobile devices. Push notification messages sent to a mobile endpoint can appear in the mobile app as message alerts, badge updates, or sound alerts. Topics • How Amazon SNS user notifications work • Setting up push notifications with Amazon SNS • Setting up a mobile app in Amazon SNS • Using Amazon SNS for mobile push notifications • Amazon SNS mobile app attributes • Amazon SNS application event notifications for mobile applications • Mobile push API actions • Common Amazon SNS mobile push API errors • Using the Amazon SNS time to live message attribute for mobile push notifications • Amazon SNS mobile application supported Regions • Best practices for managing Amazon SNS mobile push notifications How Amazon SNS user notifications work You send push notification messages to both mobile devices and desktops using one of the following supported push notification services: Sending mobile push notifications 521 Amazon Simple Notification Service Developer Guide • Amazon Device Messaging (ADM) • Apple Push Notification Service (APNs) for both iOS and Mac OS X • Baidu Cloud Push (Baidu) • Firebase Cloud Messaging (FCM) • Microsoft Push Notification Service for Windows Phone (MPNS) • Windows Push Notification Services (WNS) Push notification services, such as APNs and FCM, maintain a connection with each app and associated mobile device registered to use their service. When an app and mobile device register, the push notification service returns a device token. Amazon SNS uses the device token to create a mobile endpoint, to which it can send direct push notification messages. In order for Amazon SNS to communicate with the different push notification services, you submit your push notification service credentials to Amazon SNS to be used on your behalf. For more information, see Setting up push notifications with Amazon
|
sns-dg-147
|
sns-dg.pdf
| 147 |
Notification Services (WNS) Push notification services, such as APNs and FCM, maintain a connection with each app and associated mobile device registered to use their service. When an app and mobile device register, the push notification service returns a device token. Amazon SNS uses the device token to create a mobile endpoint, to which it can send direct push notification messages. In order for Amazon SNS to communicate with the different push notification services, you submit your push notification service credentials to Amazon SNS to be used on your behalf. For more information, see Setting up push notifications with Amazon SNS. In addition to sending direct push notification messages, you can also use Amazon SNS to send messages to mobile endpoints subscribed to a topic. The concept is the same as subscribing other endpoint types, such as Amazon SQS, HTTP/S, email, and SMS, to a topic, as described in What is Amazon SNS?. The difference is that Amazon SNS communicates using the push notification services in order for the subscribed mobile endpoints to receive push notification messages sent to the topic. Setting up push notifications with Amazon SNS 1. Obtain the credentials and device token for the mobile platforms that you want to support. 2. Use the credentials to create a platform application object (PlatformApplicationArn) using Amazon SNS. For more information, see Creating an Amazon SNS platform application. 3. Use the returned credentials to request a device token for your mobile app and device from the push notification service. The token you receive represents your mobile app and device. 4. Use the device token and the PlatformApplicationArn to create a platform endpoint object (EndpointArn) using Amazon SNS. For more information, see Setting up an Amazon SNS platform endpoint for mobile notifications. 5. Use the EndpointArn to publish a message to an app on a mobile device. For more information, see Direct Amazon SNS mobile device messaging and the Publish API in the Amazon Simple Notification Service API Reference. Setting up push notifications with Amazon SNS 522 Amazon Simple Notification Service Developer Guide Setting up a mobile app in Amazon SNS This topic describes how to set up mobile applications in the AWS Management Console using the information described in Prerequisites for Amazon SNS user notifications. Prerequisites for Amazon SNS user notifications To begin using Amazon SNS mobile push notifications, you'll need the following: • A set of credentials for connecting to one of the supported push notification services: ADM, APNs, Baidu, FCM, MPNS, or WNS. • A device token or registration ID for the mobile app and device. • Amazon SNS configured to send push notification messages to the mobile endpoints. • A mobile app that is registered and configured to use one of the supported push notification services. Registering your application with a push notification service requires several steps. Amazon SNS needs some of the information you provide to the push notification service in order to send direct push notification messages to the mobile endpoint. Generally speaking, you need the required credentials for connecting to the push notification service, a device token or registration ID (representing your mobile device and mobile app) received from the push notification service, and the mobile app registered with the push notification service. The exact form the credentials take differs between mobile platforms, but in every case, these credentials must be submitted while making a connection to the platform. One set of credentials is issued for each mobile app, and it must be used to send a message to any instance of that app. The specific names will vary depending on which push notification service is being used. For example, when using APNs as the push notification service, you need a device token. Alternatively, when using FCM, the device token equivalent is called a registration ID. The device token or registration ID is a string that is sent to the application by the operating system of the mobile device. It uniquely identifies an instance of a mobile app running on a particular mobile device and can be thought of as unique identifiers of this app-device pair. Amazon SNS stores the credentials (plus a few other settings) as a platform application resource. The device tokens (again with some extra settings) are represented as objects called platform endpoints. Each platform endpoint belongs to one specific platform application, and every Setting up a mobile app 523 Amazon Simple Notification Service Developer Guide platform endpoint can be communicated with using the credentials that are stored in its corresponding platform application. The following sections include the prerequisites for each of the supported push notification services. Once you've obtained the prerequisite information, you can send a push notification message using the AWS Management Console or the Amazon SNS mobile push APIs. For more information, see Setting up push notifications with
|
sns-dg-148
|
sns-dg.pdf
| 148 |
(again with some extra settings) are represented as objects called platform endpoints. Each platform endpoint belongs to one specific platform application, and every Setting up a mobile app 523 Amazon Simple Notification Service Developer Guide platform endpoint can be communicated with using the credentials that are stored in its corresponding platform application. The following sections include the prerequisites for each of the supported push notification services. Once you've obtained the prerequisite information, you can send a push notification message using the AWS Management Console or the Amazon SNS mobile push APIs. For more information, see Setting up push notifications with Amazon SNS. Creating an Amazon SNS platform application To send notifications from Amazon SNS to mobile endpoints—whether directly or through subscriptions to a topic—you must first create a platform application. After registering the app with AWS, you need to create an endpoint for both the app and the mobile device. This endpoint allows Amazon SNS to send messages to the device. To create a platform application 1. 2. 3. Sign in to the Amazon SNS console. In the navigation pane, select Push notifications. In the Platform applications section, choose Create platform application. 4. Choose your AWS Region. For a list of AWS Regions where you can create mobile applications, see Amazon SNS mobile application supported Regions. 5. Enter the following application details: • Application name – Provide a name for your platform application. The name must be between 1 and 256 characters and can contain uppercase and lowercase letters, numbers, underscores, hyphens, and periods. • Push notification platform – Select the appropriate notification service that the app is registered with (For example, Apple Push Notification Service (APNs), Firebase Cloud Messaging (FCM)). 6. Depending on the platform you selected, you’ll need to provide specific credentials: • For APNs (Apple Push Notification Service) – Choose between token-based or certificate- based authentication. • For token-based authentication, upload a .p8 file (generated via Keychain Access). • For certificate-based authentication, upload a .p12 file (also exported from Keychain Access). Setting up a mobile app 524 Amazon Simple Notification Service Developer Guide • For FCM (Firebase Cloud Messaging) – Enter the Server key from Firebase Console. • For other platforms (such as ADM or GCM) – Enter the respective API keys or credentials. 7. After entering the necessary details, choose Create platform application. This action registers the app with Amazon SNS and creates the corresponding platform application object. 8. Upon creation, Amazon SNS generates and returns a PlatformApplicationArn (Amazon Resource Name). This ARN uniquely identifies your platform application and is used when creating endpoints for mobile devices. Setting up an Amazon SNS platform endpoint for mobile notifications When an app and mobile device register with a push notification service (such as APNs or Firebase Cloud Messaging), the push notification service returns a device token. Amazon SNS uses this device token to create a platform endpoint, which acts as a target for sending direct push notification messages to the app on the device. The platform endpoint serves as a bridge, routing messages sent by Amazon SNS to the push notification service for delivery to the corresponding mobile device. For more information, see Prerequisites for Amazon SNS user notifications and Setting up push notifications with Amazon SNS. Understanding device tokens and platform endpoints A device token uniquely identifies a mobile device registered with a push notification service (for example, APNs, Firebase Cloud Messaging). When an app registers with the push notification service, it generates a device token specific to that app and device. Amazon SNS uses this device token to create a platform endpoint within the corresponding platform application. The platform endpoint allows Amazon SNS to send push notification messages to the device through the push notification service, maintaining the connection between your app and the user's device. Create a platform endpoint To push notifications to an app with Amazon SNS, that app's device token must first be registered with Amazon SNS by calling the create platform endpoint action. This action takes the Amazon Resource Name (ARN) of the platform application and the device token as parameters and returns the ARN of the created platform endpoint. The CreatePlatformEndpoint action does the following: Setting up a mobile app 525 Amazon Simple Notification Service Developer Guide • If the platform endpoint already exists, do not create it again. Return to the caller the ARN of the existing platform endpoint. • If the platform endpoint with the same device token but different settings already exists, do not create it again. Throw an exception to the caller. • If the platform endpoint does not exist, create it. Return to the caller the ARN of the newly- created platform endpoint. You should not call the create platform endpoint action immediately every time an app starts, because this approach does not always provide a
|
sns-dg-149
|
sns-dg.pdf
| 149 |
Amazon Simple Notification Service Developer Guide • If the platform endpoint already exists, do not create it again. Return to the caller the ARN of the existing platform endpoint. • If the platform endpoint with the same device token but different settings already exists, do not create it again. Throw an exception to the caller. • If the platform endpoint does not exist, create it. Return to the caller the ARN of the newly- created platform endpoint. You should not call the create platform endpoint action immediately every time an app starts, because this approach does not always provide a working endpoint. This can happen, for example, when an app is uninstalled and reinstalled on the same device and the endpoint for it already exists but is disabled. A successful registration process should accomplish the following: 1. Ensure a platform endpoint exists for this app-device combination. 2. Ensure the device token in the platform endpoint is the latest valid device token. 3. Ensure the platform endpoint is enabled and ready to use. Pseudo code The following pseudo code describes a recommended practice for creating a working, current, enabled platform endpoint in a wide variety of starting conditions. This approach works whether this is a first time the app is being registered or not, whether the platform endpoint for this app already exists, and whether the platform endpoint is enabled, has the correct device token, and so on. It is safe to call it multiple times in a row, as it will not create duplicate platform endpoints or change an existing platform endpoint if it is already up to date and enabled. retrieve the latest device token from the mobile operating system if (the platform endpoint ARN is not stored) # this is a first-time registration call create platform endpoint store the returned platform endpoint ARN endif call get endpoint attributes on the platform endpoint ARN if (while getting the attributes a not-found exception is thrown) # the platform endpoint was deleted call create platform endpoint with the latest device token store the returned platform endpoint ARN Setting up a mobile app 526 Amazon Simple Notification Service else Developer Guide if (the device token in the endpoint does not match the latest one) or (GetEndpointAttributes shows the endpoint as disabled) call set endpoint attributes to set the latest device token and then enable the platform endpoint endif endif This approach can be used any time the app wants to register or re-register itself. It can also be used when notifying Amazon SNS of a device token change. In this case, you can just call the action with the latest device token value. Some points to note about this approach are: • There are two cases where it may call the create platform endpoint action. It may be called at the very beginning, where the app does not know its own platform endpoint ARN, as happens during a first-time registration. It is also called if the initial GetEndpointAttributes action call fails with a not-found exception, as would happen if the application knows its endpoint ARN but it was deleted. • The GetEndpointAttributes action is called to verify the platform endpoint's state even if the platform endpoint was just created. This happens when the platform endpoint already exists but is disabled. In this case, the create platform endpoint action succeeds but does not enable the platform endpoint, so you must double-check the state of the platform endpoint before returning success. AWS SDK example The following code shows how to implement the previous pseudo code using the Amazon SNS clients that are provided by the AWS SDKs. To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. CLI AWS CLI To create a platform application endpoint The following create-platform-endpoint example creates an endpoint for the specified platform application using the specified token. Setting up a mobile app 527 Amazon Simple Notification Service Developer Guide aws sns create-platform-endpoint \ --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/ MyApplication \ --token EXAMPLE12345... Output: { "EndpointArn": "arn:aws:sns:us-west-2:1234567890:endpoint/GCM/ MyApplication/12345678-abcd-9012-efgh-345678901234" } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * * In addition, create a platform application using the AWS Management Console. * See this doc topic: * Setting up a mobile app 528 Amazon Simple Notification Service Developer Guide * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html * * Without the values created by following the previous link,
|
sns-dg-150
|
sns-dg.pdf
| 150 |
and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * * In addition, create a platform application using the AWS Management Console. * See this doc topic: * Setting up a mobile app 528 Amazon Simple Notification Service Developer Guide * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html * * Without the values created by following the previous link, this code examples * does not work. */ public class RegistrationExample { public static void main(String[] args) { final String usage = """ Usage: <token> <platformApplicationArn> Where: token - The device token or registration ID of the mobile device. This is a unique identifier provided by the device platform (e.g., Apple Push Notification Service (APNS) for iOS devices, Firebase Cloud Messaging (FCM) for Android devices) when the mobile app is registered to receive push notifications. platformApplicationArn - The ARN value of platform application. You can get this value from the AWS Management Console.\s """; if (args.length != 2) { System.out.println(usage); return; } String token = args[0]; String platformApplicationArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); createEndpoint(snsClient, token, platformApplicationArn); } public static void createEndpoint(SnsClient snsClient, String token, String platformApplicationArn) { System.out.println("Creating platform endpoint with token " + token); try { CreatePlatformEndpointRequest endpointRequest = CreatePlatformEndpointRequest.builder() Setting up a mobile app 529 Amazon Simple Notification Service Developer Guide .token(token) .platformApplicationArn(platformApplicationArn) .build(); CreatePlatformEndpointResponse response = snsClient.createPlatformEndpoint(endpointRequest); System.out.println("The ARN of the endpoint is " + response.endpointArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); } } } For more information, see Mobile push API actions. Troubleshooting Repeatedly calling create platform endpoint with an outdated device token Especially for FCM endpoints, you may think it is best to store the first device token the application is issued and then call the create platform endpoint with that device token every time on application start-up. This may seem correct since it frees the app from having to manage the state of the device token and Amazon SNS will automatically update the device token to its latest value. However, this solution has a number of serious issues: • Amazon SNS relies on feedback from FCM to update expired device tokens to new device tokens. FCM retains information about old device tokens for some time, but not indefinitely. Once FCM forgets about the connection between the old device token and the new device token, Amazon SNS will no longer be able to update the device token stored in the platform endpoint to its correct value; it will just disable the platform endpoint instead. • The platform application will contain multiple platform endpoints corresponding to the same device token. • Amazon SNS imposes a quota on the number of platform endpoints that can be created starting with the same device token. Eventually, the creation of new endpoints will fail with an invalid parameter exception and the following error message: "This endpoint is already registered with a different token." Setting up a mobile app 530 Amazon Simple Notification Service Developer Guide For more information on managing FCM endpoints, see Amazon SNS management of Firebase Cloud Messaging endpoints. Re-enabling a platform endpoint associated with an invalid device token When a mobile platform (such as APNs or FCM) informs Amazon SNS that the device token used in the publish request was invalid, Amazon SNS disables the platform endpoint associated with that device token. Amazon SNS will then reject subsequent publishes to that device token. While you may think it is best to simply re-enable the platform endpoint and keep publishing, in most situations doing this will not work: the messages that are published do not get delivered and the platform endpoint becomes disabled again soon afterward. This is because the device token associated with the platform endpoint is genuinely invalid. Deliveries to it cannot succeed because it no longer corresponds to any installed app. The next time it is published to, the mobile platform will again inform Amazon SNS that the device token is invalid, and Amazon SNS will again disable the platform endpoint. To re-enable a disabled platform endpoint, it needs to be associated with a valid device token (with a set endpoint attributes action call) and then enabled. Only then will deliveries to that platform endpoint become successful. The only time re-enabling a platform endpoint without updating its device token will work is when a device token associated with that endpoint used to be invalid but then became valid again. This can happen, for example, when an app was uninstalled and then re- installed on the same mobile device and receives the same device token. The approach presented above does this, making sure
|
sns-dg-151
|
sns-dg.pdf
| 151 |
re-enable a disabled platform endpoint, it needs to be associated with a valid device token (with a set endpoint attributes action call) and then enabled. Only then will deliveries to that platform endpoint become successful. The only time re-enabling a platform endpoint without updating its device token will work is when a device token associated with that endpoint used to be invalid but then became valid again. This can happen, for example, when an app was uninstalled and then re- installed on the same mobile device and receives the same device token. The approach presented above does this, making sure to only re-enable a platform endpoint after verifying that the device token associated with it is the most current one available. Integrating device tokens with Amazon SNS for mobile notifications When you first register an app and mobile device with a notification service, such as Apple Push Notification Service (APNs) and Firebase Cloud Messaging (FCM), device tokens or registration IDs are returned by the service. These tokens/IDs are added to Amazon SNS to create an endpoint for the app and device, using the PlatformApplicationArn API. Once the endpoint is created, an EndpointArn is returned, which Amazon SNS uses to direct notifications to the correct app/ device. You can add device tokens or registration IDs to Amazon SNS in the following ways: • Manually add a single token via the AWS Management Console • Upload several tokens using the CreatePlatformEndpoint API Setting up a mobile app 531 Amazon Simple Notification Service Developer Guide • Register tokens for future devices To manually add a device token or registration ID 1. 2. 3. Sign in to the Amazon SNS console. In the navigation pane, select Push Notifications. In the Platform applications section, select your application, and then choose Edit. If you haven't already created a platform application, follow the Creating an Amazon SNS platform application guide to do so now. 4. Choose Create Endpoint. 5. 6. In the Endpoint Token box, enter the token or registration ID, depending on the notification service you're using (for example, FCM registration ID). (Optional) Enter additional data in the User Data field. This data must be UTF-8 encoded and less than 2 KB. 7. Choose Create Endpoint. Once the endpoint is created, you can send messages directly to the mobile device or to mobile devices subscribed to an Amazon SNS topic. To upload several tokens using the CreatePlatformEndpoint API The following steps show how to use the sample Java app (bulkupload package) provided by AWS to upload several tokens (device tokens or registration IDs) to Amazon SNS. You can use this sample app to help you get started with uploading your existing tokens. Note The following steps use the Eclipse Java IDE. The steps assume you have installed the AWS SDK for Java and you have the AWS security credentials for your AWS account. For more information, see AWS SDK for Java. For more information about credentials, see AWS security credentials in the IAM User Guide. 1. Download and unzip the snsmobilepush.zip file. 2. Create a new Java project in Eclipse and import the SNSSamples folder to the project. Setting up a mobile app 532 Amazon Simple Notification Service Developer Guide 3. Download the OpenCSV library and add it to the build path. 4. In the BulkUpload.properties file, specify the following: • Your ApplicationArn (platform application ARN). • The absolute path to your CSV file containing the tokens. • Logging filenames for successful and failed tokens. For example, goodTokens.csv and badTokens.csv. • (Optional) A configuration for delimiter, quote character, and number of threads to use. Your completed BulkUpload.properties should look similar to the following: applicationarn: arn:aws:sns:us-west-2:111122223333:app/FCM/fcmpushapp csvfilename: C:\\mytokendirectory\\mytokens.csv goodfilename: C:\\mylogfiles\\goodtokens.csv badfilename: C:\\mylogfiles\\badtokens.csv delimiterchar: ',' quotechar: '"' numofthreads: 5 5. Run the BatchCreatePlatformEndpointSample.java application to upload the tokens to Amazon SNS. Tokens uploaded successfully will be logged in goodTokens.csv, while malformed tokens will be logged in badTokens.csv. To register tokens from devices for future app installations You have two options for this process: Use the Amazon Cognito service Your mobile app can use temporary security credentials to create endpoints. Amazon Cognito is recommended to generate temporary credentials. For more information, see the Amazon Cognito Developer Guide To track app registrations, use Amazon SNS events to receive notifications when new endpoint ARNs are created. Alternatively, you can use the ListEndpointByPlatformApplication API to retrieve the list of registered endpoints. Setting up a mobile app 533 Amazon Simple Notification Service Use a proxy server Developer Guide If your app infrastructure already supports device registration on installation, you can use your server as a proxy. It will forward device tokens to Amazon SNS via the CreatePlatformEndpoint API. The endpoint ARN created by Amazon SNS will be returned and can be stored by your server for future message publishing. Amazon SNS Apple push
|
sns-dg-152
|
sns-dg.pdf
| 152 |
app registrations, use Amazon SNS events to receive notifications when new endpoint ARNs are created. Alternatively, you can use the ListEndpointByPlatformApplication API to retrieve the list of registered endpoints. Setting up a mobile app 533 Amazon Simple Notification Service Use a proxy server Developer Guide If your app infrastructure already supports device registration on installation, you can use your server as a proxy. It will forward device tokens to Amazon SNS via the CreatePlatformEndpoint API. The endpoint ARN created by Amazon SNS will be returned and can be stored by your server for future message publishing. Amazon SNS Apple push notification authentication methods You can authorize Amazon SNS to send push notifications to your iOS or macOS app by providing information that identifies you as the developer of the app. To authenticate, provide either a key or a certificate when creating a platform application, both of which you can get from your Apple Developer account. Token signing key A private signing key that Amazon SNS uses to sign Apple Push Notification Service (APNs) authentication tokens. If you provide a signing key, Amazon SNS uses a token to authenticate with APNs for every push notification that you send. With your signing key, you can send push notifications to APNs production and sandbox environments. Your signing key doesn't expire, and you can use the same signing key for multiple apps. For more information, see Communicate with APNs using authentication tokens in the Developer Account Help section of the Apple website. Certificate A TLS certificate that Amazon SNS uses to authenticate with APNs when you send push notifications. You obtain the certificate from your Apple Developer account. Certificates expire after one year. When this happens, you must create a new certificate and provide it to Amazon SNS. For more information, see Establishing a Certificate-Based Connection to APNs on the Apple Developer website. To manage APNs settings using the AWS Management Console 1. Sign in to the Amazon SNS console. Setting up a mobile app 534 Amazon Simple Notification Service Developer Guide 2. 3. In the navigation pane, select Push notifications. In the Platform applications section, select the application whose APNs settings you want to edit, and then choose Edit. If you haven't already created a platform application, follow the Creating an Amazon SNS platform application guide to do so now. 4. Choose Edit to modify the settings for your platform application. 5. In theAuthentication type section, choose one of the following options: • Token-based authentication (recommended for modern APNs integrations) • Certificate-based authentication (older method) 6. Configure your credentials based on the authentication type: • For token-based authentication: • Upload the .p8 file, which is the authentication token signing key you downloaded from your Apple Developer account. • Enter the Signing Key ID that you find in your Apple Developer account. Navigate to Certificates, IDs & Profiles, Keys, and select the key you want to use. • Provide the Team Identifier from your Apple Developer account. You can find this on the Membership page. • Enter the Bundle Identifier assigned to your app. You can find this under Certificates, IDs and Profiles, App IDs. • For certificate-based authentication: • Upload the .p12 file for your TLS certificate. This file can be exported from Keychain Access on macOS after downloading the certificate from your Apple Developer account. • If you assigned a password to your .p12 certificate, enter it here. 7. After entering the necessary credentials, choose Save changes to update the settings. Amazon SNS integration with Firebase Cloud Messaging authentication setup This topic describes how to obtain the required FCM API (HTTP v1) credentials from Google to use with the AWS API, AWS CLI and the AWS Management Console. Setting up a mobile app 535 Amazon Simple Notification Service Developer Guide Important March 26, 2024 – Amazon SNS supports FCM HTTP v1 API for Apple devices and Webpush destinations. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid application disruption. January 18, 2024 – Amazon SNS introduced support for FCM HTTP v1 API for mobile push notification delivery to Android devices. June 20, 2023 – Google deprecated their Firebase Cloud Messaging (FCM) legacy HTTP API. Amazon SNS now supports delivery to all device types using FCM HTTP v1 API. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid disruption. You can authorize Amazon SNS to send push notifications to your applications by providing information that identifies you as the developer of the app. To authenticate, provide either an API key or a token when creating a platform application. You can get the following information from your Firebase application console: API Key
|
sns-dg-153
|
sns-dg.pdf
| 153 |
their Firebase Cloud Messaging (FCM) legacy HTTP API. Amazon SNS now supports delivery to all device types using FCM HTTP v1 API. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid disruption. You can authorize Amazon SNS to send push notifications to your applications by providing information that identifies you as the developer of the app. To authenticate, provide either an API key or a token when creating a platform application. You can get the following information from your Firebase application console: API Key The API key is a credential used when calling Firebase’s Legacy API. The FCM Legacy APIs will be removed by Google June 20, 2024. If you are currently using an API key as your platform credential, you can update the platform credential by selecting Token as the option, and uploading the associated JSON file for your Firebase application. Token A short lived access token is used when calling the HTTP v1 API. This is Firebase’s suggested API for sending push notifications. In order to generate access tokens, Firebase provides developers a set of credentials in the form of a private key file (also referred to as a service.json file). Prerequisite You must obtain your FCM service.json credentials before you can begin managing FCM settings in Amazon SNS. To obtain your service.json credentials, see Migrate from legacy FCM APIs to HTTP v1 in the Google Firebase documentation. Setting up a mobile app 536 Amazon Simple Notification Service Developer Guide Managing FCM settings using the CLI You can create FCM push notifications using the AWS API. The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas in the AWS General Reference Guide. To create an FCM push notification together with an Amazon SNS topic (AWS API) When using key credentials, the PlatformCredential is API key. When using token credentials, the PlatformCredential is a JSON formatted private key file: • CreatePlatformApplication To retrieve an FCM credential type for an existing Amazon SNS topic (AWS API) Retrieves the credential type "AuthenticationMethod": "Token", or "AuthenticationMethod": "Key": • GetPlatformApplicationAttributes To set an FCM attribute for an existing Amazon SNS topic (AWS API) Sets the FCM attribute: • SetPlatformApplicationAttributes Managing FCM settings using the console You can create FCM push notifications using the AWS Command Line Interface (CLI). The number and size of Amazon SNS resources in an AWS account are limited. For more information, see Amazon Simple Notification Service endpoints and quotas. To create an FCM push notification together with an Amazon SNS topic (AWS CLI) When using key credentials, the PlatformCredential is API key. When using token credentials, the PlatformCredential is a JSON formatted private key file. When using the AWS CLI, the file must be in string format and special characters must be ignored. To format the file correctly,Amazon SNS recommends using the following command: SERVICE_JSON=`jq @json <<< cat service.json`: Setting up a mobile app 537 Amazon Simple Notification Service • create-platform-application Developer Guide To retrieve an FCM credential type for an existing Amazon SNS topic (AWS CLI) Retrieves the credential type "AuthenticationMethod": "Token", or "AuthenticationMethod": "Key": • get-platform-application-attributes To set an FCM attribute for an existing Amazon SNS topic (AWS CLI) Sets the FCM attribute: • set-platform-application-attributes Managing FCM settings (console) Use the following steps to enter and manage your Firebase Cloud Messaging (FCM) credentials in Amazon SNS. 1. 2. 3. Sign in to the Amazon SNS console. In the navigation pane, select Push Notifications. In the Platform applications section, select the FCM platform application whose credentials you want to edit, and then choose Edit. 4. In the Firebase Cloud Messaging Credentials section, choose one of the following options: • Token-based authentication (recommended method) – Upload the private key file (JSON) that you downloaded from the Firebase Console. This file contains the credentials needed to generate short-lived access tokens for FCM notifications. To get this file: 1. Go to your Firebase application console. 2. In the Project Settings, select Cloud Messaging. 3. Download the Private key JSON file (for use in the token-based authentication method). • API key authentication – If you prefer to use the older API key authentication method, enter the Google API key in the provided field. To get this file: 1. Go to your Firebase application console. 2. In Project Settings, select Cloud Messaging. Setting up a mobile app 538 Amazon Simple Notification Service Developer Guide 3. Copy the Server key (API key) to use for sending notifications. 5. When you finish, choose Save changes. Related topics • Using Google Firebase Cloud Messaging v1 payloads in Amazon SNS Amazon SNS management of Firebase Cloud Messaging endpoints Managing and maintaining device tokens You can ensure
|
sns-dg-154
|
sns-dg.pdf
| 154 |
authentication – If you prefer to use the older API key authentication method, enter the Google API key in the provided field. To get this file: 1. Go to your Firebase application console. 2. In Project Settings, select Cloud Messaging. Setting up a mobile app 538 Amazon Simple Notification Service Developer Guide 3. Copy the Server key (API key) to use for sending notifications. 5. When you finish, choose Save changes. Related topics • Using Google Firebase Cloud Messaging v1 payloads in Amazon SNS Amazon SNS management of Firebase Cloud Messaging endpoints Managing and maintaining device tokens You can ensure deliverability of your mobile application's push notifications by following these steps: 1. Store all device tokens, corresponding Amazon SNS endpoint ARNs, and timestamps on your application server. 2. Remove all stale tokens and delete the corresponding Amazon SNS endpoint ARNs. Upon your app's initial start-up, you'll receive a device token (also referred to as registration token) for the device. This device token is minted by the device’s operating system, and is tied to your FCM application. Once you receive this device token, you can register it with Amazon SNS as a platform endpoint. We recommend that you store the device token, the Amazon SNS platform endpoint ARN, and the timestamp by saving the them to your application server, or another persistent store. To set-up your FCM application to retrieve and store device tokens, see Retrieve and store registration tokens in Google's Firebase documentation. It's important that you maintain up-to-date tokens. Your user’s device tokens can change under the following conditions: 1. The mobile application is restored on a new device. 2. The user uninstalls or updates the application. 3. The user clears application data. When your device token changes, we recommended that you update the corresponding Amazon SNS endpoint with the new token. This allows Amazon SNS to continue communication to the registered device. You can do this by implementing the following pseudo code within your mobile Setting up a mobile app 539 Amazon Simple Notification Service Developer Guide application. It describes a recommended practice for creating and maintaining enabled platform endpoints. This approach can be executed each time the mobile applications starts, or as a scheduled job in the background. Pseudo code Use the following FCM pseudo code to manage and maintain device tokens. retrieve the latest token from the mobile OS if (endpoint arn not stored) # first time registration call CreatePlatformEndpoint store returned endpoint arn endif call GetEndpointAttributes on the endpoint arn if (getting attributes encountered NotFound exception) #endpoint was deleted call CreatePlatformEndpoint store returned endpoint arn else if (token in endpoint does not match latest) or (GetEndpointAttributes shows endpoint as disabled) call SetEndpointAttributes to set the latest token and enable the endpoint endif endif To learn more about token update requirements, see Update Tokens on a Regular Basis in Google's Firebase documentation. Detecting invalid tokens When a message is dispatched to an FCM v1 endpoint with an invalid device token, Amazon SNS will receive one of the following exceptions: • UNREGISTERED (HTTP 404) – When Amazon SNS receives this exception, you will receive a delivery failure event with a FailureType of InvalidPlatformToken, and a FailureMessage of Platform token associated with the endpoint is not valid. Amazon SNS will disable your platform endpoint when a delivery fails with this exception. Setting up a mobile app 540 Amazon Simple Notification Service Developer Guide • INVALID_ARGUMENT (HTTP 400) – When Amazon SNS receives this exception, it means that the device token or the message payload is invalid. For more information, see ErrorCode in Google's Firebase documentation. Since INVALID_ARGUMENT can be returned in either of these cases, Amazon SNS will return a FailureType of InvalidNotification, and a FailureMessage of Notification body is invalid. When you receive this error, verify that your payload is correct. If it is correct, verify that the device token is up-to-date. Amazon SNS will not disable your platform endpoint when a delivery fails with this exception. Another case where you will experience an InvalidPlatformToken delivery failure event is when the registered device token doesn't belong to the application attempting to send that message. In this case, Google will return a SENDER_ID_MISMATCH error. Amazon SNS will disable your platform endpoint when a delivery fails with this exception. All observed error codes received from the FCM v1 API are available to you in CloudWatch when you set up delivery status logging for your application. To receive delivery events for your application, see Available application events. Removing stale tokens Tokens are considered stale once message deliveries to the endpoint device start failing. Amazon SNS sets these stale tokens as disabled endpoints for your platform application. When you publish to a disabled endpoint, Amazon SNS will return a EventDeliveryFailure event with the FailureType of EndpointDisabled, and a FailureMessage of Endpoint
|
sns-dg-155
|
sns-dg.pdf
| 155 |
your platform endpoint when a delivery fails with this exception. All observed error codes received from the FCM v1 API are available to you in CloudWatch when you set up delivery status logging for your application. To receive delivery events for your application, see Available application events. Removing stale tokens Tokens are considered stale once message deliveries to the endpoint device start failing. Amazon SNS sets these stale tokens as disabled endpoints for your platform application. When you publish to a disabled endpoint, Amazon SNS will return a EventDeliveryFailure event with the FailureType of EndpointDisabled, and a FailureMessage of Endpoint is disabled. To receive delivery events for your application, see Available application events. When you receive this error from Amazon SNS, you need to remove or update the stale token in your platform application. Using Amazon SNS for mobile push notifications This section describes how to send mobile push notifications. Publishing to a topic You can also use Amazon SNS to send messages to mobile endpoints subscribed to a topic. The concept is the same as subscribing other endpoint types, such as Amazon SQS, HTTP/S, email, Using Amazon SNS for mobile push notifications 541 Amazon Simple Notification Service Developer Guide and SMS, to a topic, as described in What is Amazon SNS?. The difference is that Amazon SNS communicates through notification services like Apple Push Notification Service (APNS) and Google Firebase Cloud Messaging (FCM). Through the notifications service, the subscribed mobile endpoints receive notifications sent to the topic. Direct Amazon SNS mobile device messaging You can send Amazon SNS push notification messages directly to an endpoint which represents an application on a mobile device. To send a direct message 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Push notifications. 3. On the Mobile push notifications page, in the Platform applications section, choose the name of the application, for example MyApp. 4. On the MyApp page, in the Endpoints section, choose an endpoint and then choose Publish message. 5. On the Publish message to endpoint page, enter the message that will appear in the application on the mobile device and then choose Publish message. Amazon SNS sends the notification message to the platform notification service which, in turn, sends the message to the application. Publishing Amazon SNS notifications with platform-specific payloads You can use the AWS Management Console or Amazon SNS APIs to send custom messages with platform-specific payloads to mobile devices. For information about using the Amazon SNS APIs, see Mobile push API actions and the SNSMobilePush.java file in snsmobilepush.zip. Sending JSON-formatted messages When you send platform-specific payloads, the data must be formatted as JSON key-value pair strings, with the quotation marks escaped. The following examples show a custom message for the FCM platform. { Using Amazon SNS for mobile push notifications 542 Amazon Simple Notification Service Developer Guide "GCM": "{\"fcmV1Message\": {\"message\": {\"notification\": {\"title\": \"Hello\", \"body\": \"This is a test.\"}, \"data\": {\"dataKey\": \"example\"}}}}" } Sending platform-specific messages In addition to sending custom data as key-value pairs, you can send platform-specific key-value pairs. The following example shows the inclusion of the FCM parameters time_to_live and collapse_key after the custom data key-value pairs in the FCM data parameter. { "GCM": "{\"fcmV1Message\": {\"message\": {\"notification\": {\"title\": \"TitleTest\", \"body\": \"Sample message for Android or iOS endpoints.\"}, \"data\":{\"time_to_live \": 3600,\"collapse_key\":\"deals\"}}}}" } For a list of the key-value pairs supported by each of the push notification services supported in Amazon SNS, see the following: Important Amazon SNS now supports Firebase Cloud Messaging (FCM) HTTP v1 API for sending mobile push notifications to Android devices. March 26, 2024 – Amazon SNS supports FCM HTTP v1 API for Apple devices and Webpush destinations. We recommend that you migrate your existing mobile push applications to the latest FCM HTTP v1 API on or before June 1, 2024 to avoid application disruption. • Payload Key Reference in the APNs documentation • Firebase Cloud Messaging HTTP Protocol in the FCM documentation • Send a Message in the ADM documentation Sending messages to an application on multiple platforms To send a message to an application installed on devices for multiple platforms, such as FCM and APNs, you must first subscribe the mobile endpoints to a topic in Amazon SNS and then publish the message to the topic. Using Amazon SNS for mobile push notifications 543 Amazon Simple Notification Service Developer Guide The following example shows a message to send to subscribed mobile endpoints on APNs, FCM, and ADM: { "default": "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.", "APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\": \"www.amazon.com\"} }", "GCM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\": \"www.amazon.com\"}}", "ADM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\":
|
sns-dg-156
|
sns-dg.pdf
| 156 |
Amazon SNS and then publish the message to the topic. Using Amazon SNS for mobile push notifications 543 Amazon Simple Notification Service Developer Guide The following example shows a message to send to subscribed mobile endpoints on APNs, FCM, and ADM: { "default": "This is the default message which must be present when publishing a message to a topic. The default message will only be used if a message is not present for one of the notification platforms.", "APNS": "{\"aps\":{\"alert\": \"Check out these awesome deals!\",\"url\": \"www.amazon.com\"} }", "GCM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\": \"www.amazon.com\"}}", "ADM": "{\"data\":{\"message\":\"Check out these awesome deals!\",\"url\": \"www.amazon.com\"}}" } Sending messages to APNs as alert or background notifications Amazon SNS can send messages to APNs as alert or background notifications (for more information, see Pushing Background Updates to Your App in the APNs documentation). • An alert APNs notification informs the user by displaying an alert message, playing a sound, or adding a badge to your application’s icon. • A background APNs notification wakes up or instructs your application to act upon the content of the notification, without informing the user. Specifying custom APNs header values We recommend specifying custom values for the AWS.SNS.MOBILE.APNS.PUSH_TYPE reserved message attribute using the Amazon SNS Publish API action, AWS SDKs, or the AWS CLI. The following CLI example sets content-available to 1 and apns-push-type to background for the specified topic. aws sns publish \ --endpoint-url https://sns.us-east-1.amazonaws.com \ --target-arn arn:aws:sns:us-east-1:123456789012:endpoint/APNS_PLATFORM/MYAPP/1234a567- bc89-012d-3e45-6fg7h890123i \ --message '{"APNS_PLATFORM":"{\"aps\":{\"content-available\":1}}"}' \ --message-attributes '{ \ "AWS.SNS.MOBILE.APNS.TOPIC": {"DataType":"String","StringValue":"com.amazon.mobile.messaging.myapp"}, \ Using Amazon SNS for mobile push notifications 544 Amazon Simple Notification Service Developer Guide "AWS.SNS.MOBILE.APNS.PUSH_TYPE":{"DataType":"String","StringValue":"background"}, \ "AWS.SNS.MOBILE.APNS.PRIORITY":{"DataType":"String","StringValue":"5"}}' \ --message-structure json Note Ensure that the JSON structure is valid. Add a comma after each key-value pair, except the last one. Inferring the APNs push type header from the payload If you don't set the apns-push-type APNs header, Amazon SNS sets header to alert or background depending on the content-available key in the aps dictionary of your JSON- formatted APNs payload configuration. Note Amazon SNS is able to infer only alert or background headers, although the apns- push-type header can be set to other values. • apns-push-type is set to alert • If the aps dictionary contains content-available set to 1 and one or more keys that trigger user interactions. • If the aps dictionary contains content-available set to 0 or if the content-available key is absent. • If the value of the content-available key isn’t an integer or a Boolean. • apns-push-type is set to background • If the aps dictionary only contains content-available set to 1 and no other keys that trigger user interactions. Important If Amazon SNS sends a raw configuration object for APNs as a background-only notification, you must include content-available set to 1 in the aps dictionary. Using Amazon SNS for mobile push notifications 545 Amazon Simple Notification Service Developer Guide Although you can include custom keys, the aps dictionary must not contain any keys that trigger user interactions (for example, alerts, badges, or sounds). The following is an example raw configuration object. { "APNS": "{\"aps\":{\"content-available\":1},\"Foo1\":\"Bar\",\"Foo2\":123}" } In this example, Amazon SNS sets the apns-push-type APNs header for the message to background. When Amazon SNS detects that the apn dictionary contains the content- available key set to 1—and doesn't contain any other keys that can trigger user interactions—it sets the header to background. Using Google Firebase Cloud Messaging v1 payloads in Amazon SNS Amazon SNS supports using FCM HTTP v1 API to send notifications to Android, iOS, and Webpush destinations. This topic provides examples of the payload structure when publishing mobile push notifications using the CLI, or the Amazon SNS API. You can include the following message types in your payload when sending an FCM notification: • Data message – A data message is handled by your client app and contains custom key-value pairs. When constructing a data message, you must include the data key with a JSON object as the value, and then enter your custom key-value pairs. • Notification message or display message – A notification message contains a predefined set of keys handled by the FCM SDK. These keys vary depending on the device type to which you are delivering. For more information on platform-specific notification keys, see the following: • Android notification keys • APNS notification keys • Webpush notification keys For more information about FCM message types, see Message types in the in Google's Firebase documentation. Using Amazon SNS for mobile push notifications 546 Amazon Simple Notification Service Developer Guide Using the FCM v1 payload structure to send messages If you are creating an FCM application for the first time, or wish to take advantage of FCM v1 features, you can opt-in to send an FCM v1 formatted payload. To do this, you must include the top-level key fcmV1Message. For more information about
|
sns-dg-157
|
sns-dg.pdf
| 157 |
notification keys, see the following: • Android notification keys • APNS notification keys • Webpush notification keys For more information about FCM message types, see Message types in the in Google's Firebase documentation. Using Amazon SNS for mobile push notifications 546 Amazon Simple Notification Service Developer Guide Using the FCM v1 payload structure to send messages If you are creating an FCM application for the first time, or wish to take advantage of FCM v1 features, you can opt-in to send an FCM v1 formatted payload. To do this, you must include the top-level key fcmV1Message. For more information about constructing FCM v1 payloads, see Migrate from legacy FCM APIs to HTTP v1 and Customizing a message across platforms in Google's Firebase documentation. FCM v1 example payload sent to Amazon SNS: Note The GCM key value used in the following example must be encoded as a String when publishing a notification using Amazon SNS. { "GCM": "{ \"fcmV1Message\": { \"validate_only\": false, \"message\": { \"notification\": { \"title\": \"string\", \"body\": \"string\" }, \"data\": { \"dataGen\": \"priority message\" }, \"android\": { \"priority\": \"high\", \"notification\": { \"body_loc_args\": [\"string\"], \"title_loc_args\": [\"string\"], \"sound\": \"string\", \"title_loc_key\": \"string\", \"title\": \"string\", \"body\": \"string\", \"click_action\": \"clicky_clacky\", \"body_loc_key\": \"string\" }, \"data\": { \"dataAndroid\": \"priority message\" Using Amazon SNS for mobile push notifications 547 Amazon Simple Notification Service Developer Guide }, \"ttl\": \"10023.32s\" }, \"apns\": { \"payload\": { \"aps\": { \"alert\": { \"subtitle\": \"string\", \"title-loc-args\": [\"string\"], \"title-loc-key\": \"string\", \"loc-args\": [\"string\"], \"loc-key\": \"string\", \"title\": \"string\", \"body\": \"string\" }, \"category\": \"Click\", \"content-available\": 0, \"sound\": \"string\", \"badge\": 5 } } }, \"webpush\": { \"notification\": { \"badge\": \"5\", \"title\": \"string\", \"body\": \"string\" }, \"data\": { \"dataWeb\": \"priority message\" } } } } }" } When sending a JSON payload, be sure to include the message-structure attribute in your request, and set it to json. CLI example: Using Amazon SNS for mobile push notifications 548 Amazon Simple Notification Service Developer Guide aws sns publish --topic $TOPIC_ARN --message '{"GCM": "{\"fcmV1Message\": {\"message\": {\"notification\":{\"title\":\"string\",\"body\":\"string\"},\"android\":{\"priority \":\"high\",\"notification\":{\"title\":\"string\",\"body\":\"string\"},\"data\": {\"customAndroidDataKey\":\"custom key value\"},\"ttl\":\"0s\"},\"apns\":{\"payload \":{\"aps\":{\"alert\":{\"title\":\"string\", \"body\":\"string\"},\"content- available\":1,\"badge\":5}}},\"webpush\":{\"notification\":{\"badge\":\"URL\",\"body \":\"Test\"},\"data\":{\"customWebpushDataKey\":\"priority message\"}},\"data\": {\"customGeneralDataKey\":\"priority message\"}}}}", "default": "{\"notification\": {\"title\": \"test\"}"}' --region $REGION --message-structure json For more information on sending FCM v1 formatted payloads, see the following in Google's Firebase documentation: • Migrate from legacy FCM APIs to HTTP v1 • About FCM messages • REST Resource: projects.messages Using the legacy payload structure to send messages to the FCM v1 API When migrating to FCM v1, you don't have to change the payload structure that you were using for your legacy credentials. Amazon SNS transforms your payload into the new FCM v1 payload structure, and sends to Google. Input message payload format: { "GCM": "{\"notification\": {\"title\": \"string\", \"body\": \"string\", \"android_channel_id\": \"string\", \"body_loc_args\": [\"string\"], \"body_loc_key\": \"string\", \"click_action\": \"string\", \"color\": \"string\", \"icon\": \"string \", \"sound\": \"string\", \"tag\": \"string\", \"title_loc_args\": [\"string\"], \"title_loc_key\": \"string\"}, \"data\": {\"message\": \"priority message\"}}" } Message sent to Google: { "message": { "token": "***", "notification": { "title": "string", Using Amazon SNS for mobile push notifications 549 Amazon Simple Notification Service Developer Guide "body": "string" }, "android": { "priority": "high", "notification": { "body_loc_args": [ "string" ], "title_loc_args": [ "string" ], "color": "string", "sound": "string", "icon": "string", "tag": "string", "title_loc_key": "string", "title": "string", "body": "string", "click_action": "string", "channel_id": "string", "body_loc_key": "string" }, "data": { "message": "priority message" } }, "apns": { "payload": { "aps": { "alert": { "title-loc-args": [ "string" ], "title-loc-key": "string", "loc-args": [ "string" ], "loc-key": "string", "title": "string", "body": "string" }, "category": "string", "sound": "string" } Using Amazon SNS for mobile push notifications 550 Developer Guide Amazon Simple Notification Service } }, "webpush": { "notification": { "icon": "string", "tag": "string", "body": "string", "title": "string" }, "data": { "message": "priority message" } }, "data": { "message": "priority message" } } } Potential risks • Legacy to v1 mapping doesn't support the Apple Push Notification Service (APNS) headers or the fcm_options keys. If you'd like to use these fields, send an FCM v1 payload. • In some cases, message headers are required by FCM v1 to send silent notifications to your APNs devices. If you are currently sending silent notifications to your APNs devices, they will not work with the legacy approach. Instead, we recommend using the FCM v1 payload to avoid unexpected issues. To find a list of APNs headers and what they are used for, see Communicating with APNs in the Apple Developer Guide. • If you are using the TTL Amazon SNS attribute when sending your notification, it will only be updated in the android field. If you'd like to set the TTL APNS attribute, use the FCM v1 payload. • The android, apns, and webpush keys will be mapped and populated with all relevant keys provided. For example, if you provide title, which is a key shared among all three platforms, the FCM v1 mapping will populate all three platforms with the title you provided. • Some shared keys
|
sns-dg-158
|
sns-dg.pdf
| 158 |
they are used for, see Communicating with APNs in the Apple Developer Guide. • If you are using the TTL Amazon SNS attribute when sending your notification, it will only be updated in the android field. If you'd like to set the TTL APNS attribute, use the FCM v1 payload. • The android, apns, and webpush keys will be mapped and populated with all relevant keys provided. For example, if you provide title, which is a key shared among all three platforms, the FCM v1 mapping will populate all three platforms with the title you provided. • Some shared keys among platforms expect different value types. For example, the badge key passed to apns expects an integer value, while the badge key passed to webpush expects a String value. In cases where you provide the badge key, the FCM v1 mapping will only populate the key for which you provided a valid value. Using Amazon SNS for mobile push notifications 551 Amazon Simple Notification Service FCM delivery failure events Developer Guide The following table provides the Amazon SNS failure type that corresponds to the error/status codes received from Google for FCM v1 notification requests. All observed error codes received from the FCM v1 API are available to you in CloudWatch when you set-up delivery status logging for your application. FCM error/status code Amazon SNS failure type Failure message Cause and mitigatio n UNREGISTERED InvalidPl atformToken Platform token associated with the The device token attached to your endpoint is not valid. endpoint is stale or invalid. Amazon SNS disabled your endpoint. Update the Amazon SNS endpoint to the newest device token. INVALID_A RGUMENT InvalidNo tification Notification body is invalid. The device token or message payload SENDER_ID _MISMATCH InvalidPl atformToken Platform token associated with the endpoint is not valid. may be invalid. Verify that your message payload is valid. If the message payload is valid, update the Amazon SNS endpoint to the newest device token. The platform application associate d with the device token doesn't have permission to send to the device token. Verify that you are Using Amazon SNS for mobile push notifications 552 Amazon Simple Notification Service Developer Guide FCM error/status code Amazon SNS failure type Failure message UNAVAILABLE Dependenc yUnavailable Dependency is not available. Cause and mitigatio n using the correct FCM credentials in your Amazon SNS platform application. FCM couldn't process the request in time. All the retries executed by Amazon SNS have failed. You can store these messages in a dead- letter queue (DLQ) and redrive them later. INTERNAL Unexpecte dFailure Unexpected failure; please contact The FCM server encountered an Amazon. Failure error while trying phrase [Internal Error]. to process your request. All the retries executed by Amazon SNS have failed. You can store these messages in a dead-letter queue (DLQ) and redrive them later. Using Amazon SNS for mobile push notifications 553 Amazon Simple Notification Service Developer Guide FCM error/status code Amazon SNS failure type Failure message Cause and mitigatio n THIRD_PAR InvalidCr TY_AUTH_ERROR edentials Platform application credentials are not A message targeted to an iOS device or valid. QUOTA_EXCEEDED Throttled Request throttled by [gcm]. a Webpush device could not be sent. Verify that your development and production credentia ls are valid. A message rate quota, device message rate quota, or topic message rate quota has been exceeded. For information on how to resolve this issue, see ErrorCode in the in Google's Firebase documentation. Using Amazon SNS for mobile push notifications 554 Amazon Simple Notification Service Developer Guide FCM error/status code Amazon SNS failure type Failure message Cause and mitigatio n PERMISSIO N_DENIED InvalidNo tification Notification body is invalid. In the case of a PERMISSIO N_DENIED exception, the caller (your FCM application) doesn't have permission to execute the specified operation in the payload. Navigate to your FCM console, and verify your credentials have the required API actions enabled. Amazon SNS mobile app attributes Amazon Simple Notification Service (Amazon SNS) provides support to log the delivery status of push notification messages. After you configure application attributes, log entries will be sent to CloudWatch Logs for messages sent from Amazon SNS to mobile endpoints. Logging message delivery status helps provide better operational insight, such as the following: • Know whether a push notification message was delivered from Amazon SNS to the push notification service. • Identify the response sent from the push notification service to Amazon SNS. • Determine the message dwell time (the time between the publish timestamp and just before handing off to a push notification service). To configure application attributes for message delivery status, you can use the AWS Management Console, AWS software development kits (SDKs), or query API. Mobile app attributes 555 Amazon Simple Notification Service Developer Guide Configuring message delivery status attributes using the AWS Management Console 1. Sign in to the Amazon
|
sns-dg-159
|
sns-dg.pdf
| 159 |
Know whether a push notification message was delivered from Amazon SNS to the push notification service. • Identify the response sent from the push notification service to Amazon SNS. • Determine the message dwell time (the time between the publish timestamp and just before handing off to a push notification service). To configure application attributes for message delivery status, you can use the AWS Management Console, AWS software development kits (SDKs), or query API. Mobile app attributes 555 Amazon Simple Notification Service Developer Guide Configuring message delivery status attributes using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, point to Mobile, and then choose Push notifications. 3. From the Platform applications section, choose the application that contains the endpoints for which you want receive CloudWatch Logs. 4. Choose Application Actions and then choose Delivery Status. 5. On the Delivery Status dialog box, choose Create IAM Roles. You will then be redirected to the IAM console. 6. Choose Allow to give Amazon SNS write access to use CloudWatch Logs on your behalf. 7. Now, back on the Delivery Status dialog box, enter a number in the Percentage of Success to Sample (0-100) field for the percentage of successful messages sent for which you want to receive CloudWatch Logs. Note After you configure application attributes for message delivery status, all failed message deliveries generate CloudWatch Logs. 8. Finally, choose Save Configuration. You will now be able to view and parse the CloudWatch Logs containing the message delivery status. For more information about using CloudWatch, see the CloudWatch Documentation. Amazon SNS message delivery status CloudWatch log examples After you configure message delivery status attributes for an application endpoint, CloudWatch Logs will be generated. Example logs, in JSON format, are shown as follows: SUCCESS { "status": "SUCCESS", "notification": { "timestamp": "2015-01-26 23:07:39.54", "messageId": "9655abe4-6ed6-5734-89f7-e6a6a42de02a" Mobile app attributes 556 Amazon Simple Notification Service }, "delivery": { "statusCode": 200, "dwellTimeMs": 65, Developer Guide "token": "Examplei7fFachkJ1xjlqT64RaBkcGHochmf1VQAr9k- IBJtKjp7fedYPzEwT_Pq3Tu0lroqro1cwWJUvgkcPPYcaXCpPWmG3Bqn- wiqIEzp5zZ7y_jsM0PKPxKhddCzx6paEsyay9Zn3D4wNUJb8m6HXrBf9dqaEw", "attempts": 1, "providerResponse": "{\"multicast_id\":5138139752481671853,\"success \":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\": \"0:1422313659698010%d6ba8edff9fd7ecd\"}]}", "destination": "arn:aws:sns:us-east-2:111122223333:endpoint/FCM/FCMPushApp/ c23e42de-3699-3639-84dd-65f84474629d" } } FAILURE { "status": "FAILURE", "notification": { "timestamp": "2015-01-26 23:29:35.678", "messageId": "c3ad79b0-8996-550a-8bfa-24f05989898f" }, "delivery": { "statusCode": 8, "dwellTimeMs": 1451, "token": "examp1e29z6j5c4df46f80189c4c83fjcgf7f6257e98542d2jt3395kj73", "attempts": 1, "providerResponse": "NotificationErrorResponse(command=8, status=InvalidToken, id=1, cause=null)", "destination": "arn:aws:sns:us-east-2:111122223333:endpoint/APNS_SANDBOX/ APNSPushApp/986cb8a1-4f6b-34b1-9a1b-d9e9cb553944" } } For a list of push notification service response codes, see Platform response codes. Configuring message delivery status attributes with the AWS SDKs The AWS SDKs provide APIs in several languages for using message delivery status attributes with Amazon SNS. Mobile app attributes 557 Amazon Simple Notification Service Developer Guide The following Java example shows how to use the SetPlatformApplicationAttributes API to configure application attributes for message delivery status of push notification messages. You can use the following attributes for message delivery status: SuccessFeedbackRoleArn, FailureFeedbackRoleArn, and SuccessFeedbackSampleRate. The SuccessFeedbackRoleArn and FailureFeedbackRoleArn attributes are used to give Amazon SNS write access to use CloudWatch Logs on your behalf. The SuccessFeedbackSampleRate attribute is for specifying the sample rate percentage (0-100) of successfully delivered messages. After you configure the FailureFeedbackRoleArn attribute, then all failed message deliveries generate CloudWatch Logs. SetPlatformApplicationAttributesRequest setPlatformApplicationAttributesRequest = new SetPlatformApplicationAttributesRequest(); Map<String, String> attributes = new HashMap<>(); attributes.put("SuccessFeedbackRoleArn", "arn:aws:iam::111122223333:role/SNS_CWlogs"); attributes.put("FailureFeedbackRoleArn", "arn:aws:iam::111122223333:role/SNS_CWlogs"); attributes.put("SuccessFeedbackSampleRate", "5"); setPlatformApplicationAttributesRequest.withAttributes(attributes); setPlatformApplicationAttributesRequest.setPlatformApplicationArn("arn:aws:sns:us- west-2:111122223333:app/FCM/FCMPushApp"); sns.setPlatformApplicationAttributes(setPlatformApplicationAttributesRequest); For more information about the SDK for Java, see Getting Started with the AWS SDK for Java. Platform response codes The following is a list of links for the push notification service response codes: Push notification service Response codes Amazon Device Messaging (ADM) Apple Push Notification Service (APNs) Firebase Cloud Messaging (FCM) See Response Format in the ADM documenta tion. See HTTP/2 Response from APNs in Communicating with APNs in the Local and Remote Notification Programming Guide. See Downstream Message Error Response Codes in the Firebase Cloud Messaging documentation. Mobile app attributes 558 Amazon Simple Notification Service Developer Guide Push notification service Response codes Microsoft Push Notification Service for Windows Phone (MPNS) See Push Notification Service Response Codes for Windows Phone 8 in the Windows 8 Windows Push Notification Services (WNS) Development documentation. See "Response codes" in Push Notification Service Request and Response Headers (Windows Runtime Apps) in the Windows 8 Development documentation. Amazon SNS application event notifications for mobile applications Amazon SNS provides support to trigger notifications when certain application events occur. You can then take some programmatic action on that event. Your application must include support for a push notification service such as Apple Push Notification Service (APNs), Firebase Cloud Messaging (FCM), and Windows Push Notification Services (WNS). You set application event notifications using the Amazon SNS console, AWS CLI, or the AWS SDKs. Available application events Application event notifications track when individual platform endpoints are created, deleted, and updated, as well as delivery failures. The following are the attribute names for the application events. Attribute name Notification trigger EventEndp ointCreated EventEndp ointDeleted EventEndp ointUpdated EventDeli veryFailure Mobile app
|
sns-dg-160
|
sns-dg.pdf
| 160 |
events occur. You can then take some programmatic action on that event. Your application must include support for a push notification service such as Apple Push Notification Service (APNs), Firebase Cloud Messaging (FCM), and Windows Push Notification Services (WNS). You set application event notifications using the Amazon SNS console, AWS CLI, or the AWS SDKs. Available application events Application event notifications track when individual platform endpoints are created, deleted, and updated, as well as delivery failures. The following are the attribute names for the application events. Attribute name Notification trigger EventEndp ointCreated EventEndp ointDeleted EventEndp ointUpdated EventDeli veryFailure Mobile app events A new platform endpoint is added to your application. Any platform endpoint associated with your application is deleted. Any of the attributes of the platform endpoints associated with your application are changed. A delivery to any of the platform endpoints associated with your application encounters a permanent failure. 559 Amazon Simple Notification Service Developer Guide Attribute name Notification trigger Note To track delivery failures on the platform application side, subscribe to message delivery status events for the applicati on. For more information, see Using Amazon SNS Application Attributes for Message Delivery Status. You can associate any attribute with an application which can then receive these event notifications. Sending mobile push notifications To send application event notifications, you specify a topic to receive the notifications for each type of event. As Amazon SNS sends the notifications, the topic can route them to endpoints that will take programmatic action. Important High-volume applications will create a large number of application event notifications (for example, tens of thousands), which will overwhelm endpoints meant for human use, such as email addresses, phone numbers, and mobile applications. Consider the following guidelines when you send application event notifications to a topic: • Each topic that receives notifications should contain only subscriptions for programmatic endpoints, such as HTTP or HTTPS endpoints, Amazon SQS queues, or AWS Lambda functions. • To reduce the amount of processing that is triggered by the notifications, limit each topic's subscriptions to a small number (for example, five or fewer). You can send application event notifications using the Amazon SNS console, the AWS Command Line Interface (AWS CLI), or the AWS SDKs. AWS Management Console 1. Sign in to the Amazon SNS console. Mobile app events 560 Amazon Simple Notification Service Developer Guide 2. On the navigation panel, choose Mobile, Push notifications. 3. On the Mobile push notifications page, in the Platform applications section, choose an application and then choose Edit. 4. Expand the Event notifications section. 5. Choose Actions, Configure events. 6. Enter the ARNs for topics to be used for the following events: • Endpoint Created • Endpoint Deleted • Endpoint Updated • Delivery Failure 7. Choose Save changes. AWS CLI Run the set-platform-application-attributes command. The following example sets the same Amazon SNS topic for all four application events: aws sns set-platform-application-attributes --platform-application-arn arn:aws:sns:us-east-1:12345EXAMPLE:app/FCM/ MyFCMPlatformApplication --attributes EventEndpointCreated="arn:aws:sns:us- east-1:12345EXAMPLE:MyFCMPlatformApplicationEvents", EventEndpointDeleted="arn:aws:sns:us- east-1:12345EXAMPLE:MyFCMPlatformApplicationEvents", EventEndpointUpdated="arn:aws:sns:us- east-1:12345EXAMPLE:MyFCMPlatformApplicationEvents", EventDeliveryFailure="arn:aws:sns:us- east-1:12345EXAMPLE:MyFCMPlatformApplicationEvents" AWS SDKs Set application event notifications by submitting a SetPlatformApplicationAttributes request with the Amazon SNS API using an AWS SDK. For a complete list of AWS SDK developer guides and code examples, including help getting started and information about previous versions, see Using Amazon SNS with an AWS SDK. Mobile app events 561 Amazon Simple Notification Service Developer Guide Mobile push API actions To use the Amazon SNS mobile push APIs, you must first meet the prerequisites for the push notification service, such as Apple Push Notification Service (APNs) and Firebase Cloud Messaging (FCM). For more information about the prerequisites, see Prerequisites for Amazon SNS user notifications. To send a push notification message to a mobile app and device using the APIs, you must first use the CreatePlatformApplication action, which returns a PlatformApplicationArn attribute. The PlatformApplicationArn attribute is then used by CreatePlatformEndpoint, which returns an EndpointArn attribute. You can then use the EndpointArn attribute with the Publish action to send a notification message to a mobile app and device, or you could use the EndpointArn attribute with the Subscribe action for subscription to a topic. For more information, see Setting up push notifications with Amazon SNS. The Amazon SNS mobile push APIs are as follows: CreatePlatformApplication Creates a platform application object for one of the supported push notification services, such as APNs and FCM, to which devices and mobile apps may register. Returns a PlatformApplicationArn attribute, which is used by the CreatePlatformEndpoint action. CreatePlatformEndpoint Creates an endpoint for a device and mobile app on one of the supported push notification services. CreatePlatformEndpoint uses the PlatformApplicationArn attribute returned from the CreatePlatformApplication action. The EndpointArn attribute, which is returned when using CreatePlatformEndpoint, is then used with the Publish action to send a notification message to a mobile app and device. CreateTopic Creates a topic to which messages can be
|
sns-dg-161
|
sns-dg.pdf
| 161 |
a platform application object for one of the supported push notification services, such as APNs and FCM, to which devices and mobile apps may register. Returns a PlatformApplicationArn attribute, which is used by the CreatePlatformEndpoint action. CreatePlatformEndpoint Creates an endpoint for a device and mobile app on one of the supported push notification services. CreatePlatformEndpoint uses the PlatformApplicationArn attribute returned from the CreatePlatformApplication action. The EndpointArn attribute, which is returned when using CreatePlatformEndpoint, is then used with the Publish action to send a notification message to a mobile app and device. CreateTopic Creates a topic to which messages can be published. DeleteEndpoint Deletes the endpoint for a device and mobile app on one of the supported push notification services. Mobile push API actions 562 Amazon Simple Notification Service Developer Guide DeletePlatformApplication Deletes a platform application object. DeleteTopic Deletes a topic and all its subscriptions. GetEndpointAttributes Retrieves the endpoint attributes for a device and mobile app. GetPlatformApplicationAttributes Retrieves the attributes of the platform application object. ListEndpointsByPlatformApplication Lists the endpoints and endpoint attributes for devices and mobile apps in a supported push notification service. ListPlatformApplications Lists the platform application objects for the supported push notification services. Publish Sends a notification message to all of a topic's subscribed endpoints. SetEndpointAttributes Sets the attributes for an endpoint for a device and mobile app. SetPlatformApplicationAttributes Sets the attributes of the platform application object. Subscribe Prepares to subscribe an endpoint by sending the endpoint a confirmation message. To actually create a subscription, the endpoint owner must call the ConfirmSubscription action with the token from the confirmation message. Unsubscribe Deletes a subscription. Mobile push API actions 563 Amazon Simple Notification Service Developer Guide Common Amazon SNS mobile push API errors Errors that are returned by the Amazon SNS APIs for mobile push are listed in the following table. For more information about the Amazon SNS APIs for mobile push, see Mobile push API actions. Error Description HTTPS status code API Action CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication Application Name is null string The required applicati on name is set to 400 null. Platform Name is null string The required platform name is set to null. Platform Name is invalid An invalid or out- of-range value was 400 400 supplied for the platform name. APNs — Principal is not a valid certificate An invalid certificate was supplied for the 400 APNs principal, which is the SSL certificate. For more informati on, see CreatePla tformApplication in the Amazon Simple Notification Service API Reference. A valid certifica te that is not in the .pem format was supplied for the APNs principal, which is the SSL certificate. APNs — Principal is a valid cert but not in a .pem format 400 CreatePla tformAppl ication Common mobile push API errors 564 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action APNs — Principal is an expired certificate An expired certificate was supplied for the 400 APNs principal, which is the SSL certificate. APNs — Principal is not an Apple issued A non-Apple issued certificate was 400 certificate APNs — Principal is not provided supplied for the APNs principal, which is the SSL certificate. 400 The APNs principal , which is the SSL certificate, was not provided. APNs — Credential is not provided The APNs credentia l, which is the 400 private key, was not provided. For more information, see CreatePlatformAppl ication in the Amazon Simple Notification Service API Reference . CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication APNs — Credentia l are not in a valid .pem format 400 The APNs credentia l, which is the private key, is not in a valid .pem format. CreatePla tformAppl ication Common mobile push API errors 565 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action FCM — serverAPIKey is not provided The FCM credential, which is the API key, 400 was not provided. For more informati on, see CreatePla tformApplication in the Amazon Simple Notification Service API Reference. FCM — serverAPIKey is empty The FCM credential, which is the API key, is empty. 400 FCM — serverAPIKey is a null string The FCM credential, which is the API key, 400 is null. FCM — serverAPIKey is invalid The FCM credential, which is the API key, 400 is invalid. ADM — clientsecret is not provided The required client secret is not ADM — clientsecret is a null string ADM — client_secret is empty string provided. The required string for the client secret is null. The required string for the client secret is empty. 400 400 400 CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication Common mobile push API errors 566 Amazon Simple Notification
|
sns-dg-162
|
sns-dg.pdf
| 162 |
is the API key, 400 is null. FCM — serverAPIKey is invalid The FCM credential, which is the API key, 400 is invalid. ADM — clientsecret is not provided The required client secret is not ADM — clientsecret is a null string ADM — client_secret is empty string provided. The required string for the client secret is null. The required string for the client secret is empty. 400 400 400 CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication Common mobile push API errors 566 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action ADM — client_secret is not valid The required string for the client secret is 400 not valid. ADM — client_id is empty string The required string for the client ID is 400 empty. ADM — clientId is not provided The required string for the client ID is not 400 provided. ADM — clientid is a null string The required string for the client ID is 400 null. ADM — client_id is not valid The required string for the client ID is not 400 valid. EventEndpointCreat ed has invalid ARN EventEndpointCreat ed has invalid ARN 400 format format. EventEndpointDelet ed has invalid ARN EventEndpointDelet ed has invalid ARN 400 format format. EventEndpointUpdat ed has invalid ARN format EventEndpointUpdat ed has invalid ARN format. EventDeliveryAttem ptFailure has invalid ARN format EventDeliveryAttem ptFailure has invalid ARN format. 400 400 CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication Common mobile push API errors 567 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action EventDeliveryFailu re has invalid ARN EventDeliveryFailu re has invalid ARN 400 format format. EventEndpointCreat ed is not an existing EventEndpointCreat ed is not an existing 400 Topic topic. EventEndpointDelet ed is not an existing EventEndpointDelet ed is not an existing 400 Topic topic. EventEndpointUpdat ed is not an existing EventEndpointUpdat ed is not an existing 400 Topic topic. EventDeliveryAttem ptFailure is not an EventDeliveryAttem ptFailure is not an 400 existing Topic existing topic. EventDeliveryFailu re is not an existing EventDeliveryFailu re is not an existing Topic topic. Platform ARN is invalid Platform ARN is invalid. Platform ARN is valid but does not belong to the user Platform ARN is valid but does not belong to the user. 400 400 400 CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication CreatePla tformAppl ication SetPlatfo rmAttributes SetPlatfo rmAttributes Common mobile push API errors 568 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action APNs — Principal is not a valid certificate An invalid certificate was supplied for the 400 SetPlatfo rmAttributes APNs principal, which is the SSL certificate. For more informati on, see CreatePla tformApplication in the Amazon Simple Notification Service API Reference. APNs — Principal is a valid cert but not in A valid certifica te that is not in 400 a .pem format the .pem format was SetPlatfo rmAttributes supplied for the APNs principal, which is the SSL certificate. APNs — Principal is an expired certificate An expired certificate was supplied for the 400 SetPlatfo rmAttributes APNs principal, which is the SSL certificate. APNs — Principal is not an Apple issued A non-Apple issued certificate was 400 SetPlatfo rmAttributes certificate APNs — Principal is not provided supplied for the APNs principal, which is the SSL certificate. 400 The APNs principal , which is the SSL certificate, was not provided. SetPlatfo rmAttributes Common mobile push API errors 569 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action APNs — Credential is not provided The APNs credentia l, which is the 400 SetPlatfo rmAttributes private key, was not provided. For more information, see CreatePlatformAppl ication in the Amazon Simple Notification Service API Reference . APNs — Credentia l are not in a The APNs credentia l, which is the private 400 valid .pem format key, is not in a valid .pem format. SetPlatfo rmAttributes FCM — serverAPIKey is not provided The FCM credential, which is the API key, 400 SetPlatfo rmAttributes was not provided. For more informati on, see CreatePla tformApplication in the Amazon Simple Notification Service API Reference. The FCM credential, which is the API key, is null. FCM — serverAPIKey is a null string ADM — clientId is not provided The required string for the client ID is not provided. 400 400 SetPlatfo rmAttributes SetPlatfo rmAttributes Common mobile push API errors 570 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action ADM — clientid is a null string The required string for the client ID is null. ADM — clientsecret
|
sns-dg-163
|
sns-dg.pdf
| 163 |
API key, 400 SetPlatfo rmAttributes was not provided. For more informati on, see CreatePla tformApplication in the Amazon Simple Notification Service API Reference. The FCM credential, which is the API key, is null. FCM — serverAPIKey is a null string ADM — clientId is not provided The required string for the client ID is not provided. 400 400 SetPlatfo rmAttributes SetPlatfo rmAttributes Common mobile push API errors 570 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action ADM — clientid is a null string The required string for the client ID is null. ADM — clientsecret is not provided The required client secret is not provided. 400 400 ADM — clientsecret is a null string The required string for the client secret is 400 null. EventEndpointUpdat ed has invalid ARN EventEndpointUpdat ed has invalid ARN 400 format format. EventEndpointDelet ed has invalid ARN EventEndpointDelet ed has invalid ARN 400 format format. EventEndpointUpdat ed has invalid ARN EventEndpointUpdat ed has invalid ARN 400 format format. EventDeliveryAttem ptFailure has invalid EventDeliveryAttem ptFailure has invalid 400 ARN format ARN format. EventDeliveryFailu re has invalid ARN format EventDeliveryFailu re has invalid ARN format. EventEndpointCreat ed is not an existing Topic EventEndpointCreat ed is not an existing topic. 400 400 SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes Common mobile push API errors 571 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action EventEndpointDelet ed is not an existing EventEndpointDelet ed is not an existing 400 Topic topic. EventEndpointUpdat ed is not an existing EventEndpointUpdat ed is not an existing 400 Topic topic. EventDeliveryAttem ptFailure is not an EventDeliveryAttem ptFailure is not an 400 existing Topic existing topic. EventDeliveryFailu re is not an existing EventDeliveryFailu re is not an existing 400 Topic topic. Platform ARN is invalid The platform ARN is invalid. 400 Platform ARN is valid but does not belong The platform ARN is valid, but does not 403 to the user belong to the user. Token specified is invalid The specified token is invalid. 400 Platform ARN is invalid The platform ARN is invalid. 400 SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes SetPlatfo rmAttributes GetPlatfo rmApplica tionAttributes GetPlatfo rmApplica tionAttributes ListPlatf ormApplic ations ListEndpo intsByPla tformAppl ication Common mobile push API errors 572 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action Platform ARN is valid but does not belong The platform ARN is valid, but does not 404 to the user belong to the user. Token specified is invalid The specified token is invalid. 400 Platform ARN is invalid The platform ARN is invalid. 400 Platform ARN is valid but does not belong The platform ARN is valid, but does not 403 to the user belong to the user. Platform ARN is invalid The platform ARN is invalid. Platform ARN is valid but does not belong The platform ARN is valid, but does not to the user belong to the user. Token is not specified The token is not specified. Token is not of correct length The token is not the correct length. Customer User data is too large The customer user data cannot be more than 2048 bytes long in UTF-8 encoding. 400 404 400 400 400 ListEndpo intsByPla tformAppl ication ListEndpo intsByPla tformAppl ication DeletePla tformAppl ication DeletePla tformAppl ication CreatePla tformEndpoint CreatePla tformEndpoint CreatePla tformEndpoint CreatePla tformEndpoint CreatePla tformEndpoint Common mobile push API errors 573 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action Endpoint ARN is invalid The endpoint ARN is invalid. Endpoint ARN is valid but does not belong The endpoint ARN is valid, but does not to the user belong to the user. Endpoint ARN is invalid The endpoint ARN is invalid. Endpoint ARN is valid but does not belong to the user The endpoint ARN is valid, but does not belong to the user. Token is not specified The token is not specified. Token is not of correct length The token is not the correct length. Customer User data is too large The customer user data cannot be more than 2048 bytes long in UTF-8 encoding. Endpoint ARN is invalid The endpoint ARN is invalid. Endpoint ARN is valid but does not belong to the user The endpoint ARN is valid, but does not belong to the user. Target ARN is invalid The target ARN is invalid. 400 403 400 403 400 400 400 400 403 400 DeleteEndpoint DeleteEndpoint SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes GetEndpoi ntAttributes GetEndpoi ntAttributes Publish Common mobile push API errors 574 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action Target ARN is valid but does not belong to the user The target ARN is valid, but
|
sns-dg-164
|
sns-dg.pdf
| 164 |
The endpoint ARN is invalid. Endpoint ARN is valid but does not belong to the user The endpoint ARN is valid, but does not belong to the user. Target ARN is invalid The target ARN is invalid. 400 403 400 403 400 400 400 400 403 400 DeleteEndpoint DeleteEndpoint SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes SetEndpoi ntAttributes GetEndpoi ntAttributes GetEndpoi ntAttributes Publish Common mobile push API errors 574 Amazon Simple Notification Service Developer Guide Error Description HTTPS status code API Action Target ARN is valid but does not belong to the user The target ARN is valid, but does not belong to the user. 403 Publish Message format is invalid The message format is invalid. 400 Message size is larger than supported by The message size is larger than supported 400 protocol/end-service by the protocol/end- service. Publish Publish Using the Amazon SNS time to live message attribute for mobile push notifications Amazon Simple Notification Service (Amazon SNS) provides support for setting a Time To Live (TTL) message attribute for mobile push notifications messages. This is in addition to the existing capability of setting TTL within the Amazon SNS message body for the mobile push notification services that support this, such as Amazon Device Messaging (ADM) and Firebase Cloud Messaging (FCM) when sending to Android. The TTL message attribute is used to specify expiration metadata about a message. This allows you to specify the amount of time that the push notification service, such as Apple Push Notification Service (APNs) or FCM, has to deliver the message to the endpoint. If for some reason (such as the mobile device has been turned off) the message is not deliverable within the specified TTL, then the message will be dropped and no further attempts to deliver it will be made. To specify TTL within message attributes, you can use the AWS Management Console, AWS software development kits (SDKs), or query API. TTL message attributes for push notification services The following is a list of the TTL message attributes for push notification services that you can use to set when using the AWS SDKs or query API: Mobile push TTL 575 Amazon Simple Notification Service Developer Guide Push notification service TTL message attribute Amazon Device Messaging (ADM) AWS.SNS.MOBILE.ADM.TTL Apple Push Notification Service (APNs) AWS.SNS.MOBILE.APNS.TTL Apple Push Notification Service Sandbox (APNs_SANDBOX) AWS.SNS.MOBILE.APNS_SANDBOX.TTL Baidu Cloud Push (Baidu) AWS.SNS.MOBILE.BAIDU.TTL Firebase Cloud Messaging (FCM when sending to Android) AWS.SNS.MOBILE.FCM.TTL Windows Push Notification Services (WNS) AWS.SNS.MOBILE.WNS.TTL Each of the push notification services handle TTL differently. Amazon SNS provides an abstract view of TTL over all the push notification services, which makes it easier to specify TTL. When you use the AWS Management Console to specify TTL (in seconds), you only have to enter the TTL value once and Amazon SNS will then calculate the TTL for each of the selected push notification services when publishing the message. TTL is relative to the publish time. Before handing off a push notification message to a specific push notification service, Amazon SNS computes the dwell time (the time between the publish timestamp and just before handing off to a push notification service) for the push notification and passes the remaining TTL to the specific push notification service. If TTL is shorter than the dwell time, Amazon SNS won't attempt to publish. If you specify a TTL for a push notification message, then the TTL value must be a positive integer, unless the value of 0 has a specific meaning for the push notification service—such as with APNs and FCM (when sending to Android). If the TTL value is set to 0 and the push notification service does not have a specific meaning for 0, then Amazon SNS will drop the message. For more information about the TTL parameter set to 0 when using APNs, see Table A-3 Item identifiers for remote notifications in the Binary Provider API documentation. Precedence order for determining TTL The precedence that Amazon SNS uses to determine the TTL for a push notification message is based on the following order, where the lowest number has the highest priority: Mobile push TTL 576 Amazon Simple Notification Service 1. Message attribute TTL 2. Message body TTL 3. Push notification service default TTL (varies per service) 4. Amazon SNS default TTL (4 weeks) Developer Guide If you set different TTL values (one in message attributes and another in the message body) for the same message, then Amazon SNS will modify the TTL in the message body to match the TTL specified in the message attribute. Specifying TTL using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Mobile, Push notifications. 3. On the Mobile push notifications page, in the Platform applications section, choose an application. 4. On the MyApplication page, in
|
sns-dg-165
|
sns-dg.pdf
| 165 |
service default TTL (varies per service) 4. Amazon SNS default TTL (4 weeks) Developer Guide If you set different TTL values (one in message attributes and another in the message body) for the same message, then Amazon SNS will modify the TTL in the message body to match the TTL specified in the message attribute. Specifying TTL using the AWS Management Console 1. Sign in to the Amazon SNS console. 2. On the navigation panel, choose Mobile, Push notifications. 3. On the Mobile push notifications page, in the Platform applications section, choose an application. 4. On the MyApplication page, in the Endpoints section, choose an application endpoint and then choose Publish message. 5. In the Message details section, enter the TTL (the number of seconds that the push notification service has to deliver the message to the endpoint). 6. Choose Publish message. Amazon SNS mobile application supported Regions Currently, you can create mobile applications in the following Regions: • US East (Ohio) • US East (N. Virginia) • US West (N. California) • US West (Oregon) • Africa (Cape Town) • Asia Pacific (Hong Kong) • Asia Pacific (Jakarta) • Asia Pacific (Mumbai) Supported Regions 577 Developer Guide Amazon Simple Notification Service • Asia Pacific (Osaka) • Asia Pacific (Seoul) • Asia Pacific (Singapore) • Asia Pacific (Sydney) • Asia Pacific (Tokyo) • Canada (Central) • Europe (Frankfurt) • Europe (Ireland) • Europe (London) • Europe (Milan) • Europe (Paris) • Europe (Stockholm) • Middle East (Bahrain) • Middle East (UAE) • South America (São Paulo) • AWS GovCloud (US-West) Best practices for managing Amazon SNS mobile push notifications This section describes best practices that might help you improve your customer engagement. Endpoint management Delivery issues might occur in situations were device tokens change due to a user’s action on the device (for example, an app is re-installed on the device), or certificate updates affecting devices running on a particular iOS version. It is a recommended best practice by Apple to register with APNs each time your app launches. Since the device token won’t change each time an app is opened by a user, the idempotent CreatePlatformEndpoint API can be used. However, this can introduce duplicates for the same device in cases where the token itself is invalid, or if the endpoint is valid but disabled (for example, a mismatch of production and sandbox environments). A device token management mechanism such as the one in the pseudo code can be used. Best practices for mobile push notifications 578 Amazon Simple Notification Service Developer Guide For information on managing and maintaining FCM v1 device tokens, see Amazon SNS management of Firebase Cloud Messaging endpoints. Delivery status logging To monitor push notification delivery status, we recommended you enable delivery status logging for your Amazon SNS platform application. This helps you troubleshoot delivery failures because the logs contain provider response codes returned from the push platform service. For details on enabling delivery status logging, see How do I access Amazon SNS topic delivery logs for push notifications?. Event notifications For managing endpoints in an event driven fashion, you can make use of the event notifications functionality. This allows the configured Amazon SNS topic to fanout events to the subscribers such as a Lambda function, for platform application events of endpoint creation, deletion, updates, and delivery failures. Amazon SNS email subscription setup and management You can subscribe an email address to an Amazon SNS topic using the AWS Management Console, AWS SDK for Java, or AWS SDK for .NET. Notes • Customization of the email message body is not supported. The email delivery feature is intended to provide internal system alerts, not marketing messages. • Directly subscribing email endpoints is supported for standard topics only. • Email delivery throughput is throttled. For more information, see Amazon SNS quotas. Important To prevent mailing list recipients from unsubscribing all recipients from Amazon SNS topic emails, see Set up an email subscription that requires authentication to unsubscribe from AWS Support. Email subscription setup and management 579 Amazon Simple Notification Service Developer Guide Subscribing an email address to an Amazon SNS topic using the AWS Management Console 1. 2. Sign in to the Amazon SNS console. In the left navigation pane, choose Subscriptions. 3. On the Subscriptions page, choose Create subscription. 4. On the Create subscription page, in the Details section, do the following: a. b. c. d. e. f. For Topic ARN, choose the Amazon Resource Name (ARN) of a topic. For Protocol, choose Email. For Endpoint, enter the email address. (Optional) To configure a filter policy, expand the Subscription filter policy section. For more information, see Amazon SNS subscription filter policies. (Optional) To enable payload-based filtering, configure Filter Policy Scope to MessageBody. For more information, see Amazon SNS subscription filter policy scope. (Optional) To configure a
|
sns-dg-166
|
sns-dg.pdf
| 166 |
left navigation pane, choose Subscriptions. 3. On the Subscriptions page, choose Create subscription. 4. On the Create subscription page, in the Details section, do the following: a. b. c. d. e. f. For Topic ARN, choose the Amazon Resource Name (ARN) of a topic. For Protocol, choose Email. For Endpoint, enter the email address. (Optional) To configure a filter policy, expand the Subscription filter policy section. For more information, see Amazon SNS subscription filter policies. (Optional) To enable payload-based filtering, configure Filter Policy Scope to MessageBody. For more information, see Amazon SNS subscription filter policy scope. (Optional) To configure a dead-letter queue for the subscription, expand the Redrive policy (dead-letter queue) section. For more information, see Amazon SNS dead-letter queues. g. Choose Create subscription. The console creates the subscription and opens the subscription's Details page. You must confirm the subscription before the email address can start to receive messages. To confirm a subscription 1. Check your email inbox and choose Confirm subscription in the email from Amazon SNS. 2. Amazon SNS opens your web browser and displays a subscription confirmation with your subscription ID. Subscribing an email address to an Amazon SNS topic using an AWS SDK To use an AWS SDK, you must configure it with your credentials. For more information, see The shared config and credentials files in the AWS SDKs and Tools Reference Guide. AWS Management Console 580 Amazon Simple Notification Service Developer Guide The following code examples show how to use Subscribe. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. /// <summary> /// Creates a new subscription to a topic. /// </summary> /// <param name="client">The initialized Amazon SNS client object, used /// to create an Amazon SNS subscription.</param> /// <param name="topicArn">The ARN of the topic to subscribe to.</param> /// <returns>A SubscribeResponse object which includes the subscription /// ARN for the new subscription.</returns> public static async Task<SubscribeResponse> TopicSubscribeAsync( IAmazonSimpleNotificationService client, string topicArn) { SubscribeRequest request = new SubscribeRequest() { TopicArn = topicArn, ReturnSubscriptionArn = true, Protocol = "email", Endpoint = "recipient@example.com", }; var response = await client.SubscribeAsync(request); return response; } AWS SDKs 581 Amazon Simple Notification Service Developer Guide Subscribe a queue to a topic with optional filters. /// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; } var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; } • For API details, see Subscribe in AWS SDK for .NET API Reference. AWS SDKs 582 Amazon Simple Notification Service Developer Guide C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an email address. /*! \param topicARN: An SNS topic Amazon Resource Name (ARN). \param emailAddress: An email address. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN, const Aws::String &emailAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("email"); request.SetEndpoint(emailAddress); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() AWS SDKs 583 Amazon Simple Notification Service Developer Guide << std::endl; } return outcome.IsSuccess(); } Subscribe a mobile application to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param endpointARN: The ARN for a mobile app or device endpoint. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeApp(const Aws::String &topicARN, const Aws::String &endpointARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("application"); request.SetEndpoint(endpointARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } AWS SDKs 584 Amazon Simple Notification Service Developer Guide return outcome.IsSuccess(); } Subscribe a Lambda function to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*!
|
sns-dg-167
|
sns-dg.pdf
| 167 |
\return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeApp(const Aws::String &topicARN, const Aws::String &endpointARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("application"); request.SetEndpoint(endpointARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } AWS SDKs 584 Amazon Simple Notification Service Developer Guide return outcome.IsSuccess(); } Subscribe a Lambda function to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); AWS SDKs 585 Amazon Simple Notification Service Developer Guide } Subscribe an SQS queue to a topic. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } AWS SDKs 586 Amazon Simple Notification Service Developer Guide Subscribe with a filter to a topic. static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/ sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. AWS SDKs 587 Amazon Simple Notification Service Developer Guide if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, AWS SDKs 588 Amazon Simple Notification Service Developer Guide sqsClient); return false; } //! Routine that lets the user select attributes for a subscription filter policy. /*! \sa getFilterPolicyFromUser() \return Aws::String: The filter policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() { std::cout << "You can filter messages by one or more of the following \"" << TONE_ATTRIBUTE << "\" attributes." << std::endl; std::vector<Aws::String> filterSelections; int selection; do { for (size_t j = 0; j < TONES.size(); ++j) { std::cout << " " << (j + 1) << ". " << TONES[j] << std::endl; } selection = askQuestionForIntRange( "Enter a number (or enter zero to stop adding more). ", 0, static_cast<int>(TONES.size())); if (selection != 0) { const Aws::String &selectedTone(TONES[selection - 1]); // Add the tone to the selection if it is not already added. if (std::find(filterSelections.begin(), filterSelections.end(), selectedTone) == filterSelections.end()) { filterSelections.push_back(selectedTone); } } } while (selection != 0); Aws::String result; if (!filterSelections.empty()) { std::ostringstream jsonPolicyStream; jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": ["; AWS SDKs 589 Amazon Simple Notification Service Developer Guide for (size_t j = 0; j < filterSelections.size(); ++j) { jsonPolicyStream << "\"" << filterSelections[j] << "\""; if (j < filterSelections.size() - 1) { jsonPolicyStream << ","; } } jsonPolicyStream << "] }";
|
sns-dg-168
|
sns-dg.pdf
| 168 |
more). ", 0, static_cast<int>(TONES.size())); if (selection != 0) { const Aws::String &selectedTone(TONES[selection - 1]); // Add the tone to the selection if it is not already added. if (std::find(filterSelections.begin(), filterSelections.end(), selectedTone) == filterSelections.end()) { filterSelections.push_back(selectedTone); } } } while (selection != 0); Aws::String result; if (!filterSelections.empty()) { std::ostringstream jsonPolicyStream; jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": ["; AWS SDKs 589 Amazon Simple Notification Service Developer Guide for (size_t j = 0; j < filterSelections.size(); ++j) { jsonPolicyStream << "\"" << filterSelections[j] << "\""; if (j < filterSelections.size() - 1) { jsonPolicyStream << ","; } } jsonPolicyStream << "] }"; result = jsonPolicyStream.str(); } return result; } • For API details, see Subscribe in AWS SDK for C++ API Reference. CLI AWS CLI To subscribe to a topic The following subscribe command subscribes an email address to the specified topic. aws sns subscribe \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ --protocol email \ --notification-endpoint my-email@example.com Output: { "SubscriptionArn": "pending confirmation" } • For API details, see Subscribe in AWS CLI Command Reference. AWS SDKs 590 Amazon Simple Notification Service Developer Guide Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe a queue to a topic with optional filters. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { AWS SDKs 591 Amazon Simple Notification Service Developer Guide filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err } • For API details, see Subscribe in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; AWS SDKs 592 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeEmail { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String email = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subEmail(snsClient, topicArn, email); snsClient.close(); } public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) AWS SDKs 593 Amazon Simple Notification Service Developer Guide .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe an HTTP endpoint to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <url> Where: topicArn - The ARN of the topic to subscribe. AWS SDKs 594 Amazon Simple Notification Service Developer Guide url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe a Lambda function to a topic. AWS
|
sns-dg-169
|
sns-dg.pdf
| 169 |
Simple Notification Service Developer Guide url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe a Lambda function to a topic. AWS SDKs 595 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } AWS SDKs 596 Amazon Simple Notification Service Developer Guide public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see Subscribe in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. AWS SDKs 597 Amazon Simple Notification Service Developer Guide export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } }; Subscribe a mobile application to a topic. AWS SDKs 598 Amazon Simple Notification Service Developer Guide import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe a Lambda function to a topic. import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** AWS SDKs 599 Amazon Simple Notification Service Developer Guide * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe an SQS queue to a topic. import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, AWS SDKs 600 Amazon Simple Notification Service Developer Guide Protocol:
|
sns-dg-170
|
sns-dg.pdf
| 170 |
response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe an SQS queue to a topic. import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, AWS SDKs 600 Amazon Simple Notification Service Developer Guide Protocol: "sqs", Endpoint: queueArn, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue- test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; Subscribe with a filter to a topic. import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueueFiltered = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the 'event' attribute set to 'order_placed'. FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ event: ["order_placed"], }), AWS SDKs 601 Amazon Simple Notification Service Developer Guide }, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue- test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Subscribe in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. suspend fun subEmail( topicArnVal: String, email: String, ): String { val request = AWS SDKs 602 Amazon Simple Notification Service Developer Guide SubscribeRequest { protocol = "email" endpoint = email returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) return result.subscriptionArn.toString() } } Subscribe a Lambda function to a topic. suspend fun subLambda( topicArnVal: String?, lambdaArn: String?, ) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } } • For API details, see Subscribe in AWS SDK for Kotlin API reference. AWS SDKs 603 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'email'; $endpoint = 'sample@example.com'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, AWS SDKs 604 Amazon Simple Notification Service Developer Guide ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Subscribe an HTTP endpoint to a topic. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'https'; $endpoint = 'https://'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); AWS SDKs 605 Amazon Simple Notification Service Developer Guide var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see Subscribe in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def subscribe(topic, protocol, endpoint): """ Subscribes an endpoint to the topic. Some endpoint types, such as email, must be confirmed before their subscriptions are active. When a subscription is not confirmed, its
|
sns-dg-171
|
sns-dg.pdf
| 171 |
Subscribe in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def subscribe(topic, protocol, endpoint): """ Subscribes an endpoint to the topic. Some endpoint types, such as email, must be confirmed before their subscriptions are active. When a subscription is not confirmed, its Amazon Resource Number (ARN) is set to 'PendingConfirmation'. :param topic: The topic to subscribe to. AWS SDKs 606 Amazon Simple Notification Service Developer Guide :param protocol: The protocol of the endpoint, such as 'sms' or 'email'. :param endpoint: The endpoint that receives messages, such as a phone number (in E.164 format) for SMS messages, or an email address for email messages. :return: The newly added subscription. """ try: subscription = topic.subscribe( Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True ) logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn) except ClientError: logger.exception( "Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn ) raise else: return subscription • For API details, see Subscribe in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. require 'aws-sdk-sns' require 'logger' AWS SDKs 607 Amazon Simple Notification Service Developer Guide # Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS) class SubscriptionService # Initializes the SubscriptionService with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Attempts to create a subscription to a topic # # @param topic_arn [String] The ARN of the SNS topic # @param protocol [String] The subscription protocol (e.g., email) # @param endpoint [String] The endpoint that receives the notifications (email address) # @return [Boolean] true if subscription was successfully created, false otherwise def create_subscription(topic_arn, protocol, endpoint) @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) @logger.info('Subscription created successfully.') true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while creating the subscription: #{e.message}") false end end # Main execution if the script is run directly if $PROGRAM_NAME == __FILE__ protocol = 'email' endpoint = 'EMAIL_ADDRESS' # Should be replaced with a real email address topic_arn = 'TOPIC_ARN' # Should be replaced with a real topic ARN sns_client = Aws::SNS::Client.new subscription_service = SubscriptionService.new(sns_client) @logger.info('Creating the subscription.') unless subscription_service.create_subscription(topic_arn, protocol, endpoint) @logger.error('Subscription creation failed. Stopping program.') exit 1 end AWS SDKs 608 Amazon Simple Notification Service Developer Guide end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see Subscribe in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; AWS SDKs 609 Amazon Simple Notification Service Developer Guide println!("Published message: {:?}", rsp); Ok(()) } • For API details, see Subscribe in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. TRY. oo_result = lo_sns->subscribe( "oo_result is returned for testing purposes." iv_topicarn = iv_topic_arn iv_protocol = 'email' iv_endpoint = iv_email_address iv_returnsubscriptionarn = abap_true ). MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. • For API details, see Subscribe in AWS SDK for SAP ABAP API reference. AWS SDKs 610 Amazon Simple Notification Service Developer Guide Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.subscribe( input: SubscribeInput( endpoint: email, protocol: "email", returnSubscriptionArn: true, topicArn: arn ) ) guard let subscriptionArn = output.subscriptionArn else { print("No subscription ARN received from Amazon SNS.") return } print("Subscription \(subscriptionArn) created.") Subscribe a phone number to a topic to receive notifications by
|
sns-dg-172
|
sns-dg.pdf
| 172 |
Notification Service Developer Guide Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.subscribe( input: SubscribeInput( endpoint: email, protocol: "email", returnSubscriptionArn: true, topicArn: arn ) ) guard let subscriptionArn = output.subscriptionArn else { print("No subscription ARN received from Amazon SNS.") return } print("Subscription \(subscriptionArn) created.") Subscribe a phone number to a topic to receive notifications by SMS. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.subscribe( AWS SDKs 611 Amazon Simple Notification Service Developer Guide input: SubscribeInput( endpoint: phone, protocol: "sms", returnSubscriptionArn: true, topicArn: arn ) ) guard let subscriptionArn = output.subscriptionArn else { print("No subscription ARN received from Amazon SNS.") return } print("Subscription \(subscriptionArn) created.") • For API details, see Subscribe in AWS SDK for Swift API reference. AWS SDKs 612 Amazon Simple Notification Service Developer Guide Code examples for Amazon SNS using AWS SDKs The following code examples show how to use Amazon SNS with an AWS software development kit (SDK). Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios. Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Get started Hello Amazon SNS The following code examples show how to get started using Amazon SNS. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; namespace SNSActions; public static class HelloSNS { static async Task Main(string[] args) 613 Amazon Simple Notification Service { Developer Guide var snsClient = new AmazonSimpleNotificationServiceClient(); Console.WriteLine($"Hello Amazon SNS! Following are some of your topics:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get a list of topics. var response = await snsClient.ListTopicsAsync( new ListTopicsRequest()); foreach (var topic in response.Topics) { Console.WriteLine($"\tTopic ARN: {topic.TopicArn}"); Console.WriteLine(); } } } • For API details, see ListTopics in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Code for the CMakeLists.txt CMake file. # Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS sns) # Set this project's name. 614 Amazon Simple Notification Service Developer Guide project("hello_sns") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_sns.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES}) Code for the hello_sns.cpp source file. #include <aws/core/Aws.h> #include <aws/sns/SNSClient.h> #include <aws/sns/model/ListTopicsRequest.h> 615 Amazon Simple Notification Service #include <iostream> /* Developer Guide * A "Hello SNS" starter application which initializes an Amazon Simple Notification * Service (Amazon SNS) client and lists the SNS topics in the current account. * * main function * * Usage: 'hello_sns' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfig); Aws::Vector<Aws::SNS::Model::Topic> allTopics; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SNS::Model::Topic> &paginatedTopics = outcome.GetResult().GetTopics(); if (!paginatedTopics.empty()) { allTopics.insert(allTopics.cend(), paginatedTopics.cbegin(), 616 Amazon Simple Notification Service Developer Guide
|
sns-dg-173
|
sns-dg.pdf
| 173 |
* Usage: 'hello_sns' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfig); Aws::Vector<Aws::SNS::Model::Topic> allTopics; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SNS::Model::Topic> &paginatedTopics = outcome.GetResult().GetTopics(); if (!paginatedTopics.empty()) { allTopics.insert(allTopics.cend(), paginatedTopics.cbegin(), 616 Amazon Simple Notification Service Developer Guide paginatedTopics.cend()); } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; return 1; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SNS! You have " << allTopics.size() << " topic" << (allTopics.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allTopics.empty()) { std::cout << "Here are your topic ARNs." << std::endl; for (const Aws::SNS::Model::Topic &topic: allTopics) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return 0; } • For API details, see ListTopics in AWS SDK for C++ API Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. 617 Amazon Simple Notification Service Developer Guide package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } snsClient := sns.NewFromConfig(sdkConfig) fmt.Println("Let's list the topics for your account.") var topics []types.Topic paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get topics. Here's why: %v\n", err) break } else { topics = append(topics, output.Topics...) } } if len(topics) == 0 { fmt.Println("You don't have any topics!") } else { 618 Amazon Simple Notification Service Developer Guide for _, topic := range topics { fmt.Printf("\t%v\n", *topic.TopicArn) } } } • For API details, see ListTopics in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.example.sns; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.paginators.ListTopicsIterable; public class HelloSNS { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsIterable listTopics = snsClient.listTopicsPaginator(); listTopics.stream() .flatMap(r -> r.topics().stream()) 619 Amazon Simple Notification Service Developer Guide .forEach(content -> System.out.println(" Topic ARN: " + content.topicArn())); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListTopics in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Initialize an SNS client and and list topics in your account. import { SNSClient, paginateListTopics } from "@aws-sdk/client-sns"; export const helloSns = async () => { // The configuration object (`{}`) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client = new SNSClient({}); // You can also use `ListTopicsCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListTopicsCommand` // with the `NextToken` parameter from the previous request. const paginatedTopics = paginateListTopics({ client }, {}); const topics = []; for await (const page of paginatedTopics) { if (page.Topics?.length) { topics.push(...page.Topics); 620 Amazon Simple Notification Service Developer Guide } } const suffix = topics.length === 1 ? "" : "s"; console.log( `Hello, Amazon SNS! You have ${topics.length} topic${suffix} in your account.`, ); console.log(topics.map((t) => ` * ${t.TopicArn}`).join("\n")); }; • For API details, see ListTopics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.ListTopicsRequest import aws.sdk.kotlin.services.sns.paginators.listTopicsPaginated import kotlinx.coroutines.flow.transform /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { 621 Amazon Simple Notification Service Developer Guide SnsClient { region = "us-east-1" }.use {
|
sns-dg-174
|
sns-dg.pdf
| 174 |
* ${t.TopicArn}`).join("\n")); }; • For API details, see ListTopics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.ListTopicsRequest import aws.sdk.kotlin.services.sns.paginators.listTopicsPaginated import kotlinx.coroutines.flow.transform /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { 621 Amazon Simple Notification Service Developer Guide SnsClient { region = "us-east-1" }.use { snsClient -> snsClient .listTopicsPaginated(ListTopicsRequest { }) .transform { it.topics?.forEach { topic -> emit(topic) } } .collect { topic -> println("The topic ARN is ${topic.topicArn}") } } } • For API details, see ListTopics in AWS SDK for Kotlin API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. The Package.swift file. import PackageDescription let package = Package( name: "sns-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" 622 Amazon Simple Notification Service Developer Guide ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sns-basics", dependencies: [ .product(name: "AWSSNS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument- parser") ], path: "Sources") ] ) The main Swift program. import ArgumentParser import AWSClientRuntime import AWSSNS import Foundation struct ExampleCommand: ParsableCommand { @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "sns-basics", abstract: """ This example shows how to list all of your available Amazon SNS topics. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SNSClient.SNSClientConfiguration(region: region) 623 Amazon Simple Notification Service Developer Guide let snsClient = SNSClient(config: config) var topics: [String] = [] let outputPages = snsClient.listTopicsPaginated( input: ListTopicsInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let topicList = output.topics else { print("Unable to get a page of Amazon SNS topics.") return } // Iterate over the topics listed on this page, adding their ARNs // to the `topics` array. for topic in topicList { guard let arn = topic.topicArn else { print("Topic has no ARN.") return } topics.append(arn) } } print("You have \(topics.count) topics:") for topic in topics { print(" \(topic)") } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { 624 Amazon Simple Notification Service Developer Guide ExampleCommand.exit(withError: error) } } } • For API details, see ListTopics in AWS SDK for Swift API reference. Code examples • Basic examples for Amazon SNS using AWS SDKs • Hello Amazon SNS • Actions for Amazon SNS using AWS SDKs • Use CheckIfPhoneNumberIsOptedOut with an AWS SDK or CLI • Use ConfirmSubscription with an AWS SDK or CLI • Use CreateTopic with an AWS SDK or CLI • Use DeleteTopic with an AWS SDK or CLI • Use GetSMSAttributes with an AWS SDK or CLI • Use GetTopicAttributes with an AWS SDK or CLI • Use ListPhoneNumbersOptedOut with an AWS SDK or CLI • Use ListSubscriptions with an AWS SDK or CLI • Use ListTopics with an AWS SDK or CLI • Use Publish with an AWS SDK or CLI • Use SetSMSAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributesRedrivePolicy with an AWS SDK • Use SetTopicAttributes with an AWS SDK or CLI • Use Subscribe with an AWS SDK or CLI • Use TagResource with an AWS SDK or CLI • Use Unsubscribe with an AWS SDK or CLI • Scenarios for Amazon SNS using AWS SDKs • Build an application to submit data to a DynamoDB table • Build a publish and subscription application that translates messages 625 Amazon Simple Notification Service Developer Guide • Create a platform endpoint for Amazon SNS push notifications using an AWS SDK • Create a photo asset management application that lets users manage photos using labels • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK • Detect people and objects in a video with Amazon Rekognition using an AWS SDK •
|
sns-dg-175
|
sns-dg.pdf
| 175 |
Scenarios for Amazon SNS using AWS SDKs • Build an application to submit data to a DynamoDB table • Build a publish and subscription application that translates messages 625 Amazon Simple Notification Service Developer Guide • Create a platform endpoint for Amazon SNS push notifications using an AWS SDK • Create a photo asset management application that lets users manage photos using labels • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Publish SMS messages to an Amazon SNS topic using an AWS SDK • Publish a large message to Amazon SNS with Amazon S3 using an AWS SDK • Publish an Amazon SNS SMS text message using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK • Use API Gateway to invoke a Lambda function • Use scheduled events to invoke a Lambda function • Serverless examples for Amazon SNS • Invoke a Lambda function from an Amazon SNS trigger Basic examples for Amazon SNS using AWS SDKs The following code examples show how to use the basics of Amazon Simple Notification Service with AWS SDKs. Examples • Hello Amazon SNS • Actions for Amazon SNS using AWS SDKs • Use CheckIfPhoneNumberIsOptedOut with an AWS SDK or CLI • Use ConfirmSubscription with an AWS SDK or CLI • Use CreateTopic with an AWS SDK or CLI • Use DeleteTopic with an AWS SDK or CLI • Use GetSMSAttributes with an AWS SDK or CLI • Use GetTopicAttributes with an AWS SDK or CLI • Use ListPhoneNumbersOptedOut with an AWS SDK or CLI • Use ListSubscriptions with an AWS SDK or CLI Basics • Use ListTopics with an AWS SDK or CLI 626 Amazon Simple Notification Service Developer Guide • Use Publish with an AWS SDK or CLI • Use SetSMSAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributesRedrivePolicy with an AWS SDK • Use SetTopicAttributes with an AWS SDK or CLI • Use Subscribe with an AWS SDK or CLI • Use TagResource with an AWS SDK or CLI • Use Unsubscribe with an AWS SDK or CLI Hello Amazon SNS The following code examples show how to get started using Amazon SNS. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; namespace SNSActions; public static class HelloSNS { static async Task Main(string[] args) { var snsClient = new AmazonSimpleNotificationServiceClient(); Console.WriteLine($"Hello Amazon SNS! Following are some of your topics:"); Console.WriteLine(); Hello Amazon SNS 627 Amazon Simple Notification Service Developer Guide // You can use await and any of the async methods to get a response. // Let's get a list of topics. var response = await snsClient.ListTopicsAsync( new ListTopicsRequest()); foreach (var topic in response.Topics) { Console.WriteLine($"\tTopic ARN: {topic.TopicArn}"); Console.WriteLine(); } } } • For API details, see ListTopics in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Code for the CMakeLists.txt CMake file. # Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS sns) # Set this project's name. project("hello_sns") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) Hello Amazon SNS 628 Amazon Simple Notification Service Developer Guide # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_sns.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES}) Code for the hello_sns.cpp source file. #include <aws/core/Aws.h> #include <aws/sns/SNSClient.h> #include <aws/sns/model/ListTopicsRequest.h> #include <iostream> /* * A "Hello SNS" starter application which initializes an Amazon Simple Notification * Service (Amazon SNS) client and lists the SNS topics in the current account. Hello Amazon SNS 629 Amazon Simple Notification Service Developer Guide * * main function * * Usage: 'hello_sns' * */ int main(int argc, char
|
sns-dg-176
|
sns-dg.pdf
| 176 |
"/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_sns.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES}) Code for the hello_sns.cpp source file. #include <aws/core/Aws.h> #include <aws/sns/SNSClient.h> #include <aws/sns/model/ListTopicsRequest.h> #include <iostream> /* * A "Hello SNS" starter application which initializes an Amazon Simple Notification * Service (Amazon SNS) client and lists the SNS topics in the current account. Hello Amazon SNS 629 Amazon Simple Notification Service Developer Guide * * main function * * Usage: 'hello_sns' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfig); Aws::Vector<Aws::SNS::Model::Topic> allTopics; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SNS::Model::Topic> &paginatedTopics = outcome.GetResult().GetTopics(); if (!paginatedTopics.empty()) { allTopics.insert(allTopics.cend(), paginatedTopics.cbegin(), paginatedTopics.cend()); } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() Hello Amazon SNS 630 Amazon Simple Notification Service Developer Guide << std::endl; return 1; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SNS! You have " << allTopics.size() << " topic" << (allTopics.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allTopics.empty()) { std::cout << "Here are your topic ARNs." << std::endl; for (const Aws::SNS::Model::Topic &topic: allTopics) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return 0; } • For API details, see ListTopics in AWS SDK for C++ API Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package main import ( Hello Amazon SNS 631 Amazon Simple Notification Service Developer Guide "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } snsClient := sns.NewFromConfig(sdkConfig) fmt.Println("Let's list the topics for your account.") var topics []types.Topic paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get topics. Here's why: %v\n", err) break } else { topics = append(topics, output.Topics...) } } if len(topics) == 0 { fmt.Println("You don't have any topics!") } else { for _, topic := range topics { fmt.Printf("\t%v\n", *topic.TopicArn) } } } Hello Amazon SNS 632 Amazon Simple Notification Service Developer Guide • For API details, see ListTopics in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.example.sns; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.paginators.ListTopicsIterable; public class HelloSNS { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsIterable listTopics = snsClient.listTopicsPaginator(); listTopics.stream() .flatMap(r -> r.topics().stream()) .forEach(content -> System.out.println(" Topic ARN: " + content.topicArn())); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); Hello Amazon SNS 633 Amazon Simple Notification Service Developer Guide System.exit(1); } } } • For API details, see ListTopics in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Initialize an SNS client and and list topics in your account. import { SNSClient, paginateListTopics } from "@aws-sdk/client-sns"; export const helloSns = async () => { // The configuration object (`{}`) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client = new SNSClient({}); // You can also use `ListTopicsCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListTopicsCommand` // with the `NextToken` parameter from the previous request. const paginatedTopics = paginateListTopics({ client }, {}); const topics = []; for await (const page of paginatedTopics) { if (page.Topics?.length) { topics.push(...page.Topics); } } const suffix = topics.length === 1 ? "" : "s"; Hello Amazon SNS 634 Amazon Simple Notification Service console.log( Developer Guide `Hello, Amazon SNS! You have ${topics.length} topic${suffix} in
|
sns-dg-177
|
sns-dg.pdf
| 177 |
uses your local configuration if it exists. const client = new SNSClient({}); // You can also use `ListTopicsCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListTopicsCommand` // with the `NextToken` parameter from the previous request. const paginatedTopics = paginateListTopics({ client }, {}); const topics = []; for await (const page of paginatedTopics) { if (page.Topics?.length) { topics.push(...page.Topics); } } const suffix = topics.length === 1 ? "" : "s"; Hello Amazon SNS 634 Amazon Simple Notification Service console.log( Developer Guide `Hello, Amazon SNS! You have ${topics.length} topic${suffix} in your account.`, ); console.log(topics.map((t) => ` * ${t.TopicArn}`).join("\n")); }; • For API details, see ListTopics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.ListTopicsRequest import aws.sdk.kotlin.services.sns.paginators.listTopicsPaginated import kotlinx.coroutines.flow.transform /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { SnsClient { region = "us-east-1" }.use { snsClient -> snsClient .listTopicsPaginated(ListTopicsRequest { }) .transform { it.topics?.forEach { topic -> emit(topic) } } .collect { topic -> Hello Amazon SNS 635 Amazon Simple Notification Service Developer Guide println("The topic ARN is ${topic.topicArn}") } } } • For API details, see ListTopics in AWS SDK for Kotlin API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. The Package.swift file. import PackageDescription let package = Package( name: "sns-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. Hello Amazon SNS 636 Amazon Simple Notification Service Developer Guide // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sns-basics", dependencies: [ .product(name: "AWSSNS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument- parser") ], path: "Sources") ] ) The main Swift program. import ArgumentParser import AWSClientRuntime import AWSSNS import Foundation struct ExampleCommand: ParsableCommand { @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "sns-basics", abstract: """ This example shows how to list all of your available Amazon SNS topics. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) var topics: [String] = [] let outputPages = snsClient.listTopicsPaginated( input: ListTopicsInput() Hello Amazon SNS 637 Amazon Simple Notification Service ) Developer Guide // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let topicList = output.topics else { print("Unable to get a page of Amazon SNS topics.") return } // Iterate over the topics listed on this page, adding their ARNs // to the `topics` array. for topic in topicList { guard let arn = topic.topicArn else { print("Topic has no ARN.") return } topics.append(arn) } } print("You have \(topics.count) topics:") for topic in topics { print(" \(topic)") } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } } Hello Amazon SNS 638 Amazon Simple Notification Service Developer Guide • For API details, see ListTopics in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions for Amazon SNS using AWS SDKs The following code examples demonstrate how to perform individual Amazon SNS actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. These excerpts call the Amazon SNS API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for Amazon SNS using AWS SDKs . The following examples include only the most commonly used actions. For a complete list, see the Amazon Simple Notification Service API Reference. Examples • Use CheckIfPhoneNumberIsOptedOut with an AWS SDK or CLI • Use ConfirmSubscription with an AWS SDK or CLI • Use CreateTopic with an AWS
|
sns-dg-178
|
sns-dg.pdf
| 178 |
example includes a link to GitHub, where you can find instructions for setting up and running the code. These excerpts call the Amazon SNS API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for Amazon SNS using AWS SDKs . The following examples include only the most commonly used actions. For a complete list, see the Amazon Simple Notification Service API Reference. Examples • Use CheckIfPhoneNumberIsOptedOut with an AWS SDK or CLI • Use ConfirmSubscription with an AWS SDK or CLI • Use CreateTopic with an AWS SDK or CLI • Use DeleteTopic with an AWS SDK or CLI • Use GetSMSAttributes with an AWS SDK or CLI • Use GetTopicAttributes with an AWS SDK or CLI • Use ListPhoneNumbersOptedOut with an AWS SDK or CLI • Use ListSubscriptions with an AWS SDK or CLI • Use ListTopics with an AWS SDK or CLI • Use Publish with an AWS SDK or CLI • Use SetSMSAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributes with an AWS SDK or CLI • Use SetSubscriptionAttributesRedrivePolicy with an AWS SDK • Use SetTopicAttributes with an AWS SDK or CLI Actions 639 Amazon Simple Notification Service Developer Guide • Use Subscribe with an AWS SDK or CLI • Use TagResource with an AWS SDK or CLI • Use Unsubscribe with an AWS SDK or CLI Use CheckIfPhoneNumberIsOptedOut with an AWS SDK or CLI The following code examples show how to use CheckIfPhoneNumberIsOptedOut. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example shows how to use the Amazon Simple Notification Service /// (Amazon SNS) to check whether a phone number has been opted out. /// </summary> public class IsPhoneNumOptedOut { public static async Task Main() { string phoneNumber = "+15551112222"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await CheckIfOptedOutAsync(client, phoneNumber); } /// <summary> /// Checks to see if the supplied phone number has been opted out. Actions 640 Amazon Simple Notification Service Developer Guide /// </summary> /// <param name="client">The initialized Amazon SNS Client object used /// to check if the phone number has been opted out.</param> /// <param name="phoneNumber">A string representing the phone number /// to check.</param> public static async Task CheckIfOptedOutAsync(IAmazonSimpleNotificationService client, string phoneNumber) { var request = new CheckIfPhoneNumberIsOptedOutRequest { PhoneNumber = phoneNumber, }; try { var response = await client.CheckIfPhoneNumberIsOptedOutAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { string optOutStatus = response.IsOptedOut ? "opted out" : "not opted out."; Console.WriteLine($"The phone number: {phoneNumber} is {optOutStatus}"); } } catch (AuthorizationErrorException ex) { Console.WriteLine($"{ex.Message}"); } } } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for .NET API Reference. CLI AWS CLI To check SMS message opt-out for a phone number Actions 641 Amazon Simple Notification Service Developer Guide The following check-if-phone-number-is-opted-out example checks whether the specified phone number is opted out of receiving SMS messages from the current AWS account. aws sns check-if-phone-number-is-opted-out \ --phone-number +1555550100 Output: { "isOptedOut": false } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutRequest; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * Actions 642 Amazon Simple Notification Service Developer Guide * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CheckOptOut { public static void main(String[] args) { final String usage = """ Usage: <phoneNumber> Where: phoneNumber - The mobile phone number to look up (for example, +1XXX5550100). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String phoneNumber = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); checkPhone(snsClient, phoneNumber); snsClient.close(); } public static void checkPhone(SnsClient snsClient, String phoneNumber) { try { CheckIfPhoneNumberIsOptedOutRequest request = CheckIfPhoneNumberIsOptedOutRequest.builder() .phoneNumber(phoneNumber) .build(); CheckIfPhoneNumberIsOptedOutResponse result = snsClient.checkIfPhoneNumberIsOptedOut(request); System.out.println( result.isOptedOut() + "Phone Number " + phoneNumber + " has Opted Out of receiving sns messages." + "\n\nStatus was " + result.sdkHttpResponse().statusCode()); Actions 643 Amazon Simple Notification Service Developer Guide } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the
|
sns-dg-179
|
sns-dg.pdf
| 179 |
"\n\nStatus was " + result.sdkHttpResponse().statusCode()); Actions 643 Amazon Simple Notification Service Developer Guide } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", Actions 644 Amazon Simple Notification Service ) => { Developer Guide const command = new CheckIfPhoneNumberIsOptedOutCommand({ phoneNumber, }); const response = await snsClient.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // isOptedOut: false // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for JavaScript API Reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; Actions 645 Amazon Simple Notification Service Developer Guide /** * Indicates whether the phone number owner has opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $phone = '+1XXX5550100'; try { $result = $SnSclient->checkIfPhoneNumberIsOptedOut([ 'phoneNumber' => $phone, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see CheckIfPhoneNumberIsOptedOut in AWS SDK for PHP API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ConfirmSubscription with an AWS SDK or CLI The following code examples show how to use ConfirmSubscription. Actions 646 Amazon Simple Notification Service Developer Guide CLI AWS CLI To confirm a subscription The following confirm-subscription command completes the confirmation process started when you subscribed to an SNS topic named my-topic. The --token parameter comes from the confirmation message sent to the notification endpoint specified in the subscribe call. aws sns confirm-subscription \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ -- token 2336412f37fb687f5d51e6e241d7700ae02f7124d8268910b858cb4db727ceeb2474bb937929d3bdd7ce5d0cce19325d036bc858d3c217426bcafa9c501a2cace93b83f1dd3797627467553dc438a8c974119496fc3eff026eaa5d14472ded6f9a5c43aec62d83ef5f49109da7176391 Output: { "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my- topic:8a21d249-4329-4871-acc6-7be709c6ea7f" } • For API details, see ConfirmSubscription in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionRequest; import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionResponse; import software.amazon.awssdk.services.sns.model.SnsException; Actions 647 Amazon Simple Notification Service Developer Guide /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class ConfirmSubscription { public static void main(String[] args) { final String usage = """ Usage: <subscriptionToken> <topicArn> Where: subscriptionToken - A short-lived token sent to an endpoint during the Subscribe action. topicArn - The ARN of the topic.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String subscriptionToken = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); confirmSub(snsClient, subscriptionToken, topicArn); snsClient.close(); } public static void confirmSub(SnsClient snsClient, String subscriptionToken, String topicArn) { try { ConfirmSubscriptionRequest request = ConfirmSubscriptionRequest.builder() .token(subscriptionToken) .topicArn(topicArn) Actions 648 Amazon Simple Notification Service Developer Guide .build(); ConfirmSubscriptionResponse result = snsClient.confirmSubscription(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription Arn: \n\n" + result.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ConfirmSubscription in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call
|
sns-dg-180
|
sns-dg.pdf
| 180 |
API details, see ConfirmSubscription in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { ConfirmSubscriptionCommand } from "@aws-sdk/client-sns"; Actions 649 Amazon Simple Notification Service Developer Guide import { snsClient } from "../libs/snsClient.js"; /** * @param {string} token - This token is sent the subscriber. Only subscribers * that are not AWS services (HTTP/S, email) need to be confirmed. * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. */ export const confirmSubscription = async ( token = "TOKEN", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( // A subscription only needs to be confirmed if the endpoint type is // HTTP/S, email, or in another AWS account. new ConfirmSubscriptionCommand({ Token: token, TopicArn: topicArn, // If this is true, the subscriber cannot unsubscribe while unauthenticated. AuthenticateOnUnsubscribe: "false", }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx- xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ConfirmSubscription in AWS SDK for JavaScript API Reference. Actions 650 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Verifies an endpoint owner's intent to receive messages by * validating the token sent to the endpoint by an earlier Subscribe action. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $subscription_token = 'arn:aws:sns:us-east-1:111122223333:MyTopic:123456- abcd-12ab-1234-12ba3dc1234a'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->confirmSubscription([ 'Token' => $subscription_token, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { Actions 651 Amazon Simple Notification Service Developer Guide // output error message if fails error_log($e->getMessage()); } • For API details, see ConfirmSubscription in AWS SDK for PHP API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use CreateTopic with an AWS SDK or CLI The following code examples show how to use CreateTopic. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Create and publish to a FIFO topic • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a topic with a specific name. using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> Actions 652 Amazon Simple Notification Service Developer Guide /// This example shows how to use Amazon Simple Notification Service /// (Amazon SNS) to add a new Amazon SNS topic. /// </summary> public class CreateSNSTopic { public static async Task Main() { string topicName = "ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var topicArn = await CreateSNSTopicAsync(client, topicName); Console.WriteLine($"New topic ARN: {topicArn}"); } /// <summary> /// Creates a new SNS topic using the supplied topic name. /// </summary> /// <param name="client">The initialized SNS client object used to /// create the new topic.</param> /// <param name="topicName">A string representing the topic name.</param> /// <returns>The Amazon Resource Name (ARN) of the created topic.</ returns> public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName) { var request = new CreateTopicRequest { Name = topicName, }; var response = await client.CreateTopicAsync(request); return response.TopicArn; } } Create a new topic with a name and specific FIFO and de-duplication attributes. /// <summary> Actions 653 Amazon Simple Notification Service Developer Guide /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de- duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic)
|
sns-dg-181
|
sns-dg.pdf
| 181 |
var response = await client.CreateTopicAsync(request); return response.TopicArn; } } Create a new topic with a name and specific FIFO and de-duplication attributes. /// <summary> Actions 653 Amazon Simple Notification Service Developer Guide /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de- duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters. createTopicRequest.Attributes = new Dictionary<string, string> { { "FifoTopic", "true" } }; if (useContentBasedDeduplication) { createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true"); } } var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest); return createResponse.TopicArn; } • For API details, see CreateTopic in AWS SDK for .NET API Reference. Actions 654 Amazon Simple Notification Service Developer Guide C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Create an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicName: An Amazon SNS topic name. \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::createTopic(const Aws::String &topicName, Aws::String &topicARNResult, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::CreateTopicRequest request; request.SetName(topicName); const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARNResult = outcome.GetResult().GetTopicArn(); std::cout << "Successfully created an Amazon SNS topic " << topicName << " with topic ARN '" << topicARNResult << "'." << std::endl; } else { std::cerr << "Error creating topic " << topicName << ":" << outcome.GetError().GetMessage() << std::endl; topicARNResult.clear(); } Actions 655 Amazon Simple Notification Service Developer Guide return outcome.IsSuccess(); } • For API details, see CreateTopic in AWS SDK for C++ API Reference. CLI AWS CLI To create an SNS topic The following create-topic example creates an SNS topic named my-topic. aws sns create-topic \ --name my-topic Output: { "ResponseMetadata": { "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83" }, "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } For more information, see Using the AWS Command Line Interface with Amazon SQS and Amazon SNS in the AWS Command Line Interface User Guide. • For API details, see CreateTopic in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 656 Amazon Simple Notification Service Developer Guide import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic is created as a FIFO topic and whether it uses content- based // deduplication instead of ID-based deduplication. func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) { var topicArn string topicAttributes := map[string]string{} if isFifoTopic { topicAttributes["FifoTopic"] = "true" } if contentBasedDeduplication { topicAttributes["ContentBasedDeduplication"] = "true" } topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{ Name: aws.String(topicName), Attributes: topicAttributes, }) if err != nil { log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err) } else { topicArn = *topic.TopicArn Actions 657 Amazon Simple Notification Service Developer Guide } return topicArn, err } • For API details, see CreateTopic in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: Actions 658 Amazon Simple Notification Service Developer Guide topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see CreateTopic in AWS SDK for Java 2.x API Reference.
|
sns-dg-182
|
sns-dg.pdf
| 182 |
- The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see CreateTopic in AWS SDK for Java 2.x API Reference. Actions 659 Amazon Simple Notification Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { CreateTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicName - The name of the topic to create. */ export const createTopic = async (topicName = "TOPIC_NAME") => { const response = await snsClient.send( new CreateTopicCommand({ Name: topicName }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, Actions 660 Amazon Simple Notification Service Developer Guide // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME' // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CreateTopic in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun createSNSTopic(topicName: String): String { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn.toString() } } • For API details, see CreateTopic in AWS SDK for Kotlin API reference. Actions 661 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Create a Simple Notification Service topics in your AWS account at the requested region. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topicname = 'myTopic'; try { $result = $SnSclient->createTopic([ 'Name' => $topicname, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Actions 662 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for PHP Developer Guide. • For API details, see CreateTopic in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_topic(self, name): """ Creates a notification topic. :param name: The name of the topic to create. :return: The newly created topic. """ try: topic = self.sns_resource.create_topic(Name=name) logger.info("Created topic %s with ARN %s.", name, topic.arn) except ClientError: logger.exception("Couldn't create topic %s.", name) raise else: return topic Actions 663 Amazon Simple Notification Service Developer Guide • For API details, see CreateTopic in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic. class SNSTopicCreator # Initializes an SNS client. # # Utilizes the default AWS configuration for region and credentials. def initialize @sns_client = Aws::SNS::Client.new end # Attempts to create an SNS topic with the specified name. # # @param topic_name [String] The name of the SNS topic to create. # @return [Boolean] true if the topic was successfully created, false otherwise. def create_topic(topic_name) @sns_client.create_topic(name: topic_name) puts "The topic '#{topic_name}' was successfully created." true rescue Aws::SNS::Errors::ServiceError => e # Handles SNS service errors gracefully. puts "Error while creating the topic named '#{topic_name}': #{e.message}" false end end # Example usage: Actions 664 Amazon Simple Notification Service Developer Guide if $PROGRAM_NAME == __FILE__ topic_name
|
sns-dg-183
|
sns-dg.pdf
| 183 |
the default AWS configuration for region and credentials. def initialize @sns_client = Aws::SNS::Client.new end # Attempts to create an SNS topic with the specified name. # # @param topic_name [String] The name of the SNS topic to create. # @return [Boolean] true if the topic was successfully created, false otherwise. def create_topic(topic_name) @sns_client.create_topic(name: topic_name) puts "The topic '#{topic_name}' was successfully created." true rescue Aws::SNS::Errors::ServiceError => e # Handles SNS service errors gracefully. puts "Error while creating the topic named '#{topic_name}': #{e.message}" false end end # Example usage: Actions 664 Amazon Simple Notification Service Developer Guide if $PROGRAM_NAME == __FILE__ topic_name = 'YourTopicName' # Replace with your topic name sns_topic_creator = SNSTopicCreator.new puts "Creating the topic '#{topic_name}'..." unless sns_topic_creator.create_topic(topic_name) puts 'The topic was not created. Stopping program.' exit 1 end end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see CreateTopic in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> { let resp = client.create_topic().name(topic_name).send().await?; println!( "Created topic with ARN: {}", resp.topic_arn().unwrap_or_default() ); Ok(()) } • For API details, see CreateTopic in AWS SDK for Rust API reference. Actions 665 Amazon Simple Notification Service SAP ABAP SDK for SAP ABAP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. " MESSAGE 'SNS topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY. • For API details, see CreateTopic in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.createTopic( input: CreateTopicInput(name: name) ) Actions 666 Amazon Simple Notification Service Developer Guide guard let arn = output.topicArn else { print("No topic ARN returned by Amazon SNS.") return } • For API details, see CreateTopic in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteTopic with an AWS SDK or CLI The following code examples show how to use DeleteTopic. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Delete a topic by its topic ARN. /// <summary> /// Delete a topic by its topic ARN. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteTopicByArn(string topicArn) { Actions 667 Amazon Simple Notification Service Developer Guide var deleteResponse = await _amazonSNSClient.DeleteTopicAsync( new DeleteTopicRequest() { TopicArn = topicArn }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteTopic in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Delete an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl; } Actions 668 Amazon Simple Notification Service else { Developer Guide std::cerr << "Error deleting topic " << topicARN << ":" << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteTopic in AWS SDK for C++ API Reference. CLI AWS CLI To delete an SNS topic The following delete-topic example deletes the specified SNS topic. aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" This command produces no output. • For API details, see DeleteTopic in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "log" Actions 669 Amazon Simple Notification Service Developer Guide "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns"
|
sns-dg-184
|
sns-dg.pdf
| 184 |
std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteTopic in AWS SDK for C++ API Reference. CLI AWS CLI To delete an SNS topic The following delete-topic example deletes the specified SNS topic. aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" This command produces no output. • For API details, see DeleteTopic in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "log" Actions 669 Amazon Simple Notification Service Developer Guide "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // DeleteTopic delete an Amazon SNS topic. func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error { _, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{ TopicArn: aws.String(topicArn)}) if err != nil { log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err) } return err } • For API details, see DeleteTopic in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; Actions 670 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class DeleteTopic { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); Actions 671 Amazon Simple Notification Service Developer Guide System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see DeleteTopic in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { DeleteTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to delete. */ Actions 672 Amazon Simple Notification Service Developer Guide export const deleteTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteTopic in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteSNSTopic(topicArnVal: String) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was successfully deleted.") } Actions 673 Amazon Simple Notification Service Developer Guide } • For API details, see DeleteTopic in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Deletes an SNS topic and all its subscriptions. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->deleteTopic([ 'TopicArn' => $topic, ]); var_dump($result); Actions 674 Amazon Simple Notification Service Developer Guide } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see DeleteTopic in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper:
|
sns-dg-185
|
sns-dg.pdf
| 185 |
AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->deleteTopic([ 'TopicArn' => $topic, ]); var_dump($result); Actions 674 Amazon Simple Notification Service Developer Guide } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see DeleteTopic in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_topic(topic): """ Deletes a topic. All subscriptions to the topic are also deleted. """ try: topic.delete() logger.info("Deleted topic %s.", topic.arn) except ClientError: logger.exception("Couldn't delete topic %s.", topic.arn) raise Actions 675 Amazon Simple Notification Service Developer Guide • For API details, see DeleteTopic in AWS SDK for Python (Boto3) API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->deletetopic( iv_topicarn = iv_topic_arn ). MESSAGE 'SNS topic deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see DeleteTopic in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) Actions 676 Amazon Simple Notification Service Developer Guide _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: arn) ) • For API details, see DeleteTopic in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetSMSAttributes with an AWS SDK or CLI The following code examples show how to use GetSMSAttributes. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Retrieve the default settings for sending SMS messages from your AWS account by using //! Amazon Simple Notification Service (Amazon SNS). /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::getSMSType(const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::GetSMSAttributesRequest request; //Set the request to only retrieve the DefaultSMSType setting. //Without the following line, GetSMSAttributes would retrieve all settings. request.AddAttributes("DefaultSMSType"); Actions 677 Amazon Simple Notification Service Developer Guide const Aws::SNS::Model::GetSMSAttributesOutcome outcome = snsClient.GetSMSAttributes( request); if (outcome.IsSuccess()) { const Aws::Map<Aws::String, Aws::String> attributes = outcome.GetResult().GetAttributes(); if (!attributes.empty()) { for (auto const &att: attributes) { std::cout << att.first << ": " << att.second << std::endl; } } else { std::cout << "AwsDoc::SNS::getSMSType - an empty map of attributes was retrieved." << std::endl; } } else { std::cerr << "Error while getting SMS Type: '" << outcome.GetError().GetMessage() << "'" << std::endl; } return outcome.IsSuccess(); } • For API details, see GetSMSAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To list the default SMS message attributes The following get-sms-attributes example lists the default attributes for sending SMS messages. aws sns get-sms-attributes Actions 678 Amazon Simple Notification Service Developer Guide Output: { "attributes": { "DefaultSenderID": "MyName" } } • For API details, see GetSMSAttributes in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.Iterator; import java.util.Map; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class GetSMSAtrributes { public static void main(String[] args) { Actions 679 Amazon Simple Notification Service Developer Guide final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic from which to retrieve attributes. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); getSNSAttrutes(snsClient, topicArn); snsClient.close(); } public static void getSNSAttrutes(SnsClient snsClient, String topicArn) { try { GetSubscriptionAttributesRequest request = GetSubscriptionAttributesRequest.builder() .subscriptionArn(topicArn) .build(); // Get the Subscription attributes GetSubscriptionAttributesResponse res = snsClient.getSubscriptionAttributes(request); Map<String, String> map = res.attributes(); // Iterate through the map Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } } catch (SnsException e) { Actions 680 Amazon Simple
|
sns-dg-186
|
sns-dg.pdf
| 186 |
of the topic from which to retrieve attributes. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); getSNSAttrutes(snsClient, topicArn); snsClient.close(); } public static void getSNSAttrutes(SnsClient snsClient, String topicArn) { try { GetSubscriptionAttributesRequest request = GetSubscriptionAttributesRequest.builder() .subscriptionArn(topicArn) .build(); // Get the Subscription attributes GetSubscriptionAttributesResponse res = snsClient.getSubscriptionAttributes(request); Map<String, String> map = res.attributes(); // Iterate through the map Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } } catch (SnsException e) { Actions 680 Amazon Simple Notification Service Developer Guide System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("\n\nStatus was good"); } } • For API details, see GetSMSAttributes in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { GetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const getSmsAttributes = async () => { const response = await snsClient.send( // If you have not modified the account-level mobile settings of SNS, // the DefaultSMSType is undefined. For this example, it was set to // Transactional. Actions 681 Amazon Simple Notification Service Developer Guide new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // attributes: { DefaultSMSType: 'Transactional' } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see GetSMSAttributes in AWS SDK for JavaScript API Reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Get the type of SMS Message sent by default from the AWS SNS service. * Actions 682 Amazon Simple Notification Service Developer Guide * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->getSMSAttributes([ 'attributes' => ['DefaultSMSType'], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see GetSMSAttributes in AWS SDK for PHP API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetTopicAttributes with an AWS SDK or CLI The following code examples show how to use GetTopicAttributes. Actions 683 Amazon Simple Notification Service Developer Guide .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; /// <summary> /// This example shows how to retrieve the attributes of an Amazon Simple /// Notification Service (Amazon SNS) topic. /// </summary> public class GetTopicAttributes { public static async Task Main() { string topicArn = "arn:aws:sns:us- west-2:000000000000:ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var attributes = await GetTopicAttributesAsync(client, topicArn); DisplayTopicAttributes(attributes); } /// <summary> /// Given the ARN of the Amazon SNS topic, this method retrieves the topic /// attributes. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to retrieve the attributes for the Amazon SNS topic.</param> /// <param name="topicArn">The ARN of the topic for which to retrieve /// the attributes.</param> /// <returns>A Dictionary of topic attributes.</returns> Actions 684 Amazon Simple Notification Service Developer Guide public static async Task<Dictionary<string, string>> GetTopicAttributesAsync( IAmazonSimpleNotificationService client, string topicArn) { var response = await client.GetTopicAttributesAsync(topicArn); return response.Attributes; } /// <summary> /// This method displays the attributes for an Amazon SNS topic. /// </summary> /// <param name="topicAttributes">A Dictionary containing the /// attributes for an Amazon SNS topic.</param> public static void DisplayTopicAttributes(Dictionary<string, string> topicAttributes) { foreach (KeyValuePair<string, string> entry in topicAttributes) { Console.WriteLine($"{entry.Key}: {entry.Value}\n"); } } } • For API details, see GetTopicAttributes in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Retrieve the properties of
|
sns-dg-187
|
sns-dg.pdf
| 187 |
var response = await client.GetTopicAttributesAsync(topicArn); return response.Attributes; } /// <summary> /// This method displays the attributes for an Amazon SNS topic. /// </summary> /// <param name="topicAttributes">A Dictionary containing the /// attributes for an Amazon SNS topic.</param> public static void DisplayTopicAttributes(Dictionary<string, string> topicAttributes) { foreach (KeyValuePair<string, string> entry in topicAttributes) { Console.WriteLine($"{entry.Key}: {entry.Value}\n"); } } } • For API details, see GetTopicAttributes in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Retrieve the properties of an Amazon Simple Notification Service (Amazon SNS) topic. /*! Actions 685 Amazon Simple Notification Service Developer Guide \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::getTopicAttributes(const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::GetTopicAttributesRequest request; request.SetTopicArn(topicARN); const Aws::SNS::Model::GetTopicAttributesOutcome outcome = snsClient.GetTopicAttributes( request); if (outcome.IsSuccess()) { std::cout << "Topic Attributes:" << std::endl; for (auto const &attribute: outcome.GetResult().GetAttributes()) { std::cout << " * " << attribute.first << " : " << attribute.second << std::endl; } } else { std::cerr << "Error while getting Topic attributes " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see GetTopicAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To retrieve the attributes of a topic The following get-topic-attributes example displays the attributes for the specified topic. Actions 686 Amazon Simple Notification Service Developer Guide aws sns get-topic-attributes \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" Output: { "Attributes": { "SubscriptionsConfirmed": "1", "DisplayName": "my-topic", "SubscriptionsDeleted": "0", "EffectiveDeliveryPolicy": "{\"http\":{\"defaultHealthyRetryPolicy \":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3, \"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0, \"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}", "Owner": "123456789012", "Policy": "{\"Version\":\"2008-10-17\",\"Id\":\"__default_policy_ID \",\"Statement\":[{\"Sid\":\"__default_statement_ID\",\"Effect\": \"Allow\",\"Principal\":{\"AWS\":\"*\"},\"Action\":[\"SNS:Subscribe\", \"SNS:ListSubscriptionsByTopic\",\"SNS:DeleteTopic\",\"SNS:GetTopicAttributes \",\"SNS:Publish\",\"SNS:RemovePermission\",\"SNS:AddPermission\", \"SNS:SetTopicAttributes\"],\"Resource\":\"arn:aws:sns:us-west-2:123456789012:my- topic\",\"Condition\":{\"StringEquals\":{\"AWS:SourceOwner\": \"0123456789012\"}}}]}", "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic", "SubscriptionsPending": "0" } } • For API details, see GetTopicAttributes in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; Actions 687 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.GetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.GetTopicAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class GetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to look up. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Getting attributes for a topic with name: " + topicArn); getSNSTopicAttributes(snsClient, topicArn); snsClient.close(); } public static void getSNSTopicAttributes(SnsClient snsClient, String topicArn) { try { Actions 688 Amazon Simple Notification Service Developer Guide GetTopicAttributesRequest request = GetTopicAttributesRequest.builder() .topicArn(topicArn) .build(); GetTopicAttributesResponse result = snsClient.getTopicAttributes(request); System.out.println("\n\nStatus is " + result.sdkHttpResponse().statusCode() + "\n\nAttributes: \n\n" + result.attributes()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see GetTopicAttributes in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Actions 689 Amazon Simple Notification Service Developer Guide Import the SDK and client modules and call the API. import { GetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to retrieve attributes for. */ export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new GetTopicAttributesCommand({ TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Attributes: { // Policy: '{...}', // Owner: 'xxxxxxxxxxxx', // SubscriptionsPending: '1', // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic', // TracingConfig: 'PassThrough', // EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy": {"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy": {"headerContentType":"text/plain; charset=UTF-8"}}}', // SubscriptionsConfirmed: '0', // DisplayName: '', // SubscriptionsDeleted: '1' // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. Actions 690 Amazon Simple Notification Service Developer Guide • For API details, see GetTopicAttributes in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Import the SDK and client modules and call the API. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set region AWS.config.update({ region: "REGION"
|
sns-dg-188
|
sns-dg.pdf
| 188 |
'0', // DisplayName: '', // SubscriptionsDeleted: '1' // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. Actions 690 Amazon Simple Notification Service Developer Guide • For API details, see GetTopicAttributes in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Import the SDK and client modules and call the API. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set region AWS.config.update({ region: "REGION" }); // Create promise and SNS service object var getTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) .getTopicAttributes({ TopicArn: "TOPIC_ARN" }) .promise(); // Handle promise's fulfilled/rejected states getTopicAttribsPromise .then(function (data) { console.log(data); }) .catch(function (err) { console.error(err, err.stack); }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see GetTopicAttributes in AWS SDK for JavaScript API Reference. Actions 691 Amazon Simple Notification Service Developer Guide Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun getSNSTopicAttributes(topicArnVal: String) { val request = GetTopicAttributesRequest { topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.getTopicAttributes(request) println("${result.attributes}") } } • For API details, see GetTopicAttributes in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); Actions 692 Amazon Simple Notification Service Developer Guide $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->getTopicAttributes([ 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see GetTopicAttributes in AWS SDK for PHP API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sns->gettopicattributes( iv_topicarn = iv_topic_arn ). " oo_result is returned for testing purposes. " DATA(lt_attributes) = oo_result->get_attributes( ). MESSAGE 'Retrieved attributes/properties of a topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see GetTopicAttributes in AWS SDK for SAP ABAP API reference. Actions 693 Amazon Simple Notification Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListPhoneNumbersOptedOut with an AWS SDK or CLI The following code examples show how to use ListPhoneNumbersOptedOut. CLI AWS CLI To list SMS message opt-outs The following list-phone-numbers-opted-out example lists the phone numbers opted out of receiving SMS messages. aws sns list-phone-numbers-opted-out Output: { "phoneNumbers": [ "+15555550100" ] } • For API details, see ListPhoneNumbersOptedOut in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; Actions 694 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutRequest; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class ListOptOut { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listOpts(snsClient); snsClient.close(); } public static void listOpts(SnsClient snsClient) { try { ListPhoneNumbersOptedOutRequest request = ListPhoneNumbersOptedOutRequest.builder().build(); ListPhoneNumbersOptedOutResponse result = snsClient.listPhoneNumbersOptedOut(request); System.out.println("Status is " + result.sdkHttpResponse().statusCode() + "\n\nPhone Numbers: \n\n" + result.phoneNumbers()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListPhoneNumbersOptedOut in AWS SDK for Java 2.x API Reference. Actions 695 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Returns a list of phone numbers that are opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listPhoneNumbersOptedOut(); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. Actions 696 Amazon Simple Notification Service Developer Guide • For API details, see ListPhoneNumbersOptedOut in AWS SDK
|
sns-dg-189
|
sns-dg.pdf
| 189 |
Aws\Sns\SnsClient; /** * Returns a list of phone numbers that are opted out of receiving SMS messages from your AWS SNS account. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listPhoneNumbersOptedOut(); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. Actions 696 Amazon Simple Notification Service Developer Guide • For API details, see ListPhoneNumbersOptedOut in AWS SDK for PHP API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListSubscriptions with an AWS SDK or CLI The following code examples show how to use ListSubscriptions. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example will retrieve a list of the existing Amazon Simple /// Notification Service (Amazon SNS) subscriptions. /// </summary> public class ListSubscriptions { public static async Task Main() { IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); Console.WriteLine("Enter a topic ARN to list subscriptions for a specific topic, " + "or press Enter to list subscriptions for all topics."); Actions 697 Amazon Simple Notification Service Developer Guide var topicArn = Console.ReadLine(); Console.WriteLine(); var subscriptions = await GetSubscriptionsListAsync(client, topicArn); DisplaySubscriptionList(subscriptions); } /// <summary> /// Gets a list of the existing Amazon SNS subscriptions, optionally by specifying a topic ARN. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to obtain the list of subscriptions.</param> /// <param name="topicArn">The optional ARN of a specific topic. Defaults to null.</param> /// <returns>A list containing information about each subscription.</ returns> public static async Task<List<Subscription>> GetSubscriptionsListAsync(IAmazonSimpleNotificationService client, string topicArn = null) { var results = new List<Subscription>(); if (!string.IsNullOrEmpty(topicArn)) { var paginateByTopic = client.Paginators.ListSubscriptionsByTopic( new ListSubscriptionsByTopicRequest() { TopicArn = topicArn, }); // Get the entire list using the paginator. await foreach (var subscription in paginateByTopic.Subscriptions) { results.Add(subscription); } } else { var paginateAllSubscriptions = client.Paginators.ListSubscriptions(new ListSubscriptionsRequest()); Actions 698 Amazon Simple Notification Service Developer Guide // Get the entire list using the paginator. await foreach (var subscription in paginateAllSubscriptions.Subscriptions) { results.Add(subscription); } } return results; } /// <summary> /// Display a list of Amazon SNS subscription information. /// </summary> /// <param name="subscriptionList">A list containing details for existing /// Amazon SNS subscriptions.</param> public static void DisplaySubscriptionList(List<Subscription> subscriptionList) { foreach (var subscription in subscriptionList) { Console.WriteLine($"Owner: {subscription.Owner}"); Console.WriteLine($"Subscription ARN: {subscription.SubscriptionArn}"); Console.WriteLine($"Topic ARN: {subscription.TopicArn}"); Console.WriteLine($"Endpoint: {subscription.Endpoint}"); Console.WriteLine($"Protocol: {subscription.Protocol}"); Console.WriteLine(); } } } • For API details, see ListSubscriptions in AWS SDK for .NET API Reference. Actions 699 Amazon Simple Notification Service Developer Guide C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) subscriptions. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::listSubscriptions( const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::String nextToken; // Next token is used to handle a paginated response. bool result = true; Aws::Vector<Aws::SNS::Model::Subscription> subscriptions; do { Aws::SNS::Model::ListSubscriptionsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListSubscriptionsOutcome outcome = snsClient.ListSubscriptions( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SNS::Model::Subscription> &newSubscriptions = outcome.GetResult().GetSubscriptions(); subscriptions.insert(subscriptions.cend(), newSubscriptions.begin(), newSubscriptions.end()); } else { std::cerr << "Error listing subscriptions " Actions 700 Amazon Simple Notification Service Developer Guide << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); if (result) { if (subscriptions.empty()) { std::cout << "No subscriptions found" << std::endl; } else { std::cout << "Subscriptions list:" << std::endl; for (auto const &subscription: subscriptions) { std::cout << " * " << subscription.GetSubscriptionArn() << std::endl; } } } return result; } • For API details, see ListSubscriptions in AWS SDK for C++ API Reference. CLI AWS CLI To list your SNS subscriptions The following list-subscriptions example displays a list of the SNS subscriptions in your AWS account. aws sns list-subscriptions Output: { Actions 701 Amazon Simple Notification Service Developer Guide "Subscriptions": [ { "Owner": "123456789012", "Endpoint": "my-email@example.com", "Protocol": "email", "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic", "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my- topic:8a21d249-4329-4871-acc6-7be709c6ea7f" } ] } • For API details, see ListSubscriptions in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListSubscriptionsRequest; import software.amazon.awssdk.services.sns.model.ListSubscriptionsResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For
|
sns-dg-190
|
sns-dg.pdf
| 190 |
aws sns list-subscriptions Output: { Actions 701 Amazon Simple Notification Service Developer Guide "Subscriptions": [ { "Owner": "123456789012", "Endpoint": "my-email@example.com", "Protocol": "email", "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic", "SubscriptionArn": "arn:aws:sns:us-west-2:123456789012:my- topic:8a21d249-4329-4871-acc6-7be709c6ea7f" } ] } • For API details, see ListSubscriptions in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListSubscriptionsRequest; import software.amazon.awssdk.services.sns.model.ListSubscriptionsResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class ListSubscriptions { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() Actions 702 Amazon Simple Notification Service Developer Guide .region(Region.US_EAST_1) .build(); listSNSSubscriptions(snsClient); snsClient.close(); } public static void listSNSSubscriptions(SnsClient snsClient) { try { ListSubscriptionsRequest request = ListSubscriptionsRequest.builder() .build(); ListSubscriptionsResponse result = snsClient.listSubscriptions(request); System.out.println(result.subscriptions()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListSubscriptions in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; Actions 703 Amazon Simple Notification Service Developer Guide // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions. */ export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Subscriptions: [ // { // SubscriptionArn: 'PendingConfirmation', // Owner: '901487484989', // Protocol: 'email', // Endpoint: 'corepyle@amazon.com', // TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic' // } // ] // } return response; }; Actions 704 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListSubscriptions in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun listSNSSubscriptions() { SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.listSubscriptions(ListSubscriptionsRequest {}) response.subscriptions?.forEach { sub -> println("Sub ARN is ${sub.subscriptionArn}") println("Sub protocol is ${sub.protocol}") } } } • For API details, see ListSubscriptions in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; Actions 705 Amazon Simple Notification Service Developer Guide use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Returns a list of Amazon SNS subscriptions in the requested region. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listSubscriptions(); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see ListSubscriptions in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" Actions 706 Amazon Simple Notification Service Developer Guide def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def list_subscriptions(self, topic=None): """ Lists subscriptions for the current account, optionally limited to a specific topic. :param topic: When specified, only subscriptions to this topic are returned. :return: An iterator that yields the subscriptions. """ try: if topic is None: subs_iter = self.sns_resource.subscriptions.all() else: subs_iter = topic.subscriptions.all() logger.info("Got subscriptions.") except ClientError: logger.exception("Couldn't get subscriptions.") raise else: return subs_iter • For API details, see ListSubscriptions in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 707 Amazon Simple Notification Service Developer Guide # This class demonstrates how to list subscriptions to an Amazon Simple Notification Service (SNS) topic class SnsSubscriptionLister def initialize(sns_client) @sns_client = sns_client @logger =
|
sns-dg-191
|
sns-dg.pdf
| 191 |
the subscriptions. """ try: if topic is None: subs_iter = self.sns_resource.subscriptions.all() else: subs_iter = topic.subscriptions.all() logger.info("Got subscriptions.") except ClientError: logger.exception("Couldn't get subscriptions.") raise else: return subs_iter • For API details, see ListSubscriptions in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 707 Amazon Simple Notification Service Developer Guide # This class demonstrates how to list subscriptions to an Amazon Simple Notification Service (SNS) topic class SnsSubscriptionLister def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Lists subscriptions for a given SNS topic # @param topic_arn [String] The ARN of the SNS topic # @return [Types::ListSubscriptionsResponse] subscriptions: The response object def list_subscriptions(topic_arn) @logger.info("Listing subscriptions for topic: #{topic_arn}") subscriptions = @sns_client.list_subscriptions_by_topic(topic_arn: topic_arn) subscriptions.subscriptions.each do |subscription| @logger.info("Subscription endpoint: #{subscription.endpoint}") end subscriptions rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error listing subscriptions: #{e.message}") raise end end # Example usage: if $PROGRAM_NAME == __FILE__ sns_client = Aws::SNS::Client.new topic_arn = 'SNS_TOPIC_ARN' # Replace with your SNS topic ARN lister = SnsSubscriptionLister.new(sns_client) begin lister.list_subscriptions(topic_arn) rescue StandardError => e puts "Failed to list subscriptions: #{e.message}" exit 1 end end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see ListSubscriptions in AWS SDK for Ruby API Reference. Actions 708 Amazon Simple Notification Service SAP ABAP SDK for SAP ABAP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sns->listsubscriptions( ). " oo_result is returned for testing purposes. " DATA(lt_subscriptions) = oo_result->get_subscriptions( ). MESSAGE 'Retrieved list of subscribers.' TYPE 'I'. CATCH /aws1/cx_rt_generic. MESSAGE 'Unable to list subscribers.' TYPE 'E'. ENDTRY. • For API details, see ListSubscriptions in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListTopics with an AWS SDK or CLI The following code examples show how to use ListTopics. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 709 Amazon Simple Notification Service Developer Guide using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// Lists the Amazon Simple Notification Service (Amazon SNS) /// topics for the current account. /// </summary> public class ListSNSTopics { public static async Task Main() { IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await GetTopicListAsync(client); } /// <summary> /// Retrieves the list of Amazon SNS topics in groups of up to 100 /// topics. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to retrieve the list of topics.</param> public static async Task GetTopicListAsync(IAmazonSimpleNotificationService client) { // If there are more than 100 Amazon SNS topics, the call to // ListTopicsAsync will return a value to pass to the // method to retrieve the next 100 (or less) topics. string nextToken = string.Empty; do { var response = await client.ListTopicsAsync(nextToken); DisplayTopicsList(response.Topics); nextToken = response.NextToken; } while (!string.IsNullOrEmpty(nextToken)); } Actions 710 Amazon Simple Notification Service Developer Guide /// <summary> /// Displays the list of Amazon SNS Topic ARNs. /// </summary> /// <param name="topicList">The list of Topic ARNs.</param> public static void DisplayTopicsList(List<Topic> topicList) { foreach (var topic in topicList) { Console.WriteLine($"{topic.TopicArn}"); } } } • For API details, see ListTopics in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) topics. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::listTopics(const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::String nextToken; // Next token is used to handle a paginated response. bool result = true; do { Aws::SNS::Model::ListTopicsRequest request; Actions 711 Amazon Simple Notification Service Developer Guide if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { std::cout << "Topics list:" << std::endl; for (auto const &topic: outcome.GetResult().GetTopics()) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); return result; } • For API details, see ListTopics in AWS SDK for C++ API Reference. CLI AWS CLI To list your SNS topics The following list-topics example lists all of SNS topics in your AWS account. aws sns list-topics Output: { Actions 712 Amazon Simple Notification Service "Topics": [ Developer Guide { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } ] } • For API details, see ListTopics in
|
sns-dg-192
|
sns-dg.pdf
| 192 |
{ std::cout << " * " << topic.GetTopicArn() << std::endl; } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); return result; } • For API details, see ListTopics in AWS SDK for C++ API Reference. CLI AWS CLI To list your SNS topics The following list-topics example lists all of SNS topics in your AWS account. aws sns list-topics Output: { Actions 712 Amazon Simple Notification Service "Topics": [ Developer Guide { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } ] } • For API details, see ListTopics in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { Actions 713 Amazon Simple Notification Service Developer Guide fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } snsClient := sns.NewFromConfig(sdkConfig) fmt.Println("Let's list the topics for your account.") var topics []types.Topic paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get topics. Here's why: %v\n", err) break } else { topics = append(topics, output.Topics...) } } if len(topics) == 0 { fmt.Println("You don't have any topics!") } else { for _, topic := range topics { fmt.Printf("\t%v\n", *topic.TopicArn) } } } • For API details, see ListTopics in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; Actions 714 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListTopicsRequest; import software.amazon.awssdk.services.sns.model.ListTopicsResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class ListTopics { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsRequest request = ListTopicsRequest.builder() .build(); ListTopicsResponse result = snsClient.listTopics(request); System.out.println( "Status was " + result.sdkHttpResponse().statusCode() + "\n \nTopics\n\n" + result.topics()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListTopics in AWS SDK for Java 2.x API Reference. Actions 715 Amazon Simple Notification Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { ListTopicsCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const listTopics = async () => { const response = await snsClient.send(new ListTopicsCommand({})); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ] // } return response; }; Actions 716 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListTopics in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun listSNSTopics() { SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.listTopics(ListTopicsRequest { }) response.topics?.forEach { topic -> println("The topic ARN is ${topic.topicArn}") } } } • For API details, see ListTopics in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; Actions 717 Amazon Simple Notification Service Developer Guide /** * Returns a list of the requester's topics from your AWS SNS account in the region specified. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient
|
sns-dg-193
|
sns-dg.pdf
| 193 |
topic -> println("The topic ARN is ${topic.topicArn}") } } } • For API details, see ListTopics in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; Actions 717 Amazon Simple Notification Service Developer Guide /** * Returns a list of the requester's topics from your AWS SNS account in the region specified. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->listTopics(); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see ListTopics in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" Actions 718 Amazon Simple Notification Service Developer Guide def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def list_topics(self): """ Lists topics for the current account. :return: An iterator that yields the topics. """ try: topics_iter = self.sns_resource.topics.all() logger.info("Got topics.") except ClientError: logger.exception("Couldn't get topics.") raise else: return topics_iter • For API details, see ListTopics in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sns' # v2: require 'aws-sdk' def list_topics?(sns_client) sns_client.topics.each do |topic| puts topic.arn Actions 719 Amazon Simple Notification Service Developer Guide rescue StandardError => e puts "Error while listing the topics: #{e.message}" end end def run_me region = 'REGION' sns_client = Aws::SNS::Resource.new(region: region) puts 'Listing the topics.' return if list_topics?(sns_client) puts 'The bucket was not created. Stopping program.' exit 1 end # Example usage: run_me if $PROGRAM_NAME == __FILE__ • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see ListTopics in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn show_topics(client: &Client) -> Result<(), Error> { let resp = client.list_topics().send().await?; println!("Topic ARNs:"); for topic in resp.topics() { Actions 720 Amazon Simple Notification Service Developer Guide println!("{}", topic.topic_arn().unwrap_or_default()); } Ok(()) } • For API details, see ListTopics in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sns->listtopics( ). " oo_result is returned for testing purposes. " DATA(lt_topics) = oo_result->get_topics( ). MESSAGE 'Retrieved list of topics.' TYPE 'I'. CATCH /aws1/cx_rt_generic. MESSAGE 'Unable to list topics.' TYPE 'E'. ENDTRY. • For API details, see ListTopics in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 721 Amazon Simple Notification Service Developer Guide import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) var topics: [String] = [] let outputPages = snsClient.listTopicsPaginated( input: ListTopicsInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let topicList = output.topics else { print("Unable to get a page of Amazon SNS topics.") return } // Iterate over the topics listed on this page, adding their ARNs // to the `topics` array. for topic in topicList { guard let arn = topic.topicArn else { print("Topic has no ARN.") return } topics.append(arn) } } • For API details, see ListTopics in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use Publish with an AWS SDK or CLI The following code examples show how to use Publish. Actions 722 Amazon Simple Notification Service Developer Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Create and publish to a FIFO topic • Publish an SMS text message • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Publish
|
sns-dg-194
|
sns-dg.pdf
| 194 |
SDK versions. Use Publish with an AWS SDK or CLI The following code examples show how to use Publish. Actions 722 Amazon Simple Notification Service Developer Guide Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Create and publish to a FIFO topic • Publish an SMS text message • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Publish a message to a topic. using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example publishes a message to an Amazon Simple Notification /// Service (Amazon SNS) topic. /// </summary> public class PublishToSNSTopic { public static async Task Main() { string topicArn = "arn:aws:sns:us- east-2:000000000000:ExampleSNSTopic"; string messageText = "This is an example message to publish to the ExampleSNSTopic."; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await PublishToTopicAsync(client, topicArn, messageText); Actions 723 Amazon Simple Notification Service } Developer Guide /// <summary> /// Publishes a message to an Amazon SNS topic. /// </summary> /// <param name="client">The initialized client object used to publish /// to the Amazon SNS topic.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="messageText">The text of the message.</param> public static async Task PublishToTopicAsync( IAmazonSimpleNotificationService client, string topicArn, string messageText) { var request = new PublishRequest { TopicArn = topicArn, Message = messageText, }; var response = await client.PublishAsync(request); Console.WriteLine($"Successfully published message ID: {response.MessageId}"); } } Publish a message to a topic with group, duplication, and attribute options. /// <summary> /// Publish messages using user settings. /// </summary> /// <returns>Async task.</returns> public static async Task PublishMessages() { Console.WriteLine("Now we can publish messages."); var keepSendingMessages = true; string? deduplicationId = null; string? toneAttribute = null; while (keepSendingMessages) Actions 724 Amazon Simple Notification Service { Developer Guide Console.WriteLine(); var message = GetUserResponse("Enter a message to publish.", "This is a sample message"); if (_useFifoTopic) { Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." + "\r\nAll messages within the same group will be received in the order " + "they were published."); Console.WriteLine(); var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1"); if (!_useContentBasedDeduplication) { Console.WriteLine("Because you are not using content-based deduplication, " + "you must enter a deduplication ID."); Console.WriteLine("Enter a deduplication ID for this message."); deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1"); } if (GetYesNoResponse("Add an attribute to this message?")) { Console.WriteLine("Enter a number for an attribute."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", "1"); int.TryParse(selection, out var selectionNumber); if (selectionNumber > 0 && selectionNumber < _tones.Length) { toneAttribute = _tones[selectionNumber - 1]; } Actions 725 Amazon Simple Notification Service } Developer Guide var messageID = await SnsWrapper.PublishToTopicWithAttribute( _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId); Console.WriteLine($"Message published with id {messageID}."); } keepSendingMessages = GetYesNoResponse("Send another message?", false); } } Apply the user's selections to the publish action. /// <summary> /// Publish a message to a topic with an attribute and optional deduplication and group IDs. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="message">The message to publish.</param> /// <param name="attributeName">The optional attribute for the message.</ param> /// <param name="attributeValue">The optional attribute value for the message.</param> /// <param name="deduplicationId">The optional deduplication ID for the message.</param> /// <param name="groupId">The optional group ID for the message.</param> /// <returns>The ID of the message published.</returns> public async Task<string> PublishToTopicWithAttribute( string topicArn, string message, string? attributeName = null, string? attributeValue = null, string? deduplicationId = null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, Actions 726 Amazon Simple Notification Service Developer Guide MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; } • For API details, see Publish in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param message: The message to publish. \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishToTopic(const Aws::String &message, const Aws::String &topicARN, Actions 727 Amazon Simple Notification Service Developer Guide const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetTopicArn(topicARN); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with
|
sns-dg-195
|
sns-dg.pdf
| 195 |
GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param message: The message to publish. \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishToTopic(const Aws::String &message, const Aws::String &topicARN, Actions 727 Amazon Simple Notification Service Developer Guide const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetTopicArn(topicARN); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with id '" << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } Publish a message with an attribute. static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetTopicArn(topicARN); Aws::String message = askQuestion("Enter a message text to publish. "); request.SetMessage(message); if (filteringMessages && askYesNoQuestion( Actions 728 Amazon Simple Notification Service Developer Guide "Add an attribute to this message? (y/n) ")) { for (size_t i = 0; i < TONES.size(); ++i) { std::cout << " " << (i + 1) << ". " << TONES[i] << std::endl; } int selection = askQuestionForIntRange( "Enter a number for an attribute. ", 1, static_cast<int>(TONES.size())); Aws::SNS::Model::MessageAttributeValue messageAttributeValue; messageAttributeValue.SetDataType("String"); messageAttributeValue.SetStringValue(TONES[selection - 1]); request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue); } Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Your message was successfully published." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Publish. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } • For API details, see Publish in AWS SDK for C++ API Reference. CLI AWS CLI Example 1: To publish a message to a topic The following publish example publishes the specified message to the specified SNS topic. The message comes from a text file, which enables you to include line breaks. Actions 729 Amazon Simple Notification Service Developer Guide aws sns publish \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \ --message file://message.txt Contents of message.txt: Hello World Second Line Output: { "MessageId": "123a45b6-7890-12c3-45d6-111122223333" } Example 2: To publish an SMS message to a phone number The following publish example publishes the message Hello world! to the phone number +1-555-555-0100. aws sns publish \ --message "Hello world!" \ --phone-number +1-555-555-0100 Output: { "MessageId": "123a45b6-7890-12c3-45d6-333322221111" } • For API details, see Publish in AWS CLI Command Reference. Actions 730 Amazon Simple Notification Service Developer Guide Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a deduplication ID. An optional key- value // filter attribute can be specified so that the message can be filtered according to // a filter policy. func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error { Actions 731 Amazon Simple Notification Service Developer Guide publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)} if groupId != "" { publishInput.MessageGroupId = aws.String(groupId) } if dedupId != "" { publishInput.MessageDeduplicationId = aws.String(dedupId) } if filterKey != "" && filterValue != "" { publishInput.MessageAttributes = map[string]types.MessageAttributeValue{ filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)}, } } _, err := actor.SnsClient.Publish(ctx, &publishInput) if err != nil { log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err) } return err } • For API details, see Publish in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; Actions 732 Amazon Simple Notification Service /** Developer Guide * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTopic { public static void main(String[] args) { final String usage = """ Usage: <message> <topicArn> Where: message - The message text to send. topicArn - The ARN of the topic to publish. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTopic(snsClient, message, topicArn); snsClient.close(); }
|
sns-dg-196
|
sns-dg.pdf
| 196 |
Notification Service /** Developer Guide * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTopic { public static void main(String[] args) { final String usage = """ Usage: <message> <topicArn> Where: message - The message text to send. topicArn - The ARN of the topic to publish. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTopic(snsClient, message, topicArn); snsClient.close(); } public static void pubTopic(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out Actions 733 Amazon Simple Notification Service Developer Guide .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see Publish in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { PublishCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object Actions 734 Amazon Simple Notification Service Developer Guide * if you are using the `json` `MessageStructure`. * @param {string} topicArn - The ARN of the topic to which you would like to publish. */ export const publish = async ( message = "Hello from SNS!", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( new PublishCommand({ Message: message, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; Publish a message to a topic with group, duplication, and attribute options. async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId; let deduplicationId; let choices; if (this.isFifo) { Actions 735 Amazon Simple Notification Service Developer Guide await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); } choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId ? { MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); Actions 736 Amazon Simple Notification Service Developer Guide const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } } • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Publish in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun pubTopic( topicArnVal: String, messageVal: String, ) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } } Actions 737 Amazon Simple Notification Service Developer Guide • For API details, see Publish in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Sends a message to an Amazon SNS topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { Actions 738 Amazon Simple Notification Service Developer Guide // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Publish in AWS SDK for PHP API Reference. PowerShell Tools for PowerShell Example 1: This example shows publishing a message with a single MessageAttribute
|
sns-dg-197
|
sns-dg.pdf
| 197 |
SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { Actions 738 Amazon Simple Notification Service Developer Guide // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Publish in AWS SDK for PHP API Reference. PowerShell Tools for PowerShell Example 1: This example shows publishing a message with a single MessageAttribute declared inline. Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" - Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}} Example 2: This example shows publishing a message with multiple MessageAttributes declared in advance. $cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue $cityAttributeValue.DataType = "String" $cityAttributeValue.StringValue = "AnyCity" $populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue $populationAttributeValue.DataType = "Number" $populationAttributeValue.StringValue = "1250800" $messageAttributes = New-Object System.Collections.Hashtable $messageAttributes.Add("City", $cityAttributeValue) $messageAttributes.Add("Population", $populationAttributeValue) Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" - Message "Hello" -MessageAttribute $messageAttributes Actions 739 Amazon Simple Notification Service Developer Guide • For API details, see Publish in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Publish a message with attributes so that a subscription can filter based on attributes. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def publish_message(topic, message, attributes): """ Publishes a message, with attributes, to a topic. Subscriptions can be filtered based on message attributes so that a subscription receives messages only when specified attributes are present. :param topic: The topic to publish to. :param message: The message to publish. :param attributes: The key-value attributes to attach to the message. Values must be either `str` or `bytes`. :return: The ID of the message. """ try: att_dict = {} for key, value in attributes.items(): Actions 740 Amazon Simple Notification Service Developer Guide if isinstance(value, str): att_dict[key] = {"DataType": "String", "StringValue": value} elif isinstance(value, bytes): att_dict[key] = {"DataType": "Binary", "BinaryValue": value} response = topic.publish(Message=message, MessageAttributes=att_dict) message_id = response["MessageId"] logger.info( "Published message with attributes %s to topic %s.", attributes, topic.arn, ) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id Publish a message that takes different forms based on the protocol of the subscriber. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def publish_multi_message( topic, subject, default_message, sms_message, email_message ): """ Publishes a multi-format message to a topic. A multi-format message takes different forms based on the protocol of the subscriber. For example, an SMS subscriber might receive a short version of the message while an email subscriber could receive a longer version. :param topic: The topic to publish to. :param subject: The subject of the message. Actions 741 Amazon Simple Notification Service Developer Guide :param default_message: The default version of the message. This version is sent to subscribers that have protocols that are not otherwise specified in the structured message. :param sms_message: The version of the message sent to SMS subscribers. :param email_message: The version of the message sent to email subscribers. :return: The ID of the message. """ try: message = { "default": default_message, "sms": sms_message, "email": email_message, } response = topic.publish( Message=json.dumps(message), Subject=subject, MessageStructure="json" ) message_id = response["MessageId"] logger.info("Published multi-format message to topic %s.", topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id • For API details, see Publish in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 742 Amazon Simple Notification Service Developer Guide # Service class for sending messages using Amazon Simple Notification Service (SNS) class SnsMessageSender # Initializes the SnsMessageSender with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Sends a message to a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param message [String] The message to send # @return [Boolean] true if message was successfully sent, false otherwise def send_message(topic_arn, message) @sns_client.publish(topic_arn: topic_arn, message: message) @logger.info("Message sent successfully to #{topic_arn}.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while sending the message: #{e.message}") false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN message = 'MESSAGE' # Should be replaced with the actual message content sns_client = Aws::SNS::Client.new message_sender = SnsMessageSender.new(sns_client) @logger.info('Sending message.') unless message_sender.send_message(topic_arn, message) @logger.error('Message sending failed. Stopping program.') exit 1 end end Actions
|
sns-dg-198
|
sns-dg.pdf
| 198 |
the SNS topic # @param message [String] The message to send # @return [Boolean] true if message was successfully sent, false otherwise def send_message(topic_arn, message) @sns_client.publish(topic_arn: topic_arn, message: message) @logger.info("Message sent successfully to #{topic_arn}.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while sending the message: #{e.message}") false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN message = 'MESSAGE' # Should be replaced with the actual message content sns_client = Aws::SNS::Client.new message_sender = SnsMessageSender.new(sns_client) @logger.info('Sending message.') unless message_sender.send_message(topic_arn, message) @logger.error('Message sending failed. Stopping program.') exit 1 end end Actions 743 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see Publish in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; println!("Published message: {:?}", rsp); Ok(()) } Actions 744 Amazon Simple Notification Service Developer Guide • For API details, see Publish in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sns->publish( " oo_result is returned for testing purposes. " iv_topicarn = iv_topic_arn iv_message = iv_message ). MESSAGE 'Message published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see Publish in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSNS Actions 745 Amazon Simple Notification Service Developer Guide let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.publish( input: PublishInput( message: message, topicArn: arn ) ) guard let messageId = output.messageId else { print("No message ID received from Amazon SNS.") return } print("Published message with ID \(messageId)") • For API details, see Publish in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetSMSAttributes with an AWS SDK or CLI The following code examples show how to use SetSMSAttributes. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. How to use Amazon SNS to set the DefaultSMSType attribute. //! Set the default settings for sending SMS messages. /*! Actions 746 Amazon Simple Notification Service Developer Guide \param smsType: The type of SMS message that you will send by default. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::setSMSType(const Aws::String &smsType, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SetSMSAttributesRequest request; request.AddAttributes("DefaultSMSType", smsType); const Aws::SNS::Model::SetSMSAttributesOutcome outcome = snsClient.SetSMSAttributes( request); if (outcome.IsSuccess()) { std::cout << "SMS Type set successfully " << std::endl; } else { std::cerr << "Error while setting SMS Type: '" << outcome.GetError().GetMessage() << "'" << std::endl; } return outcome.IsSuccess(); } • For API details, see SetSMSAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To set SMS message attributes The following set-sms-attributes example sets the default sender ID for SMS messages to MyName. aws sns set-sms-attributes \ --attributes DefaultSenderID=MyName Actions 747 Amazon Simple Notification Service Developer Guide This command produces no output. • For API details, see SetSMSAttributes in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } Actions 748 Amazon Simple Notification Service Developer Guide public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " +
|
sns-dg-199
|
sns-dg.pdf
| 199 |
Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } Actions 748 Amazon Simple Notification Service Developer Guide public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see SetSMSAttributes in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Actions 749 Amazon Simple Notification Service Developer Guide Import the SDK and client modules and call the API. import { SetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {"Transactional" | "Promotional"} defaultSmsType */ export const setSmsType = async (defaultSmsType = "Transactional") => { const response = await snsClient.send( new SetSMSAttributesCommand({ attributes: { // Promotional – (Default) Noncritical messages, such as marketing messages. // Transactional – Critical messages that support customer transactions, // such as one-time passcodes for multi-factor authentication. DefaultSMSType: defaultSmsType, }, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '1885b977-2d7e-535e-8214-e44be727e265', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SetSMSAttributes in AWS SDK for JavaScript API Reference. Actions 750 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); try { $result = $SnSclient->SetSMSAttributes([ 'attributes' => [ 'DefaultSMSType' => 'Transactional', ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see SetSMSAttributes in AWS SDK for PHP API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetSubscriptionAttributes with an AWS SDK or CLI The following code examples show how to use SetSubscriptionAttributes. Actions 751 Amazon Simple Notification Service Developer Guide CLI AWS CLI To set subscription attributes The following set-subscription-attributes example sets the RawMessageDelivery attribute to an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true This command produces no output. The following set-subscription-attributes example sets a FilterPolicy attribute to an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }" This command produces no output. The following set-subscription-attributes example removes the FilterPolicy attribute from an SQS subscription. aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us- east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}" This command produces no output. • For API details, see SetSubscriptionAttributes in AWS CLI Command Reference. Actions 752 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.ArrayList; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() Actions 753 Amazon Simple Notification Service Developer Guide .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a
|
sns-dg-200
|
sns-dg.pdf
| 200 |
UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() Actions 753 Amazon Simple Notification Service Developer Guide .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a filter policy attribute with a list of values ArrayList<String> attributeValues = new ArrayList<>(); attributeValues.add("rugby"); attributeValues.add("soccer"); attributeValues.add("hockey"); fp.addAttribute("customer_interests", attributeValues); // Add a numeric attribute fp.addAttribute("price_usd", "=", 0); // Add a numeric attribute with a range fp.addAttributeRange("price_usd", ">", 0, "<=", 100); // Apply the filter policy attributes to an Amazon SNS subscription fp.apply(snsClient, subscriptionArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Actions 754 Amazon Simple Notification Service Developer Guide • For API details, see SetSubscriptionAttributes in AWS SDK for Java 2.x API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def add_subscription_filter(subscription, attributes): """ Adds a filter policy to a subscription. A filter policy is a key and a list of values that are allowed. When a message is published, it must have an attribute that passes the filter or it will not be sent to the subscription. :param subscription: The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) Actions 755 Amazon Simple Notification Service Developer Guide except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise • For API details, see SetSubscriptionAttributes in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetSubscriptionAttributesRedrivePolicy with an AWS SDK The following code example shows how to use SetSubscriptionAttributesRedrivePolicy. Java SDK for Java 1.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. // Specify the ARN of the Amazon SNS subscription. String subscriptionArn = "arn:aws:sns:us-east-2:123456789012:MyEndpoint:1234a567- bc89-012d-3e45-6fg7h890123i"; // Specify the ARN of the Amazon SQS queue to use as a dead-letter queue. String redrivePolicy = "{\"deadLetterTargetArn\":\"arn:aws:sqs:us- east-2:123456789012:MyDeadLetterQueue\"}"; // Set the specified Amazon SQS queue as a dead-letter queue Actions 756 Amazon Simple Notification Service Developer Guide // of the specified Amazon SNS subscription by setting the RedrivePolicy attribute. SetSubscriptionAttributesRequest request = new SetSubscriptionAttributesRequest() .withSubscriptionArn(subscriptionArn) .withAttributeName("RedrivePolicy") .withAttributeValue(redrivePolicy); sns.setSubscriptionAttributes(request); For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetTopicAttributes with an AWS SDK or CLI The following code examples show how to use SetTopicAttributes. CLI AWS CLI To set an attribute for a topic The following set-topic-attributes example sets the DisplayName attribute for the specified topic. aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name DisplayName \ --attribute-value MyTopicDisplayName This command produces no output. • For API details, see SetTopicAttributes in AWS CLI Command Reference. Actions 757 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); Actions 758 Amazon Simple Notification Service } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; Developer Guide SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request =
|
sns-dg-201
|
sns-dg.pdf
| 201 |
args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); Actions 758 Amazon Simple Notification Service } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; Developer Guide SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName(attribute) .attributeValue(value) .topicArn(topicArn) .build(); SetTopicAttributesResponse result = snsClient.setTopicAttributes(request); System.out.println( "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn() + " updated " + request.attributeName() + " to " + request.attributeValue()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see SetTopicAttributes in AWS SDK for Java 2.x API Reference. Actions 759 Amazon Simple Notification Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn = "TOPIC_ARN", attributeName = "DisplayName", attributeValue = "Test Topic", ) => { const response = await snsClient.send( new SetTopicAttributesCommand({ AttributeName: attributeName, AttributeValue: attributeValue, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935', Actions 760 Amazon Simple Notification Service Developer Guide // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SetTopicAttributes in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun setTopAttr( attribute: String?, topicArnVal: String?, value: String?, ) { val request = SetTopicAttributesRequest { attributeName = attribute attributeValue = value topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.setTopicAttributes(request) println("Topic ${request.topicArn} was updated.") } } Actions 761 Amazon Simple Notification Service Developer Guide • For API details, see SetTopicAttributes in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Configure the message delivery status attributes for an Amazon SNS Topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $attribute = 'Policy | DisplayName | DeliveryPolicy'; $value = 'First Topic'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->setTopicAttributes([ 'AttributeName' => $attribute, 'AttributeValue' => $value, 'TopicArn' => $topic, ]); var_dump($result); Actions 762 Amazon Simple Notification Service Developer Guide } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see SetTopicAttributes in AWS SDK for PHP API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # Service class to enable an SNS resource with a specified policy class SnsResourceEnabler # Initializes the SnsResourceEnabler with an SNS resource client # # @param sns_resource [Aws::SNS::Resource] The SNS resource client def initialize(sns_resource) @sns_resource = sns_resource @logger = Logger.new($stdout) end # Sets a policy on a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource to include in the policy # @param policy_name [String] The name of the policy attribute to set def enable_resource(topic_arn, resource_arn, policy_name) policy = generate_policy(topic_arn, resource_arn) topic = @sns_resource.topic(topic_arn) topic.set_attributes({ attribute_name: policy_name, attribute_value: policy }) Actions 763 Amazon Simple Notification Service Developer Guide @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.") rescue Aws::SNS::Errors::ServiceError => e @logger.error("Failed to set policy: #{e.message}") end private # Generates a policy string with dynamic resource ARNs # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { Version: '2008-10-17', Id: '__default_policy_ID', Statement: [{ Sid:
|
sns-dg-202
|
sns-dg.pdf
| 202 |
The name of the policy attribute to set def enable_resource(topic_arn, resource_arn, policy_name) policy = generate_policy(topic_arn, resource_arn) topic = @sns_resource.topic(topic_arn) topic.set_attributes({ attribute_name: policy_name, attribute_value: policy }) Actions 763 Amazon Simple Notification Service Developer Guide @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.") rescue Aws::SNS::Errors::ServiceError => e @logger.error("Failed to set policy: #{e.message}") end private # Generates a policy string with dynamic resource ARNs # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { Version: '2008-10-17', Id: '__default_policy_ID', Statement: [{ Sid: '__default_statement_ID', Effect: 'Allow', Principal: { "AWS": '*' }, Action: ['SNS:Publish'], Resource: topic_arn, Condition: { ArnEquals: { "AWS:SourceArn": resource_arn } } }] }.to_json end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = 'MY_TOPIC_ARN' # Should be replaced with a real topic ARN resource_arn = 'MY_RESOURCE_ARN' # Should be replaced with a real resource ARN policy_name = 'POLICY_NAME' # Typically, this is "Policy" sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) enabler.enable_resource(topic_arn, resource_arn, policy_name) end Actions 764 Amazon Simple Notification Service Developer Guide • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see SetTopicAttributes in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->settopicattributes( iv_topicarn = iv_topic_arn iv_attributename = iv_attribute_name iv_attributevalue = iv_attribute_value ). MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see SetTopicAttributes in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use Subscribe with an AWS SDK or CLI The following code examples show how to use Subscribe. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Create and publish to a FIFO topic Actions 765 Amazon Simple Notification Service • Publish messages to queues .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. /// <summary> /// Creates a new subscription to a topic. /// </summary> /// <param name="client">The initialized Amazon SNS client object, used /// to create an Amazon SNS subscription.</param> /// <param name="topicArn">The ARN of the topic to subscribe to.</param> /// <returns>A SubscribeResponse object which includes the subscription /// ARN for the new subscription.</returns> public static async Task<SubscribeResponse> TopicSubscribeAsync( IAmazonSimpleNotificationService client, string topicArn) { SubscribeRequest request = new SubscribeRequest() { TopicArn = topicArn, ReturnSubscriptionArn = true, Protocol = "email", Endpoint = "recipient@example.com", }; var response = await client.SubscribeAsync(request); return response; } Actions 766 Amazon Simple Notification Service Developer Guide Subscribe a queue to a topic with optional filters. /// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; } var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; } • For API details, see Subscribe in AWS SDK for .NET API Reference. Actions 767 Amazon Simple Notification Service Developer Guide C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an email address. /*! \param topicARN: An SNS topic Amazon Resource Name (ARN). \param emailAddress: An email address. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN, const Aws::String &emailAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("email"); request.SetEndpoint(emailAddress); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() Actions 768 Amazon Simple Notification Service Developer Guide << std::endl; } return outcome.IsSuccess(); } Subscribe a mobile application to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app. /*! \param topicARN:
|
sns-dg-203
|
sns-dg.pdf
| 203 |
\return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN, const Aws::String &emailAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("email"); request.SetEndpoint(emailAddress); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() Actions 768 Amazon Simple Notification Service Developer Guide << std::endl; } return outcome.IsSuccess(); } Subscribe a mobile application to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param endpointARN: The ARN for a mobile app or device endpoint. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeApp(const Aws::String &topicARN, const Aws::String &endpointARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("application"); request.SetEndpoint(endpointARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } Actions 769 Amazon Simple Notification Service Developer Guide return outcome.IsSuccess(); } Subscribe a Lambda function to a topic. //! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); Actions 770 Amazon Simple Notification Service Developer Guide } Subscribe an SQS queue to a topic. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } Actions 771 Amazon Simple Notification Service Developer Guide Subscribe with a filter to a topic. static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/ sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. Actions 772 Amazon Simple Notification Service Developer Guide if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, Actions 773 Amazon Simple Notification Service Developer Guide sqsClient); return false; } //! Routine that lets the user select attributes for a subscription filter policy. /*! \sa getFilterPolicyFromUser() \return Aws::String: The filter policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() { std::cout << "You can filter messages by one or more of the following \"" << TONE_ATTRIBUTE << "\" attributes." << std::endl; std::vector<Aws::String> filterSelections; int selection; do { for (size_t j = 0; j < TONES.size(); ++j) { std::cout << " " << (j +
|
sns-dg-204
|
sns-dg.pdf
| 204 |
} else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, Actions 773 Amazon Simple Notification Service Developer Guide sqsClient); return false; } //! Routine that lets the user select attributes for a subscription filter policy. /*! \sa getFilterPolicyFromUser() \return Aws::String: The filter policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() { std::cout << "You can filter messages by one or more of the following \"" << TONE_ATTRIBUTE << "\" attributes." << std::endl; std::vector<Aws::String> filterSelections; int selection; do { for (size_t j = 0; j < TONES.size(); ++j) { std::cout << " " << (j + 1) << ". " << TONES[j] << std::endl; } selection = askQuestionForIntRange( "Enter a number (or enter zero to stop adding more). ", 0, static_cast<int>(TONES.size())); if (selection != 0) { const Aws::String &selectedTone(TONES[selection - 1]); // Add the tone to the selection if it is not already added. if (std::find(filterSelections.begin(), filterSelections.end(), selectedTone) == filterSelections.end()) { filterSelections.push_back(selectedTone); } } } while (selection != 0); Aws::String result; if (!filterSelections.empty()) { std::ostringstream jsonPolicyStream; jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": ["; Actions 774 Amazon Simple Notification Service Developer Guide for (size_t j = 0; j < filterSelections.size(); ++j) { jsonPolicyStream << "\"" << filterSelections[j] << "\""; if (j < filterSelections.size() - 1) { jsonPolicyStream << ","; } } jsonPolicyStream << "] }"; result = jsonPolicyStream.str(); } return result; } • For API details, see Subscribe in AWS SDK for C++ API Reference. CLI AWS CLI To subscribe to a topic The following subscribe command subscribes an email address to the specified topic. aws sns subscribe \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ --protocol email \ --notification-endpoint my-email@example.com Output: { "SubscriptionArn": "pending confirmation" } • For API details, see Subscribe in AWS CLI Command Reference. Actions 775 Amazon Simple Notification Service Developer Guide Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe a queue to a topic with optional filters. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { Actions 776 Amazon Simple Notification Service Developer Guide filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err } • For API details, see Subscribe in AWS SDK for Go API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; Actions 777 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeEmail { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String email = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subEmail(snsClient, topicArn, email); snsClient.close(); } public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) Actions 778 Amazon Simple Notification Service Developer Guide .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe an HTTP endpoint to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage:
|
sns-dg-205
|
sns-dg.pdf
| 205 |
Simple Notification Service Developer Guide .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe an HTTP endpoint to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <url> Where: topicArn - The ARN of the topic to subscribe. Actions 779 Amazon Simple Notification Service Developer Guide url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Subscribe a Lambda function to a topic. Actions 780 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } Actions 781 Amazon Simple Notification Service Developer Guide public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see Subscribe in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. Actions 782 Amazon Simple Notification Service Developer Guide export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } }; Subscribe a mobile application to a topic. Actions 783 Amazon Simple Notification Service Developer Guide import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe a Lambda function to a topic. import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** Actions 784 Amazon Simple Notification Service Developer Guide * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async (
|
sns-dg-206
|
sns-dg.pdf
| 206 |
}), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe a Lambda function to a topic. import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** Actions 784 Amazon Simple Notification Service Developer Guide * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; }; Subscribe an SQS queue to a topic. import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Actions 785 Amazon Simple Notification Service Developer Guide Protocol: "sqs", Endpoint: queueArn, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue- test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; Subscribe with a filter to a topic. import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueueFiltered = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the 'event' attribute set to 'order_placed'. FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ event: ["order_placed"], }), Actions 786 Amazon Simple Notification Service Developer Guide }, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue- test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Subscribe in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. suspend fun subEmail( topicArnVal: String, email: String, ): String { val request = Actions 787 Amazon Simple Notification Service Developer Guide SubscribeRequest { protocol = "email" endpoint = email returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) return result.subscriptionArn.toString() } } Subscribe a Lambda function to a topic. suspend fun subLambda( topicArnVal: String?, lambdaArn: String?, ) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } } • For API details, see Subscribe in AWS SDK for Kotlin API reference. Actions 788 Amazon Simple Notification Service Developer Guide PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'email'; $endpoint = 'sample@example.com'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, Actions 789 Amazon Simple Notification Service Developer Guide ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Subscribe an HTTP endpoint to a topic. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'https'; $endpoint = 'https://'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); Actions 790 Amazon Simple Notification Service Developer Guide var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } •
|
sns-dg-207
|
sns-dg.pdf
| 207 |
'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $protocol = 'https'; $endpoint = 'https://'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); Actions 790 Amazon Simple Notification Service Developer Guide var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } • For API details, see Subscribe in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def subscribe(topic, protocol, endpoint): """ Subscribes an endpoint to the topic. Some endpoint types, such as email, must be confirmed before their subscriptions are active. When a subscription is not confirmed, its Amazon Resource Number (ARN) is set to 'PendingConfirmation'. :param topic: The topic to subscribe to. Actions 791 Amazon Simple Notification Service Developer Guide :param protocol: The protocol of the endpoint, such as 'sms' or 'email'. :param endpoint: The endpoint that receives messages, such as a phone number (in E.164 format) for SMS messages, or an email address for email messages. :return: The newly added subscription. """ try: subscription = topic.subscribe( Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True ) logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn) except ClientError: logger.exception( "Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn ) raise else: return subscription • For API details, see Subscribe in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. require 'aws-sdk-sns' require 'logger' Actions 792 Amazon Simple Notification Service Developer Guide # Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS) class SubscriptionService # Initializes the SubscriptionService with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Attempts to create a subscription to a topic # # @param topic_arn [String] The ARN of the SNS topic # @param protocol [String] The subscription protocol (e.g., email) # @param endpoint [String] The endpoint that receives the notifications (email address) # @return [Boolean] true if subscription was successfully created, false otherwise def create_subscription(topic_arn, protocol, endpoint) @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) @logger.info('Subscription created successfully.') true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while creating the subscription: #{e.message}") false end end # Main execution if the script is run directly if $PROGRAM_NAME == __FILE__ protocol = 'email' endpoint = 'EMAIL_ADDRESS' # Should be replaced with a real email address topic_arn = 'TOPIC_ARN' # Should be replaced with a real topic ARN sns_client = Aws::SNS::Client.new subscription_service = SubscriptionService.new(sns_client) @logger.info('Creating the subscription.') unless subscription_service.create_subscription(topic_arn, protocol, endpoint) @logger.error('Subscription creation failed. Stopping program.') exit 1 end Actions 793 Amazon Simple Notification Service Developer Guide end • For more information, see AWS SDK for Ruby Developer Guide. • For API details, see Subscribe in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; Actions 794 Amazon Simple Notification Service Developer Guide println!("Published message: {:?}", rsp); Ok(()) } • For API details, see Subscribe in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. TRY. oo_result = lo_sns->subscribe( "oo_result is returned for testing purposes." iv_topicarn = iv_topic_arn iv_protocol = 'email' iv_endpoint = iv_email_address iv_returnsubscriptionarn = abap_true ). MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. • For API details, see Subscribe in AWS SDK for SAP ABAP API reference. Actions 795 Amazon Simple Notification
|
sns-dg-208
|
sns-dg.pdf
| 208 |
and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. TRY. oo_result = lo_sns->subscribe( "oo_result is returned for testing purposes." iv_topicarn = iv_topic_arn iv_protocol = 'email' iv_endpoint = iv_email_address iv_returnsubscriptionarn = abap_true ). MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. • For API details, see Subscribe in AWS SDK for SAP ABAP API reference. Actions 795 Amazon Simple Notification Service Developer Guide Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Subscribe an email address to a topic. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.subscribe( input: SubscribeInput( endpoint: email, protocol: "email", returnSubscriptionArn: true, topicArn: arn ) ) guard let subscriptionArn = output.subscriptionArn else { print("No subscription ARN received from Amazon SNS.") return } print("Subscription \(subscriptionArn) created.") Subscribe a phone number to a topic to receive notifications by SMS. import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) let output = try await snsClient.subscribe( Actions 796 Amazon Simple Notification Service Developer Guide input: SubscribeInput( endpoint: phone, protocol: "sms", returnSubscriptionArn: true, topicArn: arn ) ) guard let subscriptionArn = output.subscriptionArn else { print("No subscription ARN received from Amazon SNS.") return } print("Subscription \(subscriptionArn) created.") • For API details, see Subscribe in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use TagResource with an AWS SDK or CLI The following code examples show how to use TagResource. CLI AWS CLI To add a tag to a topic The following tag-resource example adds a metadata tag to the specified Amazon SNS topic. aws sns tag-resource \ --resource-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --tags Key=Team,Value=Alpha This command produces no output. • For API details, see TagResource in AWS CLI Command Reference. Actions 797 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.Tag; import software.amazon.awssdk.services.sns.model.TagResourceRequest; import java.util.ArrayList; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class AddTags { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to which tags are added. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Actions 798 Amazon Simple Notification Service Developer Guide String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); addTopicTags(snsClient, topicArn); snsClient.close(); } public static void addTopicTags(SnsClient snsClient, String topicArn) { try { Tag tag = Tag.builder() .key("Team") .value("Development") .build(); Tag tag2 = Tag.builder() .key("Environment") .value("Gamma") .build(); List<Tag> tagList = new ArrayList<>(); tagList.add(tag); tagList.add(tag2); TagResourceRequest tagResourceRequest = TagResourceRequest.builder() .resourceArn(topicArn) .tags(tagList) .build(); snsClient.tagResource(tagResourceRequest); System.out.println("Tags have been added to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see TagResource in AWS SDK for Java 2.x API Reference. Actions 799 Amazon Simple Notification Service Developer Guide Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun addTopicTags(topicArn: String) { val tag = Tag { key = "Team" value = "Development" } val tag2 = Tag { key = "Environment" value = "Gamma" } val tagList = mutableListOf<Tag>() tagList.add(tag) tagList.add(tag2) val request = TagResourceRequest { resourceArn = topicArn tags = tagList } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.tagResource(request) println("Tags have been added to $topicArn") } } • For API details, see TagResource in AWS SDK for Kotlin API reference. Actions 800 Amazon Simple Notification Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use Unsubscribe with an AWS SDK or CLI The following code examples show how to use Unsubscribe. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find
|
sns-dg-209
|
sns-dg.pdf
| 209 |
Actions 800 Amazon Simple Notification Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use Unsubscribe with an AWS SDK or CLI The following code examples show how to use Unsubscribe. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Unsubscribe from a topic by a subscription ARN. /// <summary> /// Unsubscribe from a topic by a subscription ARN. /// </summary> /// <param name="subscriptionArn">The ARN of the subscription.</param> /// <returns>True if successful.</returns> public async Task<bool> UnsubscribeByArn(string subscriptionArn) { var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync( new UnsubscribeRequest() { SubscriptionArn = subscriptionArn }); return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK; } Actions 801 Amazon Simple Notification Service Developer Guide • For API details, see Unsubscribe in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. //! Delete a subscription to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param subscriptionARN: The Amazon Resource Name (ARN) for an Amazon SNS topic subscription. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::unsubscribe(const Aws::String &subscriptionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::UnsubscribeRequest request; request.SetSubscriptionArn(subscriptionARN); const Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request); if (outcome.IsSuccess()) { std::cout << "Unsubscribed successfully " << std::endl; } else { std::cerr << "Error while unsubscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } Actions 802 Amazon Simple Notification Service Developer Guide • For API details, see Unsubscribe in AWS SDK for C++ API Reference. CLI AWS CLI To unsubscribe from a topic The following unsubscribe example deletes the specified subscription from a topic. aws sns unsubscribe \ --subscription-arn arn:aws:sns:us-west-2:0123456789012:my- topic:8a21d249-4329-4871-acc6-7be709c6ea7f This command produces no output. • For API details, see Unsubscribe in AWS CLI Command Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: Actions 803 Amazon Simple Notification Service Developer Guide * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class Unsubscribe { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of the subscription to delete. """; if (args.length < 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); unSub(snsClient, subscriptionArn); snsClient.close(); } public static void unSub(SnsClient snsClient, String subscriptionArn) { try { UnsubscribeRequest request = UnsubscribeRequest.builder() .subscriptionArn(subscriptionArn) .build(); UnsubscribeResponse result = snsClient.unsubscribe(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription was removed for " + request.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } Actions 804 Amazon Simple Notification Service Developer Guide } } • For API details, see Unsubscribe in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create the client in a separate module and export it. import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({}); Import the SDK and client modules and call the API. import { UnsubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} subscriptionArn - The ARN of the subscription to cancel. */ const unsubscribe = async ( subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx- xxxx-xxxx-xxxxxxxxxxxx", ) => { const response = await snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn, Actions 805 Amazon Simple Notification Service Developer Guide }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0178259a-9204-507c-b620-78a7570a44c6', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Unsubscribe in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun unSub(subscriptionArnVal: String) { val request = UnsubscribeRequest { subscriptionArn =
|
sns-dg-210
|
sns-dg.pdf
| 210 |
Notification Service Developer Guide }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0178259a-9204-507c-b620-78a7570a44c6', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see Unsubscribe in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun unSub(subscriptionArnVal: String) { val request = UnsubscribeRequest { subscriptionArn = subscriptionArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.unsubscribe(request) println("Subscription was removed for ${request.subscriptionArn}") } } Actions 806 Amazon Simple Notification Service Developer Guide • For API details, see Unsubscribe in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Deletes a subscription to an Amazon SNS topic. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $subscription = 'arn:aws:sns:us-east-1:111122223333:MySubscription'; try { $result = $SnSclient->unsubscribe([ 'SubscriptionArn' => $subscription, ]); var_dump($result); } catch (AwsException $e) { Actions 807 Amazon Simple Notification Service Developer Guide // output error message if fails error_log($e->getMessage()); } • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Unsubscribe in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def delete_subscription(subscription): """ Unsubscribes and deletes a subscription. """ try: subscription.delete() logger.info("Deleted subscription %s.", subscription.arn) except ClientError: logger.exception("Couldn't delete subscription %s.", subscription.arn) raise Actions 808 Amazon Simple Notification Service Developer Guide • For API details, see Unsubscribe in AWS SDK for Python (Boto3) API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. lo_sns->unsubscribe( iv_subscriptionarn = iv_subscription_arn ). MESSAGE 'Subscription deleted.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Subscription does not exist.' TYPE 'E'. CATCH /aws1/cx_snsinvalidparameterex. MESSAGE 'Subscription with "PendingConfirmation" status cannot be deleted/unsubscribed. Confirm subscription before performing unsubscribe operation.' TYPE 'E'. ENDTRY. • For API details, see Unsubscribe in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 809 Amazon Simple Notification Service Developer Guide import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.unsubscribe( input: UnsubscribeInput( subscriptionArn: arn ) ) print("Unsubscribed.") • For API details, see Unsubscribe in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Scenarios for Amazon SNS using AWS SDKs The following code examples show you how to implement common scenarios in Amazon SNS with AWS SDKs. These scenarios show you how to accomplish specific tasks by calling multiple functions within Amazon SNS or combined with other AWS services. Each scenario includes a link to the complete source code, where you can find instructions on how to set up and run the code. Scenarios target an intermediate level of experience to help you understand service actions in context. Examples • Build an application to submit data to a DynamoDB table • Build a publish and subscription application that translates messages • Create a platform endpoint for Amazon SNS push notifications using an AWS SDK • Create a photo asset management application that lets users manage photos using labels • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK Scenarios 810 Amazon Simple Notification Service Developer Guide • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Publish SMS messages to an Amazon SNS topic using an AWS SDK • Publish a large message to Amazon SNS with Amazon S3 using an AWS SDK • Publish an Amazon SNS SMS text message using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK • Use API Gateway to invoke a Lambda
|
sns-dg-211
|
sns-dg.pdf
| 211 |
explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK Scenarios 810 Amazon Simple Notification Service Developer Guide • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Publish SMS messages to an Amazon SNS topic using an AWS SDK • Publish a large message to Amazon SNS with Amazon S3 using an AWS SDK • Publish an Amazon SNS SMS text message using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK • Use API Gateway to invoke a Lambda function • Use scheduled events to invoke a Lambda function Build an application to submit data to a DynamoDB table The following code examples show how to build an application that submits data to an Amazon DynamoDB table and notifies you when a user updates the table. Java SDK for Java 2.x Shows how to create a dynamic web application that submits data using the Amazon DynamoDB Java API and sends a text message using the Amazon Simple Notification Service Java API. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • DynamoDB • Amazon SNS JavaScript SDK for JavaScript (v3) This example shows how to build an app that enables users to submit data to an Amazon DynamoDB table, and send a text message to the administrator using Amazon Simple Notification Service (Amazon SNS). For complete source code and instructions on how to set up and run, see the full example on GitHub. Build an app to submit data to a DynamoDB table 811 Amazon Simple Notification Service Developer Guide This example is also available in the AWS SDK for JavaScript v3 developer guide. Services used in this example • DynamoDB • Amazon SNS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Build a publish and subscription application that translates messages The following code examples show how to create an application that has subscription and publish functionality and translates messages. .NET SDK for .NET Shows how to use the Amazon Simple Notification Service .NET API to create a web application that has subscription and publish functionality. In addition, this example application also translates messages. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon SNS • Amazon Translate Java SDK for Java 2.x Shows how to use the Amazon Simple Notification Service Java API to create a web application that has subscription and publish functionality. In addition, this example application also translates messages. Building an Amazon SNS application 812 Amazon Simple Notification Service Developer Guide For complete source code and instructions on how to set up and run, see the full example on GitHub. For complete source code and instructions on how to set up and run the example that uses the Java Async API, see the full example on GitHub. Services used in this example • Amazon SNS • Amazon Translate Kotlin SDK for Kotlin Shows how to use the Amazon SNS Kotlin API to create an application that has subscription and publish functionality. In addition, this example application also translates messages. For complete source code and instructions on how to create a web app, see the full example on GitHub. For complete source code and instructions on how to create a native Android app, see the full example on GitHub. Services used in this example • Amazon SNS • Amazon Translate For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create a platform endpoint for Amazon SNS push notifications using an AWS SDK The following code examples show how to create a platform endpoint for Amazon SNS push notifications. Create a platform endpoint for push notifications 813 Amazon Simple Notification Service Developer Guide CLI AWS CLI To create a platform application endpoint The following create-platform-endpoint example creates an endpoint for the specified platform application using the specified token. aws sns create-platform-endpoint \ --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/ MyApplication \ --token EXAMPLE12345... Output: { "EndpointArn": "arn:aws:sns:us-west-2:1234567890:endpoint/GCM/ MyApplication/12345678-abcd-9012-efgh-345678901234" } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * Create a platform endpoint
|
sns-dg-212
|
sns-dg.pdf
| 212 |
CLI To create a platform application endpoint The following create-platform-endpoint example creates an endpoint for the specified platform application using the specified token. aws sns create-platform-endpoint \ --platform-application-arn arn:aws:sns:us-west-2:123456789012:app/GCM/ MyApplication \ --token EXAMPLE12345... Output: { "EndpointArn": "arn:aws:sns:us-west-2:1234567890:endpoint/GCM/ MyApplication/12345678-abcd-9012-efgh-345678901234" } Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * Create a platform endpoint for push notifications 814 Amazon Simple Notification Service Developer Guide * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * * In addition, create a platform application using the AWS Management Console. * See this doc topic: * * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html * * Without the values created by following the previous link, this code examples * does not work. */ public class RegistrationExample { public static void main(String[] args) { final String usage = """ Usage: <token> <platformApplicationArn> Where: token - The device token or registration ID of the mobile device. This is a unique identifier provided by the device platform (e.g., Apple Push Notification Service (APNS) for iOS devices, Firebase Cloud Messaging (FCM) for Android devices) when the mobile app is registered to receive push notifications. platformApplicationArn - The ARN value of platform application. You can get this value from the AWS Management Console.\s """; if (args.length != 2) { System.out.println(usage); return; } String token = args[0]; String platformApplicationArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); Create a platform endpoint for push notifications 815 Amazon Simple Notification Service Developer Guide createEndpoint(snsClient, token, platformApplicationArn); } public static void createEndpoint(SnsClient snsClient, String token, String platformApplicationArn) { System.out.println("Creating platform endpoint with token " + token); try { CreatePlatformEndpointRequest endpointRequest = CreatePlatformEndpointRequest.builder() .token(token) .platformApplicationArn(platformApplicationArn) .build(); CreatePlatformEndpointResponse response = snsClient.createPlatformEndpoint(endpointRequest); System.out.println("The ARN of the endpoint is " + response.endpointArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); } } } For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create a photo asset management application that lets users manage photos using labels The following code examples show how to create a serverless application that lets users manage photos using labels. .NET SDK for .NET Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. Create a serverless application to manage photos 816 Amazon Simple Notification Service Developer Guide For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS C++ SDK for C++ Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS Create a serverless application to manage photos 817 Amazon Simple Notification Service Developer Guide Java SDK for Java 2.x Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS JavaScript SDK for JavaScript (v3) Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition Create a serverless application to manage photos 818 Amazon Simple Notification Service Developer Guide • Amazon S3 • Amazon SNS Kotlin SDK for Kotlin Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition
|
sns-dg-213
|
sns-dg.pdf
| 213 |
using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition Create a serverless application to manage photos 818 Amazon Simple Notification Service Developer Guide • Amazon S3 • Amazon SNS Kotlin SDK for Kotlin Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS PHP SDK for PHP Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway Create a serverless application to manage photos 819 Amazon Simple Notification Service Developer Guide • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS Rust SDK for Rust Shows how to develop a photo asset management application that detects labels in images using Amazon Rekognition and stores them for later retrieval. For complete source code and instructions on how to set up and run, see the full example on GitHub. For a deep dive into the origin of this example see the post on AWS Community. Services used in this example • API Gateway • DynamoDB • Lambda • Amazon Rekognition • Amazon S3 • Amazon SNS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create an Amazon Textract explorer application The following code examples show how to explore Amazon Textract output through an interactive application. Create an Amazon Textract explorer application 820 Amazon Simple Notification Service JavaScript SDK for JavaScript (v3) Developer Guide Shows how to use the AWS SDK for JavaScript to build a React application that uses Amazon Textract to extract data from a document image and display it in an interactive web page. This example runs in a web browser and requires an authenticated Amazon Cognito identity for credentials. It uses Amazon Simple Storage Service (Amazon S3) for storage, and for notifications it polls an Amazon Simple Queue Service (Amazon SQS) queue that is subscribed to an Amazon Simple Notification Service (Amazon SNS) topic. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract Python SDK for Python (Boto3) Shows how to use the AWS SDK for Python (Boto3) with Amazon Textract to detect text, form, and table elements in a document image. The input image and Amazon Textract output are shown in a Tkinter application that lets you explore the detected elements. • Submit a document image to Amazon Textract and explore the output of detected elements. • Submit images directly to Amazon Textract or through an Amazon Simple Storage Service (Amazon S3) bucket. • Use asynchronous APIs to start a job that publishes a notification to an Amazon Simple Notification Service (Amazon SNS) topic when the job completes. • Poll an Amazon Simple Queue Service (Amazon SQS) queue for a job completion message and display the results. Create an Amazon Textract explorer application 821 Amazon Simple Notification Service Developer Guide For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create and publish to a FIFO Amazon SNS topic using an AWS SDK The following code examples show how to create and publish to a FIFO Amazon SNS topic. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up
|
sns-dg-214
|
sns-dg.pdf
| 214 |
example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create and publish to a FIFO Amazon SNS topic using an AWS SDK The following code examples show how to create and publish to a FIFO Amazon SNS topic. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. This example • creates an Amazon SNS FIFO topic, two Amazon SQS FIFO queues, and one Standard queue. • subscribes the queues to the topic and publishes a message to the topic. The test verifies the receipt of the message to each queue. The complete example also shows the addition of access policies and deletes the resources at the end. public class PriceUpdateExample { public final static SnsClient snsClient = SnsClient.create(); Create and publish to a FIFO topic 822 Amazon Simple Notification Service Developer Guide public final static SqsClient sqsClient = SqsClient.create(); public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" + "Where:\n" + " fifoTopicName - The name of the FIFO topic that you want to create. \n\n" + " wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n" + " retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" + " analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n"; if (args.length != 4) { System.out.println(usage); System.exit(1); } final String fifoTopicName = args[0]; final String wholeSaleQueueName = args[1]; final String retailQueueName = args[2]; final String analyticsQueueName = args[3]; // For convenience, the QueueData class holds metadata about a queue: ARN, URL, // name and type. List<QueueData> queues = List.of( new QueueData(wholeSaleQueueName, QueueType.FIFO), new QueueData(retailQueueName, QueueType.FIFO), new QueueData(analyticsQueueName, QueueType.Standard)); // Create queues. createQueues(queues); // Create a topic. String topicARN = createFIFOTopic(fifoTopicName); // Subscribe each queue to the topic. subscribeQueues(queues, topicARN); Create and publish to a FIFO topic 823 Amazon Simple Notification Service Developer Guide // Allow the newly created topic to send messages to the queues. addAccessPolicyToQueuesFINAL(queues, topicARN); // Publish a sample price update message with payload. publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables"); // Clean up resources. deleteSubscriptions(queues); deleteQueues(queues); deleteTopic(topicARN); } public static String createFIFOTopic(String topicName) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = Map.of( "FifoTopic", "true", "ContentBasedDeduplication", "false", "FifoThroughputScope", "MessageGroup"); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); String topicArn = response.topicArn(); System.out.println("The topic ARN is" + topicArn); return topicArn; } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void subscribeQueues(List<QueueData> queues, String topicARN) { queues.forEach(queue -> { SubscribeRequest subscribeRequest = SubscribeRequest.builder() .topicArn(topicARN) Create and publish to a FIFO topic 824 Amazon Simple Notification Service Developer Guide .endpoint(queue.queueARN) .protocol("sqs") .build(); // Subscribe to the endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); }); } public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue = "wholesale"; MessageAttributeValue msgAttValue = MessageAttributeValue.builder() .dataType("String") .stringValue(attributeValue) .build(); Map<String, MessageAttributeValue> attributes = new HashMap<>(); attributes.put(attributeName, msgAttValue); PublishRequest pubRequest = PublishRequest.builder() .topicArn(topicArn) .subject(subject) .message(payload) .messageGroupId(groupId) .messageDeduplicationId(dedupId) .messageAttributes(attributes) .build(); final PublishResponse response = snsClient.publish(pubRequest); System.out.println(response.messageId()); Create and publish to a FIFO topic 825 Amazon Simple Notification Service Developer Guide System.out.println(response.sequenceNumber()); System.out.println("Message was published to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateTopic • Publish • Subscribe Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SNS FIFO topic, subscribe Amazon SQS FIFO and standard queues to the topic, and publish a message to the topic. def usage_demo(): """Shows how to subscribe queues to a FIFO topic.""" print("-" * 88) print("Welcome to the `Subscribe queues to a FIFO topic` demo!") print("-" * 88) sns = boto3.resource("sns") sqs = boto3.resource("sqs") fifo_topic_wrapper = FifoTopicWrapper(sns) sns_wrapper = SnsWrapper(sns) prefix = "sqs-subscribe-demo-" Create and publish to a FIFO topic
|
sns-dg-215
|
sns-dg.pdf
| 215 |
Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SNS FIFO topic, subscribe Amazon SQS FIFO and standard queues to the topic, and publish a message to the topic. def usage_demo(): """Shows how to subscribe queues to a FIFO topic.""" print("-" * 88) print("Welcome to the `Subscribe queues to a FIFO topic` demo!") print("-" * 88) sns = boto3.resource("sns") sqs = boto3.resource("sqs") fifo_topic_wrapper = FifoTopicWrapper(sns) sns_wrapper = SnsWrapper(sns) prefix = "sqs-subscribe-demo-" Create and publish to a FIFO topic 826 Amazon Simple Notification Service Developer Guide queues = set() subscriptions = set() wholesale_queue = sqs.create_queue( QueueName=prefix + "wholesale.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(wholesale_queue) print(f"Created FIFO queue with URL: {wholesale_queue.url}.") retail_queue = sqs.create_queue( QueueName=prefix + "retail.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(retail_queue) print(f"Created FIFO queue with URL: {retail_queue.url}.") analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={}) queues.add(analytics_queue) print(f"Created standard queue with URL: {analytics_queue.url}.") topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo") print(f"Created FIFO topic: {topic.attributes['TopicArn']}.") for q in queues: fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"]) print(f"Added access policies for topic: {topic.attributes['TopicArn']}.") for q in queues: sub = fifo_topic_wrapper.subscribe_queue_to_topic( Create and publish to a FIFO topic 827 Amazon Simple Notification Service Developer Guide topic, q.attributes["QueueArn"] ) subscriptions.add(sub) print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.") input("Press Enter to publish a message to the topic.") message_id = fifo_topic_wrapper.publish_price_update( topic, '{"product": 214, "price": 79.99}', "Consumables" ) print(f"Published price update with message ID: {message_id}.") # Clean up the subscriptions, queues, and topic. input("Press Enter to clean up resources.") for s in subscriptions: sns_wrapper.delete_subscription(s) sns_wrapper.delete_topic(topic) for q in queues: fifo_topic_wrapper.delete_queue(q) print(f"Deleted subscriptions, queues, and topic.") print("Thanks for watching!") print("-" * 88) class FifoTopicWrapper: """Encapsulates Amazon SNS FIFO topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_fifo_topic(self, topic_name): """ Create a FIFO topic. Create and publish to a FIFO topic 828 Amazon Simple Notification Service Developer Guide Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long. For a FIFO topic, the name must end with the .fifo suffix. :param topic_name: The name for the topic. :return: The new topic. """ try: topic = self.sns_resource.create_topic( Name=topic_name, Attributes={ "FifoTopic": str(True), "ContentBasedDeduplication": str(False), "FifoThroughputScope": "MessageGroup", }, ) logger.info("Created FIFO topic with name=%s.", topic_name) return topic except ClientError as error: logger.exception("Couldn't create topic with name=%s!", topic_name) raise error @staticmethod def add_access_policy(queue, topic_arn): """ Add the necessary access policy to a queue, so it can receive messages from a topic. :param queue: The queue resource. :param topic_arn: The ARN of the topic. :return: None. """ try: queue.set_attributes( Attributes={ "Policy": json.dumps( { "Version": "2012-10-17", "Statement": [ { "Sid": "test-sid", Create and publish to a FIFO topic 829 Amazon Simple Notification Service Developer Guide "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "SQS:SendMessage", "Resource": queue.attributes["QueueArn"], "Condition": { "ArnLike": {"aws:SourceArn": topic_arn} }, } ], } ) } ) logger.info("Added trust policy to the queue.") except ClientError as error: logger.exception("Couldn't add trust policy to the queue!") raise error @staticmethod def subscribe_queue_to_topic(topic, queue_arn): """ Subscribe a queue to a topic. :param topic: The topic resource. :param queue_arn: The ARN of the queue. :return: The subscription resource. """ try: subscription = topic.subscribe( Protocol="sqs", Endpoint=queue_arn, ) logger.info("The queue is subscribed to the topic.") return subscription except ClientError as error: logger.exception("Couldn't subscribe queue to topic!") raise error @staticmethod def publish_price_update(topic, payload, group_id): """ Compose and publish a message that updates the wholesale price. Create and publish to a FIFO topic 830 Amazon Simple Notification Service Developer Guide :param topic: The topic to publish to. :param payload: The message to publish. :param group_id: The group ID for the message. :return: The ID of the message. """ try: att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}} dedup_id = uuid.uuid4() response = topic.publish( Subject="Price Update", Message=payload, MessageAttributes=att_dict, MessageGroupId=group_id, MessageDeduplicationId=str(dedup_id), ) message_id = response["MessageId"] logger.info("Published message to topic %s.", topic.arn) except ClientError as error: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise error return message_id @staticmethod def delete_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: queue.delete() logger.info("Deleted queue with URL=%s.", queue.url) except ClientError as error: logger.exception("Couldn't delete queue with URL=%s!", queue.url) raise error Create and publish to a FIFO topic 831 Amazon Simple Notification Service Developer Guide • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateTopic • Publish • Subscribe SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples
|
sns-dg-216
|
sns-dg.pdf
| 216 |
60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: queue.delete() logger.info("Deleted queue with URL=%s.", queue.url) except ClientError as error: logger.exception("Couldn't delete queue with URL=%s!", queue.url) raise error Create and publish to a FIFO topic 831 Amazon Simple Notification Service Developer Guide • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateTopic • Publish • Subscribe SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a FIFO topic, subscribe an Amazon SQS FIFO queue to the topic, and publish a message to an Amazon SNS topic. " Creates a FIFO topic. " DATA lt_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>tt_topicattributesmap. DATA ls_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>ts_topicattributesmap_maprow. ls_tpc_attributes-key = 'FifoTopic'. ls_tpc_attributes-value = NEW /aws1/cl_snstopicattrsmap_w( iv_value = 'true' ). INSERT ls_tpc_attributes INTO TABLE lt_tpc_attributes. TRY. DATA(lo_create_result) = lo_sns->createtopic( iv_name = iv_topic_name it_attributes = lt_tpc_attributes ). DATA(lv_topic_arn) = lo_create_result->get_topicarn( ). ov_topic_arn = lv_topic_arn. " ov_topic_arn is returned for testing purposes. " MESSAGE 'FIFO topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. Create and publish to a FIFO topic 832 Amazon Simple Notification Service Developer Guide MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY. " Subscribes an endpoint to an Amazon Simple Notification Service (Amazon SNS) topic. " " Only Amazon Simple Queue Service (Amazon SQS) FIFO queues can be subscribed to an SNS FIFO topic. " TRY. DATA(lo_subscribe_result) = lo_sns->subscribe( iv_topicarn = lv_topic_arn iv_protocol = 'sqs' iv_endpoint = iv_queue_arn ). DATA(lv_subscription_arn) = lo_subscribe_result->get_subscriptionarn( ). ov_subscription_arn = lv_subscription_arn. " ov_subscription_arn is returned for testing purposes. " MESSAGE 'SQS queue was subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. " Publish message to SNS topic. " TRY. DATA lt_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>tt_messageattributemap. DATA ls_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>ts_messageattributemap_maprow. ls_msg_attributes-key = 'Importance'. ls_msg_attributes-value = NEW /aws1/cl_snsmessageattrvalue( iv_datatype = 'String' iv_stringvalue = 'High' ). INSERT ls_msg_attributes INTO TABLE lt_msg_attributes. DATA(lo_result) = lo_sns->publish( iv_topicarn = lv_topic_arn iv_message = 'The price of your mobile plan has been increased from $19 to $23' iv_subject = 'Changes to mobile plan' iv_messagegroupid = 'Update-2' iv_messagededuplicationid = 'Update-2.1' Create and publish to a FIFO topic 833 Amazon Simple Notification Service Developer Guide it_messageattributes = lt_msg_attributes ). ov_message_id = lo_result->get_messageid( ). " ov_message_id is returned for testing purposes. " MESSAGE 'Message was published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. • For API details, see the following topics in AWS SDK for SAP ABAP API reference. • CreateTopic • Publish • Subscribe For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Detect people and objects in a video with Amazon Rekognition using an AWS SDK The following code examples show how to detect people and objects in a video with Amazon Rekognition. Java SDK for Java 2.x Shows how to use Amazon Rekognition Java API to create an app to detect faces and objects in videos located in an Amazon Simple Storage Service (Amazon S3) bucket. The app sends the admin an email notification with the results using Amazon Simple Email Service (Amazon SES). For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition Detect people and objects in a video 834 Amazon Simple Notification Service Developer Guide • Amazon S3 • Amazon SES • Amazon SNS • Amazon SQS Python SDK for Python (Boto3) Use Amazon Rekognition to detect faces, objects, and people in videos by starting asynchronous detection jobs. This example also configures Amazon Rekognition to notify an Amazon Simple Notification Service (Amazon SNS) topic when jobs complete and subscribes an Amazon Simple Queue Service (Amazon SQS) queue to the topic. When the queue receives a message about a job, the job is retrieved and the results are output. This example is best viewed on GitHub. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition • Amazon S3 • Amazon SES • Amazon SNS • Amazon SQS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish SMS messages to an Amazon SNS topic using an AWS SDK The following code example shows
|
sns-dg-217
|
sns-dg.pdf
| 217 |
results are output. This example is best viewed on GitHub. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition • Amazon S3 • Amazon SES • Amazon SNS • Amazon SQS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish SMS messages to an Amazon SNS topic using an AWS SDK The following code example shows how to: • Create an Amazon SNS topic. • Subscribe phone numbers to the topic. Publish SMS messages to a topic 835 Amazon Simple Notification Service Developer Guide • Publish SMS messages to the topic so that all subscribed phone numbers receive the message at once. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a topic and return its ARN. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; Publish SMS messages to a topic 836 Amazon Simple Notification Service Developer Guide if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } Subscribe an endpoint to a topic. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; Publish SMS messages to a topic 837 Amazon Simple Notification Service /** Developer Guide * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SubscribeTextSMS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <phoneNumber> Where: topicArn - The ARN of the topic to subscribe. phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100). """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subTextSNS(snsClient, topicArn, phoneNumber); snsClient.close(); } public static void subTextSNS(SnsClient snsClient, String topicArn, String phoneNumber) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("sms") .endpoint(phoneNumber) .returnSubscriptionArn(true) .topicArn(topicArn) Publish SMS messages to a topic 838 Amazon Simple Notification Service Developer Guide .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Set attributes on the message, such as the ID of the sender, the maximum price, and its type. Message attributes are optional. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); Publish SMS messages to a topic 839 Amazon Simple Notification Service Developer Guide setSNSAttributes(snsClient, attributes); snsClient.close(); } public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Publish a message to a topic. The message is sent to every subscriber. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTextSMS { Publish SMS messages to a topic 840 Amazon Simple Notification Service Developer Guide public static void main(String[] args) { final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length
|
sns-dg-218
|
sns-dg.pdf
| 218 |
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTextSMS { Publish SMS messages to a topic 840 Amazon Simple Notification Service Developer Guide public static void main(String[] args) { final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Publish SMS messages to a topic 841 Amazon Simple Notification Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish a large message to Amazon SNS with Amazon S3 using an AWS SDK The following code example shows how to publish a large message to Amazon SNS using Amazon S3 to store the message payload. Java SDK for Java 1.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. To publish a large message, use the Amazon SNS Extended Client Library for Java. The message that you send references an Amazon S3 object containing the actual message content. import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient; import com.amazon.sqs.javamessaging.ExtendedClientConfiguration; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.amazonaws.services.sns.model.CreateTopicRequest; import com.amazonaws.services.sns.model.PublishRequest; import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest; import com.amazonaws.services.sns.util.Topics; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; Publish a large message 842 Amazon Simple Notification Service Developer Guide import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import software.amazon.sns.AmazonSNSExtendedClient; import software.amazon.sns.SNSExtendedClientConfiguration; public class Example { public static void main(String[] args) { final String BUCKET_NAME = "extended-client-bucket"; final String TOPIC_NAME = "extended-client-topic"; final String QUEUE_NAME = "extended-client-queue"; final Regions region = Regions.DEFAULT_REGION; // Message threshold controls the maximum message size that will be allowed to // be published // through SNS using the extended client. Payload of messages exceeding this // value will be stored in // S3. The default value of this parameter is 256 KB which is the maximum // message size in SNS (and SQS). final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32; // Initialize SNS, SQS and S3 clients final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build(); final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build(); final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build(); // Create bucket, topic, queue and subscription s3Client.createBucket(BUCKET_NAME); final String topicArn = snsClient.createTopic( new CreateTopicRequest().withName(TOPIC_NAME)).getTopicArn(); final String queueUrl = sqsClient.createQueue( new CreateQueueRequest().withQueueName(QUEUE_NAME)).getQueueUrl(); final String subscriptionArn = Topics.subscribeQueue( snsClient, sqsClient, topicArn, queueUrl); Publish a large message 843 Amazon Simple Notification Service Developer Guide // To read message content stored in S3 transparently through SQS extended // client, // set the RawMessageDelivery subscription attribute to TRUE final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest(); subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn); subscriptionAttributesRequest.setAttributeName("RawMessageDelivery"); subscriptionAttributesRequest.setAttributeValue("TRUE"); snsClient.setSubscriptionAttributes(subscriptionAttributesRequest); // Initialize SNS extended client // PayloadSizeThreshold triggers message content storage in S3 when the // threshold is exceeded // To store all messages content in S3, use AlwaysThroughS3 flag final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration() .withPayloadSupportEnabled(s3Client, BUCKET_NAME) .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD); final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient, snsExtendedClientConfiguration); // Publish message via SNS with storage in S3 final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above."; snsExtendedClient.publish(topicArn, message); // Initialize SQS extended client final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration() .withPayloadSupportEnabled(s3Client, BUCKET_NAME); final AmazonSQSExtendedClient sqsExtendedClient = new AmazonSQSExtendedClient(sqsClient, sqsExtendedClientConfiguration); // Read the message from the queue Publish a large message 844 Amazon Simple Notification Service Developer Guide final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl); System.out.println("Received message is " + result.getMessages().get(0).getBody()); } } For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish an Amazon SNS SMS text message using an AWS SDK The following code examples show how to publish SMS messages using Amazon SNS. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. namespace SNSMessageExample { using System; using System.Threading.Tasks; using Amazon; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; public class SNSMessage { private AmazonSimpleNotificationServiceClient snsClient; /// <summary> /// Initializes a new instance of the <see cref="SNSMessage"/> class. /// Constructs a new SNSMessage object initializing the Amazon Simple Publish an
|
sns-dg-219
|
sns-dg.pdf
| 219 |
details about previous SDK versions. Publish an Amazon SNS SMS text message using an AWS SDK The following code examples show how to publish SMS messages using Amazon SNS. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. namespace SNSMessageExample { using System; using System.Threading.Tasks; using Amazon; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; public class SNSMessage { private AmazonSimpleNotificationServiceClient snsClient; /// <summary> /// Initializes a new instance of the <see cref="SNSMessage"/> class. /// Constructs a new SNSMessage object initializing the Amazon Simple Publish an SMS text message 845 Amazon Simple Notification Service Developer Guide /// Notification Service (Amazon SNS) client using the supplied /// Region endpoint. /// </summary> /// <param name="regionEndpoint">The Amazon Region endpoint to use in /// sending test messages with this object.</param> public SNSMessage(RegionEndpoint regionEndpoint) { snsClient = new AmazonSimpleNotificationServiceClient(regionEndpoint); } /// <summary> /// Sends the SMS message passed in the text parameter to the phone number /// in phoneNum. /// </summary> /// <param name="phoneNum">The ten-digit phone number to which the text /// message will be sent.</param> /// <param name="text">The text of the message to send.</param> /// <returns>Async task.</returns> public async Task SendTextMessageAsync(string phoneNum, string text) { if (string.IsNullOrEmpty(phoneNum) || string.IsNullOrEmpty(text)) { return; } // Now actually send the message. var request = new PublishRequest { Message = text, PhoneNumber = phoneNum, }; try { var response = await snsClient.PublishAsync(request); } catch (Exception ex) { Console.WriteLine($"Error sending message: {ex}"); } } } Publish an SMS text message 846 Amazon Simple Notification Service Developer Guide } • For API details, see Publish in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /** * Publish SMS: use Amazon Simple Notification Service (Amazon SNS) to send an SMS text message to a phone number. * Note: This requires additional AWS configuration prior to running example. * * NOTE: When you start using Amazon SNS to send SMS messages, your AWS account is in the SMS sandbox and you can only * use verified destination phone numbers. See https://docs.aws.amazon.com/sns/ latest/dg/sns-sms-sandbox.html. * NOTE: If destination is in the US, you also have an additional restriction that you have use a dedicated * origination ID (phone number). You can request an origination number using Amazon Pinpoint for a fee. * See https://aws.amazon.com/blogs/compute/provisioning-and-using-10dlc- origination-numbers-with-amazon-sns/ * for more information. * * <phone_number_value> input parameter uses E.164 format. * For example, in United States, this input value should be of the form: +12223334444 */ //! Send an SMS text message to a phone number. /*! \param message: The message to publish. \param phoneNumber: The phone number of the recipient in E.164 format. Publish an SMS text message 847 Amazon Simple Notification Service Developer Guide \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishSms(const Aws::String &message, const Aws::String &phoneNumber, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetPhoneNumber(phoneNumber); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with message id, '" << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see Publish in AWS SDK for C++ API Reference. Java SDK for Java 2.x Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Publish an SMS text message 848 Amazon Simple Notification Service Developer Guide import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html */ public class PublishTextSMS { public static void main(String[] args) { final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { Publish an SMS text message 849 Amazon Simple Notification Service try { Developer Guide PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see Publish in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up
|
sns-dg-220
|
sns-dg.pdf
| 220 |
SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { Publish an SMS text message 849 Amazon Simple Notification Service try { Developer Guide PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see Publish in AWS SDK for Java 2.x API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun pubTextSMS( messageVal: String?, phoneNumberVal: String?, ) { val request = PublishRequest { message = messageVal phoneNumber = phoneNumberVal } SnsClient { region = "us-east-1" }.use { snsClient -> Publish an SMS text message 850 Amazon Simple Notification Service Developer Guide val result = snsClient.publish(request) println("${result.messageId} message sent.") } } • For API details, see Publish in AWS SDK for Kotlin API reference. PHP SDK for PHP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Sends a text message (SMS message) directly to a phone number using Amazon SNS. * * This code expects that you have AWS credentials set up per: * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/ guide_credentials.html */ $SnSclient = new SnsClient([ 'profile' => 'default', 'region' => 'us-east-1', 'version' => '2010-03-31' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $phone = '+1XXX5550100'; Publish an SMS text message 851 Amazon Simple Notification Service try { $result = $SnSclient->publish([ 'Message' => $message, 'PhoneNumber' => $phone, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); } Developer Guide • For more information, see AWS SDK for PHP Developer Guide. • For API details, see Publish in AWS SDK for PHP API Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def publish_text_message(self, phone_number, message): """ Publishes a text message directly to a phone number without need for a subscription. Publish an SMS text message 852 Amazon Simple Notification Service Developer Guide :param phone_number: The phone number that receives the message. This must be in E.164 format. For example, a United States phone number might be +12065550101. :param message: The message to send. :return: The ID of the message. """ try: response = self.sns_resource.meta.client.publish( PhoneNumber=phone_number, Message=message ) message_id = response["MessageId"] logger.info("Published message to %s.", phone_number) except ClientError: logger.exception("Couldn't publish message to %s.", phone_number) raise else: return message_id • For API details, see Publish in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SNS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK The following code examples show how to: • Create topic (FIFO or non-FIFO). • Subscribe several queues to the topic with an option to apply a filter. • Publish messages to the topic. • Poll the queues for messages received. Publish messages to queues 853 Amazon Simple Notification Service Developer Guide .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario at a command prompt. /// <summary> /// Console application to run a feature scenario for topics and queues. /// </summary> public static class TopicsAndQueues { private static bool _useFifoTopic = false; private static bool _useContentBasedDeduplication = false; private static string _topicName = null!; private static string _topicArn = null!; private static readonly int _queueCount = 2; private static readonly string[] _queueUrls = new string[_queueCount]; private static readonly string[] _subscriptionArns = new string[_queueCount]; private static readonly string[] _tones = { "cheerful", "funny", "serious", "sincere" }; public static SNSWrapper SnsWrapper { get; set; } = null!; public static SQSWrapper SqsWrapper { get; set; } = null!; public static bool UseConsole { get; set; } = true; static async Task Main(string[] args) { // Set up dependency injection for Amazon EventBridge. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonSQS>() .AddAWSService<IAmazonSimpleNotificationService>() Publish messages to queues 854 Amazon Simple Notification Service Developer Guide .AddTransient<SNSWrapper>() .AddTransient<SQSWrapper>() ) .Build(); ServicesSetup(host); PrintDescription(); await RunScenario(); } /// <summary> /// Populate the services for use within the console application. /// </summary> ///
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.