電話番号および SMS サブスクリプションを管理する - Amazon Simple Notification Service

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

電話番号および SMS サブスクリプションを管理する

Amazon SNS には、アカウントから SMS メッセージを受信するユーザーを管理するためのオプションが複数用意されています。制限された頻度で、アカウントからの SMS メッセージの受信をオプトアウトした電話番号をオプトインできます。SMS サブスクリプションへのメッセージの送信を停止するために、それらに発行されるサブスクリプションやトピックを削除できます。

SMS メッセージの受信をオプトアウトする

現地の法律および規制により義務付けられている場合 (米国およびカナダなど)、SMS の受信者は、デバイスを利用して以下のいずれかのメッセージに返信することによって、オプトアウトできます。

  • ARRET (フランス語)

  • CANCEL

  • END

  • OPT-OUT

  • OPTOUT

  • QUIT

  • REMOVE

  • STOP

  • TD

  • UNSUBSCRIBE

オプトアウトするには、受信者はAmazon SNS がメッセージの配信に使用したものと同じ送信元番号に返信する必要があります。オプトアウトすると、電話番号をオプトイン AWS アカウント しない限り、受信者は から配信された SMS メッセージを受信しなくなります。

電話番号が Amazon SNS トピックにサブスクライブされると、オプトアウトはサブスクリプションを削除しませんが、電話番号をオプトインしない限り、SMS メッセージは、サブスクリプションへ送信できません。

電話番号とサブスクリプション (コンソール) を管理する

Amazon SNS コンソールを使用して、アカウントで SMS メッセージを受信する電話番号を管理できます。

オプトアウトされた電話番号をオプトインする

ユーザーのアカウントからの SMS メッセージの受信をオプトアウトした電話番号を表示し、これらの電話番号をオプトインしてメッセージの送信を再開することができます。

30 日に 1 回のみ、電話番号をオプトインできます。

  1. Amazon SNS コンソールにサインインします。

  2. コンソールメニューで、SMS メッセージングをサポートしているリージョンにリージョンセレクタを設定します。

  3. ナビゲーションパネルで、[テキストメッセージング (SMS)] を選択します。

  4. [テキストメッセージング (SMS)] ページで、[オプトアウトされた電話番号を表示] を選択します。[Opted out phone numbers] ページは、オプトアウトされた電話番号を表示します。

  5. オプトインする電話番号のチェックボックスをオンにして、[オプトイン] を選択します。電話番号はオプトアウトではなくなり、送信した SMS メッセージを受信します。

SMS サブスクリプションを削除する

トピックにパブリッシュするときに、その電話番号への SMS メッセージの送信を停止するように SMS サブスクリプションを削除します。

  1. ナビゲーションパネルで、[サブスクリプション] を選択します。

  2. 削除するサブスクリプションのチェックボックスをオンにします。それから、[アクション] を選択して、[アプリケーションの削除] を選択します。

  3. [削除] ウィンドウで、[削除] を選択します。Amazon SNS はサブスクリプションを削除し、成功のメッセージを表示します。

トピックを削除する

サブスクライブしたエンドポイントにメッセージを発行しない場合トピックを削除します。

  1. ナビゲーションパネルで、[トピック] を選択します。

  2. 削除するトピックのチェックボックスをオンにします。[アクション] を選択してから、[トピックの削除] を選択します。

  3. [削除] ウィンドウで、[削除] を選択します。Amazon SNS はトピックを削除し、成功のメッセージを表示します。

電話番号およびサブスクリプション (AWS SDK) を管理する

AWS SDKs を使用して Amazon SNS にプログラムでリクエストを行い、アカウントから SMS メッセージを受信できる電話番号を管理できます。

AWS SDK を使用するには、 認証情報を使用して設定する必要があります。詳細については、『AWS SDK とツールのリファレンスガイド』の「共有設定ファイルおよび認証情報ファイル」を参照してください。

すべてのオプトアウトした電話番号を表示する

すべてのオプトアウトした電話番号を表示するには、Amazon SNS API を使用して、ListPhoneNumbersOptedOut リクエストを送信します。

次のコード例は、Amazon SNS メッセージの受信をオプトアウトした電話番号をリストする方法を示しています。

CLI
AWS CLI

SMS メッセージのオプトアウトを一覧表示するには

