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

管理电话号码和 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. 在导航面板中,选择订阅

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

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

删除主题

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

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

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

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

管理手机号码和订阅(Amazon 开发工具包)

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

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

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

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

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

Java
SDK for Java 2.x

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); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 ListPhoneNumbersOptedOut

PHP
SDK for PHP

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

/// <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}"); } }
Java
SDK for Java 2.x

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 for JavaScript V3

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

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import {CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { phoneNumber: "353861230764" }; //PHONE_NUMBER, in the E.164 phone number structure const run = async () => { try { const data = await snsClient.send( new CheckIfPhoneNumberIsOptedOutCommand(params) ); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
PHP
SDK for PHP

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

C++
SDK for C++

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String subscription_arn = argv[1]; Aws::SNS::Model::UnsubscribeRequest s_req; s_req.SetSubscriptionArn(subscription_arn); auto s_out = sns.Unsubscribe(s_req); if (s_out.IsSuccess()) { std::cout << "Unsubscribed successfully " << std::endl; } else { std::cout << "Error while unsubscribing " << s_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考 中的 Unsubscribe

Java
SDK for Java 2.x

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); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考 中的 Unsubscribe

JavaScript
SDK for JavaScript V3

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

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入开发工具包和客户端模块,然后调用 API。

// Import required AWS SDK clients and commands for Node.js import {UnsubscribeCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { SubscriptionArn: "TOPIC_SUBSCRIPTION_ARN" }; //TOPIC_SUBSCRIPTION_ARN const run = async () => { try { const data = await snsClient.send(new UnsubscribeCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

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}") } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 Unsubscribe

PHP
SDK for PHP

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

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 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
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Python (Boto3) API 参考中的 Unsubscribe

删除主题

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

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

.NET
Amazon SDK for .NET

/// <summary> /// This example deletes an existing Amazon Simple Notification Service /// (Amazon SNS) topic. The example was created using the AWS SDK for .NET /// version 3.7 and .NET Core 5.0. /// </summary> public class DeleteSNSTopic { public static async Task Main() { string topicArn = "arn:aws:sns:us-east-2:704825161248:ExampleSNSTopic"; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var response = await client.DeleteTopicAsync(topicArn); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 DeleteTopic

C++
SDK for C++

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String topic_arn = argv[1]; Aws::SNS::SNSClient sns; Aws::SNS::Model::DeleteTopicRequest dt_req; dt_req.SetTopicArn(topic_arn); auto dt_out = sns.DeleteTopic(dt_req); if (dt_out.IsSuccess()) { std::cout << "Successfully deleted topic " << topic_arn << std::endl; } else { std::cout << "Error deleting topic " << topic_arn << ":" << dt_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 DeleteTopic

Java
SDK for Java 2.x

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); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 DeleteTopic

JavaScript
SDK for JavaScript V3

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

import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };

导入开发工具包和客户端模块,然后调用 API。

// Load the AWS SDK for Node.js // Import required AWS SDK clients and commands for Node.js import {DeleteTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { TopicArn: "TOPIC_ARN" }; //TOPIC_ARN const run = async () => { try { const data = await snsClient.send(new DeleteTopicCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

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.") } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 DeleteTopic

PHP
SDK for PHP

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Deletes a 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()); }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 DeleteTopic

Python
SDK for Python (Boto3)

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 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
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Python (Boto3) API 参考中的 DeleteTopic