View a markdown version of this page

管理 Amazon SNS 电话号码和订阅 - Amazon Simple Notification Service

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

管理 Amazon SNS 电话号码和订阅

Amazon SNS 提供了多个用于管理账户 SMS 消息接收者的选项。您可以选择加入已选择不接收 SMS 消息的电话号码。但是,您只能在有限的频率下执行此操作。

要停止向 SMS 订阅发送消息,请删除订阅或向其发布的主题。

退出接收 SMS 消息

如果当地法律和法规有要求(例如美国和加拿大),SMS 收件人可以使用自己的设备,通过向该消息回复以下内容来表示退出:

  • ARRET(法语)

  • CANCEL

  • END

  • OPT-OUT

  • OPTOUT

  • QUIT

  • REMOVE

  • STOP

  • TD

  • UNSUBSCRIBE

要退出,收件人必须回复 Amazon SNS 用于传输消息的相同发起号码。选择退出后,收件人将不再收到您的短信。 AWS 账户除非您选择加入电话号码,否则这适用。

如果该电话号码订阅了 Amazon SNS 主题,则选择退出不会取消订阅。但是,除非您选择加入该电话号码,否则短信无法发送到该订阅中。

使用 Amazon SNS 控制台管理手机号码和订阅

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

Opting-in 已选择退出亚马逊 SNS 控制台的电话号码

您可以查看哪些电话号码选择不从您的账户接收短信。您也可以选择加入这些电话号码,继续向他们发送消息。

对于每个电话号码,您只能每隔 30 天重新加入一次。

  1. 登录 Amazon SNS 控制台。

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

  3. 在导航面板上,选择文本消息(SMS)。

  4. 在移动短信 (SMS) 页面的Opted-out 电话号码部分,该页面显示已选择退出的电话号码。

  5. 选中您想要加入的电话号码的复选框,然后选择选择加入。该电话号码不再选择退出,它会接收您发送给该号码的 SMS 消息。

在 Amazon SNS 控制台中删除短信订阅

删除 SMS 订阅可停止在您发布至主题时向该电话号码发送 SMS 消息。

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

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

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

在 Amazon SNS 控制台中删除主题

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

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

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

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

使用管理电话号码和订阅 AWS SDK

您可以使用软件开发工具包向亚马逊 AWS SNS 发出编程请求。您可以管理哪些电话号码可以从您的账户接收 SMS 消息。

要使用 S AWS DK,必须使用您的证书对其进行配置。有关更多信息,请参阅 AWS 开发工具包和工具参考指南中的共享配置和凭证文件。

使用查看所有选择退出的电话号码 AWS SDK

要查看所有已退出的电话号码,请使用 Amazon SNS API 提交 ListPhoneNumbersOptedOut 请求。

以下代码示例显示了如何使用ListPhoneNumbersOptedOut。

CLI
AWS CLI

列出 SMS 消息退出

以下 list-phone-numbers-opted-out 示例将列出退出 SMS 消息接收的电话号码。

aws sns list-phone-numbers-opted-out

输出:

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

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

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
适用于 PHP 的 SDK
注意

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

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

使用检查电话号码是否已选择退出 AWS SDK

要检查电话号码是否退出,请使用 Amazon SNS API 提交 CheckIfPhoneNumberIsOptedOut 请求。

以下代码示例显示了如何使用CheckIfPhoneNumberIsOptedOut。

.NET
适用于 .NET 的 SDK
注意

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

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
AWS CLI

检查电话号码的 SMS 消息退出

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

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

输出:

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

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

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
适用于 JavaScript (v3) 的软件开发工具包
注意

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

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

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
适用于 PHP 的 SDK
注意

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

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

Opting-in 已使用亚马逊 SNS API 选择退出的电话号码

要选择加入电话号码,请使用 Amazon SNS API 提交 OptInPhoneNumber 请求。

对于每个电话号码,您只能每隔 30 天重新加入一次。

使用删除短信订阅 AWS SDK

要从亚马逊 SNS 主题中删除短信订阅,请使用亚马逊 SNS API 提交ListSubscriptions请求来获取订阅 ARN。然后将 ARN 传递给Unsubscribe请求。

以下代码示例显示了如何使用Unsubscribe。

.NET
适用于 .NET 的 SDK
注意

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

通过订阅 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 详细信息,请参阅《适用于 .NET 的 AWS SDK API Reference》中的 Unsubscribe。

C++
SDK for C++
注意

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

//! 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 详细信息,请参阅《适用于 C++ 的 AWS SDK API Reference》中的 Unsubscribe。

CLI
AWS CLI

从主题取消订阅

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

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

此命令不生成任何输出。

  • 有关 API 详细信息,请参阅《AWS CLI Command Reference》中的 Unsubscribe。

Java
适用于 Java 的 SDK 2.x
注意

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

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 详细信息,请参阅《AWS SDK for Java 2.x API Reference》中的 Unsubscribe。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

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

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

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
适用于 Kotlin 的 SDK
注意

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

suspend fun unSub(subscriptionArnVal: String) { val request = UnsubscribeRequest { subscriptionArn = subscriptionArnVal } SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient -> snsClient.unsubscribe(request) println("Subscription was removed for ${request.subscriptionArn}") } }
  • 有关 API 详细信息,请参阅《AWS SDK for Kotlin API Reference》中的 Unsubscribe。