次の list-phone-numbers-opted-out の例では、SMS メッセージの受信をオプトアウトした電話番号を一覧表示しています。

aws sns list-phone-numbers-opted-out

出力:

{ "phoneNumbers": [ "+15555550100" ] }
  • API の詳細については、「 コマンドリファレンスListPhoneNumbersOptedOut」の「」を参照してください。 AWS CLI

Java
SDK for Java 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); } } }
  • API の詳細については、「 API リファレンスListPhoneNumbersOptedOut」の「」を参照してください。 AWS SDK for Java 2.x

PHP
SDK for PHP
注記

には他にもがあります 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()); }

電話番号がオプトアウトしているかどうかを確認する

電話番号がオプトアウトしているかどうかを確認するには、Amazon SNS API を使用して、CheckIfPhoneNumberIsOptedOut リクエストを送信します。

次のコード例は、電話番号が Amazon SNS メッセージの受信をオプトアウトしているかを確認する方法を示しています。

.NET
AWS SDK for .NET
注記

には他にもがあります 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}"); } } }
  • API の詳細については、「 API リファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS SDK for .NET

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 }
  • API の詳細については、「 コマンドリファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS CLI

Java
SDK for Java 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); } } }
  • API の詳細については、「 API リファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS SDK for JavaScript

PHP
SDK for PHP
注記

には他にもがあります 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()); }

オプトアウトされた電話番号をオプトインする

電話番号をオプトインするには、Amazon SNS API を使用して、OptInPhoneNumber リクエストを送信します。

30 日に 1 回のみ、電話番号をオプトインできます。

SMS サブスクリプションを削除する

Amazon SNS トピックからの SMS サブスクリプションを削除するには、Amazon SNS API を使用して ListSubscriptions リクエストを送信することにより、サブスクリプション ARN を取得し、次に、その ARN を Unsubscribe リクエストに渡します。

以下のコード例で、Amazon SNS サブスクリプションを削除する方法を示します。

.NET
AWS SDK for .NET
注記

には他にもがあります 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 の詳細については、「AWS SDK for .NET API リファレンス」の「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 の詳細については、「AWS SDK for C++ API リファレンス」の「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 コマンドリファレンス」の「Unsubscribe」を参照してください。

Java
SDK for Java 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 リファレンス」の「Unsubscribe」を参照してください。

JavaScript
SDK for 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Unsubscribe」を参照してください。

Kotlin
SDK for Kotlin
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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 の詳細については、AWS SDK for Kotlin API リファレンスの「Unsubscribe」を参照してください。

PHP
SDK for PHP
注記

には他にもがあります 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
SDK for Python (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
  • API の詳細については、AWS SDK for Python (Boto3) API リファレンスの「Unsubscribe」を参照してください。

SAP ABAP
SDK for SAP ABAP
注記

には他にもがあります 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 リファレンスの「Unsubscribe」(サブスクリプション解除) を参照してください。

トピックを削除する

トピックとサブスクリプションすべてを削除するには、Amazon SNS API を使用して ListTopics リクエストを送信することでトピック ARN を取得し、次に、その ARN を DeleteTopic リクエストに渡します。

次のコード例は、Amazon SNS トピックとそのトピックに対するすべてのサブスクリプションを削除する方法を示しています。

.NET
AWS SDK for .NET
注記

には他にもがあります 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 の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for .NET

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 の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for C++

CLI
AWS CLI

SNS トピックを削除するには

次の delete-topic の例では、指定した SNS トピックを削除します。

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

このコマンドでは何も出力されません。

  • API の詳細については、「 コマンドリファレンスDeleteTopic」の「」を参照してください。 AWS CLI

Go
SDK for Go V2
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// 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 の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for Go

Java
SDK for Java 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 の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for Java 2.x

JavaScript
SDK for 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 // } // } };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for JavaScript

Kotlin
SDK for Kotlin
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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 の詳細については、DeleteTopicAWS 「 SDK for Kotlin API リファレンス」の「」を参照してください。

PHP
SDK for PHP
注記

には他にもがあります 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 の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for PHP

Python
SDK for Python (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
  • API の詳細については、DeleteTopicAWS 「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。

SAP ABAP
SDK for SAP ABAP
注記

には他にもがあります 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 の詳細については、DeleteTopicAWS 「 SDK for SAP ABAP API リファレンス」の「」を参照してください。