在 Amazon 中管理电话号码和SMS订阅 SNS - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在 Amazon 中管理电话号码和SMS订阅 SNS

Amazon SNS 提供了多种选项来管理谁从您的账户接收SMS消息。在有限的频率下,您可以选择加入已选择不接收来自您帐户的SMS消息的电话号码。要停止向SMS订阅发送消息,您可以删除订阅或向其发布的主题。

选择不接收消息 SMS

在当地法律和法规(例如美国和加拿大)要求的情况下,SMS收件人可以通过回复邮件并提供以下任何一项来使用其设备选择退出:

  • ARRET(法语)

  • CANCEL

  • END

  • OPT-OUT

  • OPTOUT

  • QUIT

  • REMOVE

  • STOP

  • TD

  • UNSUBSCRIBE

要选择退出,收件人必须回复与 Amazon 发送邮件时SNS使用的相同发件号。选择退出后, Amazon Web Services 账户 除非您选择使用电话号码,否则收件人将不再收到您发送的SMS消息。

如果电话号码订阅了某个 Amazon SNS 主题,则选择退出不会删除订阅,但除非您选择加入电话号码,否则SMS消息将无法发送到该订阅。

管理电话号码和订阅(控制台)

您可以使用 Amazon SNS 控制台控制哪些电话号码接收来自您账户的SMS消息。

选择已选择退出的电话号码

您可以查看哪些电话号码已选择不接收来自您帐户的SMS消息,也可以选择加入这些电话号码以继续向他们发送消息。

您只能每 30 天选择一次电话号码。

  1. 登录 Amazon SNS 控制台

  2. 在控制台菜单中,将区域选择器设置为支持消息SMS传递的区域

  3. 在导航面板上,选择短信 (SMS)

  4. 在 “移动短信” (SMS) 页面的 “已选择退出的电话号码” 部分中,将显示已选择退出的电话号码。

  5. 选中您要选择加入的电话号码对应的复选框,然后选择加入。该电话号码不再选择退出,并且会收到您向其发送的SMS消息。

删除订SMS阅

删除订SMS阅,以便在发布主题时停止向该电话号码发送SMS消息。

  1. 在导航面板中,选择 Subscriptions(订阅)。

  2. 选中要删除的订阅的复选框。然后选择 Actions,再选择 Delete Subscriptions

  3. Delete(删除)窗口中,选择 Delete(删除)。Amazon SNS 删除订阅并显示成功消息。

删除主题

当您不想再向其订阅终端节点发布消息时,可删除主题。

  1. 在导航面板上,选择 Topics(主题)。

  2. 选中要删除的主题的复选框。然后选择 Actions,再选择 Delete Topics

  3. Delete(删除)窗口中,选择 Delete(删除)。Amazon SNS 删除该主题并显示成功消息。

管理电话号码和订阅 (Amazon SDKs)

您可以使用向 Amazon 发出编程请求,SNS并管理哪些电话号码可以从您的账户接收SMS消息。 Amazon SDKs

要使用 Amazon SDK,必须使用您的凭据对其进行配置。有关更多信息,请参阅工具参考指南中的共享配置Amazon SDKs和凭据文件

查看所有已选择退出的电话号码

要查看所有已选择退出的电话号码,请向 Amazon 提交ListPhoneNumbersOptedOut申请。SNS API

以下代码示例演示如何使用 ListPhoneNumbersOptedOut

CLI
Amazon CLI

列出退出SMS留言

以下list-phone-numbers-opted-out示例列出了选择不接收SMS消息的电话号码。

aws sns list-phone-numbers-opted-out

输出:

{ "phoneNumbers": [ "+15555550100" ] }
Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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; /** * 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); } } }
PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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()); }

检查电话号码是否已选择退出

要查看电话号码是否已选择退出,请向 Amazon 提交CheckIfPhoneNumberIsOptedOut申请。SNS API

以下代码示例演示如何使用 CheckIfPhoneNumberIsOptedOut

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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. /// </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}"); } } }
CLI
Amazon CLI

要查看SMS留言,请选择退出电话号码

以下check-if-phone-number-is-opted-out示例检查指定的电话号码是否已选择不接收来自当前 Amazon 账户的SMS消息。

aws sns check-if-phone-number-is-opted-out \ --phone-number +1555550100

输出:

{ "isOptedOut": false }
Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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: * * 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()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

在单独的模块中创建客户端并将其导出。

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({});

导入SDK和客户端模块并调用API。

import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", ) => { 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; };
PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * 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()); }

选择已选择退出的电话号码

要选择加入电话号码,请向 Amazon SNS API 提交OptInPhoneNumber申请。

您只能每 30 天选择一次电话号码。

删除订SMS阅

要从亚马逊SNS主题中删除SMS订阅,请ARN通过向亚马逊提交ListSubscriptions请求来获取订阅 SNSAPI,然后将其传递ARN给一个Unsubscribe请求。

以下代码示例演示如何使用 Unsubscribe

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

通过订阅取消订阅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; }
  • 有关API详细信息,请参阅 “Amazon SDK for .NET API参考资料” 中的 “取消订阅”。

C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

//! 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(); }
  • 有关API详细信息,请参阅 “Amazon SDK for C++ API参考资料” 中的 “取消订阅”。

CLI
Amazon CLI

从主题取消订阅

以下 unsubscribe 示例将从主题删除指定的订阅。

aws sns unsubscribe \ --subscription-arn arn:aws:sns:us-west-2:0123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f

此命令不生成任何输出。

  • 有关API详细信息,请参阅《Amazon CLI 命令参考》中的 “取消订阅”。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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. """; 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); } } }
  • 有关API详细信息,请参阅 “Amazon SDK for Java 2.x API参考资料” 中的 “取消订阅”。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

在单独的模块中创建客户端并将其导出。

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({});

导入SDK和客户端模块并调用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', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };
Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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}") } }
PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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()); }
Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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
SAP ABAP
SDK对于 SAP ABAP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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.

删除主题

要删除主题及其所有订阅,请向 Amazon ARN 提交ListTopics请求以获取该主题 SNSAPI,然后将其传递ARN给该DeleteTopic请求。

以下代码示例演示如何使用 DeleteTopic

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

按主题删除主题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; }
  • 有关API详细信息,请参阅 “Amazon SDK for .NET API参考 DeleteTopic” 中的。

C++
SDK对于 C++
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

//! 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(); }
  • 有关API详细信息,请参阅 “Amazon SDK for C++ API参考 DeleteTopic” 中的。

CLI
Amazon CLI

删除SNS主题

以下delete-topic示例删除了指定的SNS主题。

aws sns delete-topic \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"

此命令不生成任何输出。

  • 有关API详细信息,请参阅Amazon CLI 命令参考DeleteTopic中的。

Go
SDK适用于 Go V2
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// 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(topicArn string) error { _, err := actor.SnsClient.DeleteTopic(context.TODO(), &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 }
  • 有关API详细信息,请参阅 “Amazon SDK for Go API参考 DeleteTopic” 中的。

Java
SDK适用于 Java 2.x
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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. * * 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); } } }
  • 有关API详细信息,请参阅 “Amazon SDK for Java 2.x API参考 DeleteTopic” 中的。

JavaScript
SDK对于 JavaScript (v3)
注意

还有更多相关信息 GitHub。查找完整示例,了解如何在 Amazon 代码示例存储库中进行设置和运行。

在单独的模块中创建客户端并将其导出。

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({});

导入SDK和客户端模块并调用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); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } };
Kotlin
SDK对于 Kotlin 来说
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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.") } }
  • 有关API详细信息,请参阅DeleteTopic中的 Kotlin Amazon SDK API 参考

PHP
SDK for PHP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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()); }
  • 有关API详细信息,请参阅 “Amazon SDK for PHP API参考 DeleteTopic” 中的。

Python
SDK适用于 Python (Boto3)
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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
  • 有关API详细信息,请参阅DeleteTopic中的 Amazon SDKPython (Boto3) API 参考。

SAP ABAP
SDK对于 SAP ABAP
注意

还有更多相关信息 GitHub。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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.
  • 有关API详细信息,请参阅DeleteTopic中的Amazon SDK以供SAPABAPAPI参考