PHP
适用于 PHP 的 SDK
注意

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

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

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

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
class SnsWrapper: """Wrapper class for managing Amazon SNS operations.""" def __init__(self, sns_client: Any) -> None: """ Initialize the SnsWrapper. :param sns_client: A Boto3 Amazon SNS client. """ self.sns_client = sns_client @classmethod def from_client(cls) -> 'SnsWrapper': """ Create an SnsWrapper instance using a default boto3 client. :return: An instance of this class. """ sns_client = boto3.client('sns') return cls(sns_client) def unsubscribe(self, subscription_arn: str) -> bool: """ Unsubscribe from an SNS topic. :param subscription_arn: The ARN of the subscription to remove. :return: True if successful. :raises ClientError: If the unsubscribe operation fails. """ try: self.sns_client.unsubscribe(SubscriptionArn=subscription_arn) logger.info(f"Unsubscribed: {subscription_arn}") return True except ClientError as e: error_code = e.response.get('Error', {}).get('Code', 'Unknown') if error_code == 'NotFound': logger.warning(f"Subscription not found: {subscription_arn}") return True # Already unsubscribed else: logger.error(f"Error unsubscribing: {error_code} - {e}") raise
  • 有关 API 详细信息,请参阅《AWS SDK for Python (Boto3) API Reference》中的 Unsubscribe。

SAP ABAP
适用于 SAP ABAP 的 SDK
注意

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

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.
  • 有关 API 详细信息,请参阅《AWS SDK for SAP ABAP API Reference》中的 Unsubscribe。

Swift
适用于 Swift 的 SDK
注意

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

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.")
  • 有关 API 详细信息,请参阅《AWS SDK for Swift API Reference》中的 Unsubscribe。

使用删除主题 AWS SDK

要删除一个主题及其所有订阅,请通过使用 Amazon SNS API 提交ListTopics请求来获取该主题 ARN。然后将 ARN 传递给DeleteTopic请求。

以下代码示例显示了如何使用DeleteTopic。

.NET
适用于 .NET 的 SDK
注意

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

按主题 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 的详细信息,请参阅 适用于 .NET 的 AWS SDK API 参考DeleteTopic中的。

C++
SDK for C++
注意

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

//! 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 的详细信息,请参阅 适用于 C++ 的 AWS SDK API 参考DeleteTopic中的。

CLI
AWS CLI

删除 SNS 主题

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

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

此命令不生成任何输出。

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

Go
适用于 Go 的 SDK V2
注意

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

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 } // 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 }
  • 有关 API 的详细信息,请参阅 适用于 Go 的 AWS SDK API 参考DeleteTopic中的。

Java
适用于 Java 的 SDK 2.x
注意

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

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 的详细信息,请参阅 AWS SDK for Java 2.x API 参考DeleteTopic中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

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

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

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
适用于 Kotlin 的 SDK
注意

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

suspend fun deleteSNSTopic(topicArnVal: String) { val request = DeleteTopicRequest { topicArn = topicArnVal } SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient -> snsClient.deleteTopic(request) println("$topicArnVal was successfully deleted.") } }
  • 有关 API 的详细信息,请参阅适用DeleteTopic于 Kotlin 的 AWS SDK API 参考文档。

PHP
适用于 PHP 的 SDK
注意

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

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 的详细信息,请参阅 适用于 PHP 的 AWS SDK API 参考DeleteTopic中的。

Python
适用于 Python 的 SDK(Boto3)
注意

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

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
class SnsWrapper: """Wrapper class for managing Amazon SNS operations.""" def __init__(self, sns_client: Any) -> None: """ Initialize the SnsWrapper. :param sns_client: A Boto3 Amazon SNS client. """ self.sns_client = sns_client @classmethod def from_client(cls) -> 'SnsWrapper': """ Create an SnsWrapper instance using a default boto3 client. :return: An instance of this class. """ sns_client = boto3.client('sns') return cls(sns_client) def delete_topic(self, topic_arn: str) -> bool: """ Delete an SNS topic. :param topic_arn: The ARN of the topic to delete. :return: True if successful. :raises ClientError: If the topic deletion fails. """ try: self.sns_client.delete_topic(TopicArn=topic_arn) logger.info(f"Deleted topic: {topic_arn}") return True except ClientError as e: error_code = e.response.get('Error', {}).get('Code', 'Unknown') if error_code == 'NotFound': logger.warning(f"Topic not found: {topic_arn}") return True # Already deleted else: logger.error(f"Error deleting topic: {error_code} - {e}") raise
  • 有关 API 的详细信息,请参阅 Python AWS 开发工具包 (Boto3) API 参考DeleteTopic中的内容。

SAP ABAP
适用于 SAP ABAP 的 SDK
注意

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

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 的详细信息,请参阅AWS 适用DeleteTopic于 SAP 的 SDK ABAP API 参考文档。

Swift
适用于 Swift 的 SDK
注意

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

import AWSSNS let config = try await SNSClient.SNSClientConfiguration(region: region) let snsClient = SNSClient(config: config) _ = try await snsClient.deleteTopic( input: DeleteTopicInput(topicArn: arn) )
  • 有关 API 的详细信息,请参阅 DeleteTopic Swift AWS 开发工具包 API 参考文档。