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

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

管理电话号码和 SMS 订阅

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. 在导航面板上,选择 Text messaging (SMS) (文本消息(SMS))

  4. Text messaging (SMS) (文本消息(SMS)) 页面上,选择 View opted out phone numbers (查看已退出的电话号码)Opted out phone numbers 页面将显示已退出的电话号码。

  5. 选中您想要重新加入的电话号码的复选框,然后选择 Opt in。电话号码将不再处于退出状态,并将接收您发送的 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 开发工具包)

您可以使用 Amazon 开发工具包向 Amazon SNS 提交编程请求,并管理哪些电话号码可以从您的账户收到 SMS 消息。

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

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

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

以下代码示例演示了如何列出选择不接收 Amazon SNS 消息的电话号码。

CLI
Amazon CLI

列出 SMS 消息退出

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

aws sns list-phone-numbers-opted-out

输出:

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

还有更多相关信息 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
适用于 PHP 的 SDK
注意

还有更多相关信息 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 SNS API 提交 CheckIfPhoneNumberIsOptedOut 请求。

以下代码示例演示如何检查电话号码是否退出接收 Amazon SNS 消息。

.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
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 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
适用于 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
适用于 PHP 的 SDK
注意

还有更多相关信息 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 订阅

要从 Amazon SNS 主题删除 SMS 订阅,请使用 Amazon SNS API 提交 ListSubscriptions 请求来获取订阅 ARN,然后将该 ARN 传递给 Unsubscribe 请求。

以下代码示例显示如何删除 Amazon SNS 订阅。

.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 参考》中的 Unsubscribe

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 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 参考》中的 Unsubscribe

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 Command Reference》中的 Unsubscribe

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

还有更多相关信息 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 参考》中的 Unsubscribe

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

还有更多相关信息 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}") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Unsubscribe

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 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
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 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
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 Unsubscribe

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

删除主题

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

以下代码示例显示如何删除 Amazon SNS 主题以及该主题的所有订阅。

.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 .NETAPI 参考DeleteTopic中的。

C++
适用于 C++ 的 SDK
注意

还有更多相关信息 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
适用于 Go V2 的 SDK
注意

还有更多相关信息 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 GoAPI 参考DeleteTopic中的。

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

还有更多相关信息 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.xAPI 参考DeleteTopic中的。

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

还有更多相关信息 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于 K otlin 的 Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 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 PHPAPI 参考DeleteTopic中的。

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

还有更多相关信息 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 的详细信息,请参阅适用DeleteTopicPython 的 Amazon SDK (Boto3) API 参考

SAP ABAP
SDK for 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于 S AP 的 Amazon SDK ABAP API 参考