As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.
Gerenciar assinaturas de números de telefone do Amazon SNS
O Amazon SNS oferece várias opções para gerenciar quem recebe mensagens SMS de sua conta. Você pode ativar números de telefone que optaram por não receber mensagens SMS. No entanto, você só pode fazer isso com uma frequência limitada.
Para parar de enviar mensagens para assinaturas de SMS, remova as assinaturas ou os tópicos que são publicados nelas.
Cancelar recebimento de mensagens SMS
Quando exigido pelas leis e regulamentos locais (como nos Estados Unidos e Canadá), os destinatários de SMS podem usar seus dispositivos para cancelar a inscrição respondendo à mensagem com uma destas opções:
-
ARRET (Francês)
-
CANCEL
-
END
-
OPT-OUT
-
CANCELAR
-
QUIT
-
REMOVE
-
STOP
-
TD
-
CANCELAR INSCRIÇÃO
Para cancelar o recebimento, o destinatário deve responder ao mesmo número de origem que o Amazon SNS usou para entregar a mensagem. Depois de cancelar, o destinatário não recebe mais mensagens SMS do seu. Conta da AWS Isso se aplica, a menos que você opte pelo número de telefone.
Se o número de telefone estiver inscrito em um tópico do Amazon SNS, a desativação não removerá a assinatura. No entanto, as mensagens SMS não são entregues nessa assinatura, a menos que você opte pelo número de telefone.
Gerenciar números de telefone e assinaturas usando o console do Amazon SNS
É possível usar o console do Amazon SNS para controlar quais números de telefone recebem mensagens SMS de sua conta.
Opting-in um número de telefone que foi excluído do console do Amazon SNS
Você pode ver quais números de telefone optaram por não receber mensagens SMS da sua conta. Você também pode ativar esses números de telefone para retomar o envio de mensagens para eles.
Você pode incluir um número de telefone somente uma vez a cada 30 dias.
Faça login no console do Amazon SNS.
-
No menu do console, defina o seletor de região para uma região que ofereça suporte a mensagens SMS.
-
No painel de navegação, escolha Text messaging (SMS) [Mensagens de texto (SMS)].
-
Na página Mensagens de texto móveis (SMS), na seção de números de Opted-out telefone, a página exibe números de telefone desativados.
-
Marque a caixa de seleção para o número de telefone que você deseja incluir e selecione Incluir. O número de telefone não está mais desativado e recebe mensagens SMS que você envia para ele.
Excluir uma assinatura de SMS no console do Amazon SNS
Exclua uma inscrição de SMS para interromper o envio de mensagens SMS para aquele número de telefone quando você publicar nos tópicos.
-
No painel de navegação, escolha Subscriptions (Assinaturas).
-
Marque as caixas de seleção das assinaturas a serem excluídas. Escolha Ações e escolha Excluir inscrições.
-
Na janela Delete (Excluir), escolha Delete (Excluir). O Amazon SNS exclui a assinatura e exibe uma mensagem de êxito.
Excluir um tópico do console do Amazon SNS
Exclua um tópico quando você não desejar mais publicar mensagens em seus endpoints inscritos.
-
No painel de navegação, escolha Tópicos.
-
Marque as caixas de seleção dos tópicos a serem excluídos. Escolha Ações e escolha Excluir tópicos.
-
Na janela Delete (Excluir), escolha Delete (Excluir). O Amazon SNS exclui o tópico e exibe uma mensagem de êxito.
Gerenciando números de telefone e assinaturas usando o AWS SDK
Você pode usar os AWS SDKs para fazer solicitações programáticas ao Amazon SNS. Você pode gerenciar quais números de telefone podem receber mensagens SMS da sua conta.
Para usar um AWS SDK, você deve configurá-lo com suas credenciais. Para obter mais informações, consulte Arquivos compartilhados de configuração e de credenciais no Guia de referência de AWS SDKs e ferramentas.
Visualizando todos os números de telefone desativados usando o AWS SDK
Para visualizar todos os números de telefone cancelados, envie uma solicitação ListPhoneNumbersOptedOut com a API do Amazon SNS.
Os exemplos de código a seguir mostram como usar o ListPhoneNumbersOptedOut.
- CLI
-
- AWS CLI
-
Para listar as opções de cancelamento de mensagens SMS
O exemplo list-phone-numbers-opted-out a seguir lista os números de telefone que optaram por não receber mensagens SMS.
aws sns list-phone-numbers-opted-out
Saída:
{
"phoneNumbers": [
"+15555550100"
]
}
- Java
-
- SDK para Java 2.x
-
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 para PHP
-
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());
}
Verificar se um número de telefone foi excluído usando o AWS SDK
Para verificar se um número de telefone cancelou o recebimento, envie uma solicitação CheckIfPhoneNumberIsOptedOut com a API do Amazon SNS.
Os exemplos de código a seguir mostram como usar o CheckIfPhoneNumberIsOptedOut.
- .NET
-
- SDK para .NET
-
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
-
Para verificar o cancelamento de mensagens SMS para um número de telefone
O check-if-phone-number-is-opted-out exemplo a seguir verifica se o número de telefone especificado optou por não receber mensagens SMS da AWS conta atual.
aws sns check-if-phone-number-is-opted-out \
--phone-number +1555550100
Saída:
{
"isOptedOut": false
}
- Java
-
- SDK para Java 2.x
-
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 para JavaScript (v3)
-
Crie o cliente em um módulo separado e exporte-o.
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({});
Importe o SDK e os módulos do cliente e chame a 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 para PHP
-
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 um número de telefone que foi desativado usando a API do Amazon SNS
Para incluir um número de telefone que cancelou o recebimento, envie uma solicitação OptInPhoneNumber com a API do Amazon SNS.
Você pode incluir um número de telefone somente uma vez a cada 30 dias.
Excluindo uma assinatura de SMS usando o AWS SDK
Para excluir uma assinatura de SMS de um tópico do Amazon SNS, obtenha o ARN da assinatura enviando uma ListSubscriptions solicitação com a API do Amazon SNS. Em seguida, passe o ARN para uma Unsubscribe solicitação.
Os exemplos de código a seguir mostram como usar o Unsubscribe.
- .NET
-
- SDK para .NET
-
Cancele a assinatura de um tópico por meio de um ARN de assinatura.
/// <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;
}
- C++
-
- SDK para C++
-
//! 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();
}
- CLI
-
- AWS CLI
-
Para cancelar a assinatura de um tópico
O exemplo unsubscribe a seguir exclui a assinatura especificada de um tópico.
aws sns unsubscribe \
--subscription-arn arn:aws:sns:us-west-2:0123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f
Este comando não produz saída.
- Java
-
- SDK para Java 2.x
-
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);
}
}
}
- JavaScript
-
- SDK para JavaScript (v3)
-
Crie o cliente em um módulo separado e exporte-o.
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({});
Importe o SDK e os módulos do cliente e chame a 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 para Kotlin
-
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}")
}
}
- PHP
-
- SDK para PHP
-
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 para 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
@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
- SAP ABAP
-
- SDK para SAP ABAP
-
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.
- Swift
-
- SDK para Swift
-
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.")
Excluindo um tópico usando o AWS SDK
Para excluir um tópico e todas as suas assinaturas, obtenha o ARN do tópico enviando uma ListTopics solicitação com a API do Amazon SNS. Em seguida, passe o ARN para a DeleteTopic solicitação.
Os exemplos de código a seguir mostram como usar o DeleteTopic.
- .NET
-
- SDK para .NET
-
Exclua um tópico por meio do respectivo 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;
}
- C++
-
- SDK para C++
-
//! 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();
}
- CLI
-
- AWS CLI
-
Para excluir um tópico do SNS
O exemplo delete-topic a seguir exclui o tópico do SNS especificado.
aws sns delete-topic \
--topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"
Este comando não produz saída.
- Go
-
- SDK para Go V2
-
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
}
- Java
-
- SDK para Java 2.x
-
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);
}
}
}
- JavaScript
-
- SDK para JavaScript (v3)
-
Crie o cliente em um módulo separado e exporte-o.
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({});
Importe o SDK e os módulos do cliente e chame a 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 para Kotlin
-
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.")
}
}
- PHP
-
- SDK para PHP
-
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());
}
- Python
-
- SDK para 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
@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
- SAP ABAP
-
- SDK para SAP ABAP
-
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.
- Swift
-
- SDK para Swift
-
import AWSSNS
let config = try await SNSClient.SNSClientConfiguration(region: region)
let snsClient = SNSClient(config: config)
_ = try await snsClient.deleteTopic(
input: DeleteTopicInput(topicArn: arn)
)