

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 建立 Amazon SNS 主題並發佈訊息
<a name="sns-getting-started"></a>

本主題提供管理 Amazon SNS 資源的基礎步驟，特別著重於主題、訂閱和訊息發佈。首先，您將設定 Amazon SNS 的必要存取許可，確保您擁有建立和管理 Amazon SNS 資源的正確許可。接著，您將建立新的 Amazon SNS 主題，做為管理和交付訊息給訂閱用戶的中心中樞。建立主題後，您將繼續建立此主題的訂閱，允許特定端點接收發佈至主題的訊息。

主題和訂閱到位後，您將發佈訊息到主題，觀察 Amazon SNS 如何有效率地將訊息傳遞到所有訂閱的端點。最後，您將了解如何同時刪除訂閱和主題，完成您管理的 Amazon SNS 資源生命週期。此方法可讓您清楚了解 Amazon SNS 中的基本操作，讓您具備使用 Amazon SNS 主控台管理簡訊工作流程所需的實際技能。

# 設定 Amazon SNS 存取權限
<a name="sns-setting-up"></a>

第一次使用 Amazon SNS 之前，您必須先完成以下步驟。

## 建立 AWS 帳戶 和 IAM 使用者
<a name="create-aws-account"></a>

若要存取任何 AWS 服務，您必須先建立 [AWS 帳戶](https://aws.amazon.com/)。您可以使用 AWS 帳戶 來檢視活動和用量報告，以及管理身分驗證和存取。

### 註冊 AWS 帳戶
<a name="sign-up-for-aws"></a>

如果您沒有 AWS 帳戶，請完成下列步驟來建立一個。

**註冊 AWS 帳戶**

1. 開啟 [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)。

1. 請遵循線上指示進行。

   部分註冊程序需接收來電或簡訊，並在電話鍵盤輸入驗證碼。

   當您註冊 時 AWS 帳戶，會建立*AWS 帳戶 根使用者*。根使用者有權存取該帳戶中的所有 AWS 服務 和資源。作為安全最佳實務，請將管理存取權指派給使用者，並且僅使用根使用者來執行[需要根使用者存取權的任務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS 會在註冊程序完成後傳送確認電子郵件給您。您可以隨時登錄 [https://aws.amazon.com/](https://aws.amazon.com/) 並選擇**我的帳戶**，以檢視您目前的帳戶活動並管理帳戶。

### 建立具有管理存取權的使用者
<a name="create-an-admin"></a>

註冊 後 AWS 帳戶，請保護您的 AWS 帳戶 根使用者 AWS IAM Identity Center、啟用和建立管理使用者，以免將根使用者用於日常任務。

**保護您的 AWS 帳戶 根使用者**

1.  選擇**根使用者**並輸入 AWS 帳戶 您的電子郵件地址，以帳戶擁有者[AWS 管理主控台](https://console.aws.amazon.com/)身分登入 。在下一頁中，輸入您的密碼。

   如需使用根使用者登入的說明，請參閱 *AWS 登入 使用者指南*中的[以根使用者身分登入](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 若要在您的根使用者帳戶上啟用多重要素驗證 (MFA)。

   如需說明，請參閱《*IAM 使用者指南*》中的[為您的 AWS 帳戶 根使用者 （主控台） 啟用虛擬 MFA 裝置](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

**建立具有管理存取權的使用者**

1. 啟用 IAM Identity Center。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[啟用 AWS IAM Identity Center](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)。

1. 在 IAM Identity Center 中，將管理存取權授予使用者。

   如需使用 IAM Identity Center 目錄 做為身分來源的教學課程，請參閱*AWS IAM Identity Center 《 使用者指南*》中的[使用預設值設定使用者存取 IAM Identity Center 目錄](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html)。

**以具有管理存取權的使用者身分登入**
+ 若要使用您的 IAM Identity Center 使用者簽署，請使用建立 IAM Identity Center 使用者時傳送至您電子郵件地址的簽署 URL。

  如需使用 IAM Identity Center 使用者登入的說明，請參閱*AWS 登入 《 使用者指南*》中的[登入 AWS 存取入口網站](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)。

**指派存取權給其他使用者**

1. 在 IAM Identity Center 中，建立一個許可集來遵循套用最低權限的最佳實務。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[建立許可集](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)。

1. 將使用者指派至群組，然後對該群組指派單一登入存取權。

   如需指示，請參閱《AWS IAM Identity Center 使用者指南》**中的[新增群組](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)。

## 後續步驟
<a name="next-steps-setting-up"></a>

現在您已準備好使用 Amazon SNS，請開始使用：

1. [建立 Amazon SNS 主題](sns-create-topic.md)

1. [建立 Amazon SNS 主題的訂閱](sns-create-subscribe-endpoint-to-topic.md) 

1. [發佈 Amazon SNS 訊息](sns-publishing.md)

1. [刪除 Amazon SNS 主題和訂閱](sns-delete-subscription-topic.md)

# 建立 Amazon SNS 主題
<a name="sns-create-topic"></a>

Amazon SNS 主題是做為*通訊頻道*的邏輯存取點。主題可讓您將多個*端點* （例如 AWS Lambda Amazon SQS、HTTP/S 或電子郵件地址） 分組。

若要廣播訊息生產者系統 (例如，電子商務網站) 的訊息，而此系統會搭配需要其訊息的其他多個服務 (例如，結帳和履行系統)，您可以為生產者系統建立主題。

第一個最常見的 Amazon SNS 任務是建立主題。此頁面說明如何使用 AWS 管理主控台、 適用於 Java 的 AWS SDK和 適用於 .NET 的 AWS SDK 來建立主題。

在建立期間，您可以選擇主題類型 (標準或 FIFO) 並命名主題。建立主題後，即無法變更主題類型或名稱。所有其他組態選項在建立主題期間都是可選的，您可以稍後編輯它們。

**重要**  
請勿在主題名稱中新增個人身分識別資訊 (PII) 或其他機密或敏感資訊。包括 CloudWatch Logs 在內的其他 Amazon Web Services 可存取主題名稱。主題名稱不適用於私有或敏感資料。

## 使用 建立主題 AWS 管理主控台
<a name="create-topic-aws-console"></a>

在 Amazon SNS 中建立主題可建立訊息分發的基礎，讓您能夠發佈可散發給多個訂閱用戶的訊息。此步驟對於設定主題的類型、加密設定和存取政策至關重要，可確保主題符合組織的安全性、合規性和操作需求。

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 執行以下任意一項：
   + 如果 AWS 帳戶 之前沒有在您的 下建立任何主題，請閱讀 首頁上的 Amazon SNS 說明。
   + 如果 AWS 帳戶 之前已在 下建立主題，請在導覽面板上選擇**主題**。

1. 在**主題**頁面上，選擇**建立主題**。

1. 在 **Create topic** (建立主題) 頁面上，於 **Details** (詳細資訊) 區段中，執行以下作業：

   1. 對於 **Type** (類型)，選擇主題類型 (**Standard** (標準)或**FIFO**。

   1. 輸入新主題的**名稱**。對於[FIFO 主題](sns-fifo-topics.md)，新增**.fifo**到名稱的結尾。

   1. (選用) 為主題輸入 **Display name** (顯示名稱)。
**重要**  
訂閱電子郵件端點時，Amazon SNS 主題顯示名稱和傳送電子郵件地址 (例如 no-reply@sns.amazonaws.com) 的組合字元計數不得超過 320 個 UTF-8 字元。在為 Amazon SNS 主題設定顯示名稱之前，您可以使用第三方編碼工具來驗證傳送地址的長度。

   1. (選用) 對於 FIFO 主題，您可以選擇**內容型訊息重複資料刪除功能**，以啟用預設的重複訊息刪除功能。如需詳細資訊，請參閱[FIFO 主題的 Amazon SNS 訊息重複資料刪除](fifo-message-dedup.md)。

1. (選用) 展開 **Encryption** (加密) 區段並執行下列動作。如需詳細資訊，請參閱[使用伺服器端加密保護 Amazon SNS 資料](sns-server-side-encryption.md)。

   1. 選擇 **Enable encryption** (啟用加密)。

   1. 指定 AWS KMS 金鑰。如需詳細資訊，請參閱[重要用語](sns-server-side-encryption.md#sse-key-terms)。

      每個 KMS 類型均會顯示 **Description (描述)**、**Account (帳戶)** 和 **KMS ARN**。
**重要**  
若您並非 KMS 的擁有者，或者您登入的帳戶並無 `kms:ListAliases` 和 `kms:DescribeKey` 的許可，即無法在 Amazon SNS 主控台上檢視 KMS 相關資訊。  
請要求 KMS 的擁有者授與您這些許可。如需詳細資訊，請參閱《AWS Key Management Service 開發人員指南》中的[AWS KMS API 許可：動作和資源參考](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html)。
      + 預設會選取 Amazon SNS **（預設） alias/aws/sns** 的 AWS 受管 KMS。
**注意**  
請謹記以下幾點：  
第一次使用 AWS 管理主控台 來指定主題的 Amazon SNS AWS 受管 KMS 時， 會 AWS KMS 建立 Amazon SNS 的 AWS 受管 KMS。
或者，當您第一次在已啟用 SSE 的主題上使用 `Publish`動作時， 會 AWS KMS 建立 Amazon SNS 的 AWS 受管 KMS。
      + 若要從 AWS 您的帳戶使用自訂 KMS，請選擇 **KMS 金鑰**欄位，然後從清單中選擇自訂 KMS。
**注意**  
如需建立自訂 KMS 的說明，請參閱 *AWS Key Management Service 開發人員指南*中的[建立金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)
      + 若要從您的帳戶或其他 AWS 帳戶使用自訂 KMS ARN AWS ，請在 **KMS 金鑰**欄位中輸入它。

1. (選用) 根據預設，只有主題擁有者可以發布或訂閱主題。若要設定其他存取許可，請展開 **Access policy** (存取政策) 區段。如需詳細資訊，請參閱[Amazon SNS 中的 Identity and Access Management](security-iam.md)及[Amazon SNS 存取控制的範例案例](sns-access-policy-use-cases.md)。
**注意**  
當您使用主控台建立主題時，預設政策會使用 `aws:SourceOwner` 條件金鑰。此金鑰類似於 `aws:SourceAccount`。

1. (選用) 若要設定 Amazon SNS 如何在訊息傳遞嘗試失敗後重試，請展開 **Delivery retry policy (HTTP/S)** (傳遞重試政策 (HTTP/S)) 區段。如需詳細資訊，請參閱[Amazon SNS 訊息傳遞重試](sns-message-delivery-retries.md)。

1. (選用) 若要設定 Amazon SNS 如何將訊息傳遞情形記錄到 CloudWatch，請展開 **Delivery status logging** (傳遞狀態記錄) 區段。如需詳細資訊，請參閱[Amazon SNS 訊息傳遞狀態](sns-topic-attributes.md)。

1. (選用) 若要將中繼資料標籤新增至主題，請展開 **Tags** (標籤) 區段，輸入 **Key**(金鑰) 和 **Value** (值) (選用)，然後選擇 **Add tag** (新增標籤)。如需詳細資訊，請參閱[Amazon SNS 主題標記](sns-tags.md)。

1. 請選擇**建立主題**。

   該主題隨即建立，並且 ***MyTopic*** 頁面即會顯示。

   主題**的名稱**、**ARN**、（選用） **顯示名稱**和**主題擁有者** AWS 的帳戶 ID 會顯示在**詳細資訊**區段中。

1. 將主題 ARN 複製到剪貼簿，例如：

   ```
   arn:aws:sns:us-east-2:123456789012:MyTopic
   ```

## 使用 AWS SDK 建立主題
<a name="create-topic-aws-sdks"></a>

若要使用 AWS SDK，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

下列程式碼範例示範如何使用 `CreateTopic`。

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)中設定和執行。
建立具有特定名稱的主題。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example shows how to use Amazon Simple Notification Service
    /// (Amazon SNS) to add a new Amazon SNS topic.
    /// </summary>
    public class CreateSNSTopic
    {
        public static async Task Main()
        {
            string topicName = "ExampleSNSTopic";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            var topicArn = await CreateSNSTopicAsync(client, topicName);
            Console.WriteLine($"New topic ARN: {topicArn}");
        }

        /// <summary>
        /// Creates a new SNS topic using the supplied topic name.
        /// </summary>
        /// <param name="client">The initialized SNS client object used to
        /// create the new topic.</param>
        /// <param name="topicName">A string representing the topic name.</param>
        /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
        public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
        {
            var request = new CreateTopicRequest
            {
                Name = topicName,
            };

            var response = await client.CreateTopicAsync(request);

            return response.TopicArn;
        }
    }
```
建立具有名稱、特定 FIFO 和重複資料刪除屬性的新主題。  

```
    /// <summary>
    /// Create a new topic with a name and specific FIFO and de-duplication attributes.
    /// </summary>
    /// <param name="topicName">The name for the topic.</param>
    /// <param name="useFifoTopic">True to use a FIFO topic.</param>
    /// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param>
    /// <returns>The ARN of the new topic.</returns>
    public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication)
    {
        var createTopicRequest = new CreateTopicRequest()
        {
            Name = topicName,
        };

        if (useFifoTopic)
        {
            // Update the name if it is not correct for a FIFO topic.
            if (!topicName.EndsWith(".fifo"))
            {
                createTopicRequest.Name = topicName + ".fifo";
            }

            // Add the attributes from the method parameters.
            createTopicRequest.Attributes = new Dictionary<string, string>
            {
                { "FifoTopic", "true" }
            };
            if (useContentBasedDeduplication)
            {
                createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true");
            }
        }

        var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest);
        return createResponse.TopicArn;
    }
```
+  如需 API 詳細資訊，請參閱 *適用於 .NET 的 AWS SDK API 參考*中的 [CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中設定和執行。

```
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicName: An Amazon SNS topic name.
  \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
                              Aws::String &topicARNResult,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::CreateTopicRequest request;
    request.SetName(topicName);

    const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

    if (outcome.IsSuccess()) {
        topicARNResult = outcome.GetResult().GetTopicArn();
        std::cout << "Successfully created an Amazon SNS topic " << topicName
                  << " with topic ARN '" << topicARNResult
                  << "'." << std::endl;

    }
    else {
        std::cerr << "Error creating topic " << topicName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
        topicARNResult.clear();
    }

    return outcome.IsSuccess();
}
```
+  如需 API 詳細資訊，請參閱《適用於 C\$1\$1 的 AWS SDK API 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)。

------
#### [ CLI ]

**AWS CLI**  
**建立 SNS 主題**  
下列 `create-topic` 範例會建立名為 `my-topic` 的 SNS 主題。  

```
aws sns create-topic \
    --name my-topic
```
輸出：  

```
{
    "ResponseMetadata": {
        "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83"
    },
    "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
```
如需詳細資訊，請參閱《 [AWS 命令列界面使用者指南》中的搭配 Amazon SQS 和 Amazon SNS 使用](https://docs.aws.amazon.com/cli/latest/userguide/cli-sqs-queue-sns-topic.html)命令列界面。 *AWS *  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [CreateTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-topic.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)中設定和執行。

```
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
}



// CreateTopic creates an Amazon SNS topic with the specified name. You can optionally
// specify that the topic is created as a FIFO topic and whether it uses content-based
// deduplication instead of ID-based deduplication.
func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) {
	var topicArn string
	topicAttributes := map[string]string{}
	if isFifoTopic {
		topicAttributes["FifoTopic"] = "true"
	}
	if contentBasedDeduplication {
		topicAttributes["ContentBasedDeduplication"] = "true"
	}
	topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{
		Name:       aws.String(topicName),
		Attributes: topicAttributes,
	})
	if err != nil {
		log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err)
	} else {
		topicArn = *topic.TopicArn
	}

	return topicArn, err
}
```
+  如需 API 詳細資訊，請參閱 *適用於 Go 的 AWS SDK API 參考*中的 [CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中設定和執行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
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 CreateTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicName>

                Where:
                   topicName - The name of the topic to create (for example, mytopic).

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicName = args[0];
        System.out.println("Creating a topic with name: " + topicName);
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String arnVal = createSNSTopic(snsClient, topicName);
        System.out.println("The topic ARN is" + arnVal);
        snsClient.close();
    }

    public static String createSNSTopic(SnsClient snsClient, String topicName) {
        CreateTopicResponse result;
        try {
            CreateTopicRequest request = CreateTopicRequest.builder()
                    .name(topicName)
                    .build();

            result = snsClient.createTopic(request);
            return result.topicArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  如需 API 詳細資訊，請參閱《AWS SDK for Java 2.x API 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)。

------
#### [ JavaScript ]

**適用於 JavaScript (v3) 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)中設定和執行。
在單獨的模組中建立用戶端並將其匯出。  

```
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 { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```
+  如需詳細資訊，請參閱[《適用於 JavaScript 的 AWS SDK 開發人員指南》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)。
+  如需 API 詳細資訊，請參閱《適用於 JavaScript 的 AWS SDK API 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)。

------
#### [ Kotlin ]

**適用於 Kotlin 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中設定和執行。

```
suspend fun createSNSTopic(topicName: String): String {
    val request =
        CreateTopicRequest {
            name = topicName
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.createTopic(request)
        return result.topicArn.toString()
    }
}
```
+  如需 API 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》[https://sdk.amazonaws.com/kotlin/api/latest/index.html](https://sdk.amazonaws.com/kotlin/api/latest/index.html)中的 *CreateTopic*。

------
#### [ PHP ]

**適用於 PHP 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中設定和執行。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Create a Simple Notification Service topics in your AWS account at the requested region.
 *
 * 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'
]);

$topicname = 'myTopic';

try {
    $result = $SnSclient->createTopic([
        'Name' => $topicname,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  如需詳細資訊，請參閱《[適用於 PHP 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)》。
+  如需 API 詳細資訊，請參閱《適用於 PHP 的 AWS SDK API 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)。

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中設定和執行。

```
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 create_topic(self, name):
        """
        Creates a notification topic.

        :param name: The name of the topic to create.
        :return: The newly created topic.
        """
        try:
            topic = self.sns_resource.create_topic(Name=name)
            logger.info("Created topic %s with ARN %s.", name, topic.arn)
        except ClientError:
            logger.exception("Couldn't create topic %s.", name)
            raise
        else:
            return topic
```

```
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 create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API 參考*中的 [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)中設定和執行。

```
# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic.
class SNSTopicCreator
  # Initializes an SNS client.
  #
  # Utilizes the default AWS configuration for region and credentials.
  def initialize
    @sns_client = Aws::SNS::Client.new
  end

  # Attempts to create an SNS topic with the specified name.
  #
  # @param topic_name [String] The name of the SNS topic to create.
  # @return [Boolean] true if the topic was successfully created, false otherwise.
  def create_topic(topic_name)
    @sns_client.create_topic(name: topic_name)
    puts "The topic '#{topic_name}' was successfully created."
    true
  rescue Aws::SNS::Errors::ServiceError => e
    # Handles SNS service errors gracefully.
    puts "Error while creating the topic named '#{topic_name}': #{e.message}"
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_name = 'YourTopicName' # Replace with your topic name
  sns_topic_creator = SNSTopicCreator.new

  puts "Creating the topic '#{topic_name}'..."
  unless sns_topic_creator.create_topic(topic_name)
    puts 'The topic was not created. Stopping program.'
    exit 1
  end
end
```
+  如需詳細資訊，請參閱《[適用於 Ruby 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)》。
+  如需 API 詳細資訊，請參閱 *適用於 Ruby 的 AWS SDK API 參考*中的 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)。

------
#### [ Rust ]

**適用於 Rust 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)中設定和執行。

```
async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> {
    let resp = client.create_topic().name(topic_name).send().await?;

    println!(
        "Created topic with ARN: {}",
        resp.topic_arn().unwrap_or_default()
    );

    Ok(())
}
```
+  如需 API 詳細資訊，請參閱*適用於 Rust API 的AWS SDK 參考*中的 [CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)。

------
#### [ SAP ABAP ]

**適用於 SAP ABAP 的開發套件**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中設定和執行。

```
    TRY.
        oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. "
        MESSAGE 'SNS topic created' TYPE 'I'.
      CATCH /aws1/cx_snstopiclimitexcdex.
        MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'.
    ENDTRY.
```
+  如需 API 詳細資訊，請參閱《適用於 SAP ABAP API 的AWS SDK 參考》**中的 [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**適用於 Swift 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)中設定和執行。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(name: name)
        )

        guard let arn = output.topicArn else {
            print("No topic ARN returned by Amazon SNS.")
            return
        }
```
+  如需 API 詳細資訊，請參閱《適用於 Swift 的AWS SDK API 參考》**中的 [CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))。

------

# 建立 Amazon SNS 主題的訂閱
<a name="sns-create-subscribe-endpoint-to-topic"></a>

若要接收發佈到[主題](sns-create-topic.md)的訊息，您必須*訂閱*[端點](#sns-endpoints)至該主題。當您讓端點訂閱主題時，該端點會開始接收發佈到相關聯主題的訊息。

**注意**  
其他 AWS 帳戶 中的 HTTP(S) 端點、電子郵件地址 AWS 和資源需要先確認訂閱，才能接收訊息。

## 讓端點訂閱 Amazon SNS 主題
<a name="subscribe-topic-aws-console"></a>

訂閱 Amazon SNS 主題的端點可讓訊息傳遞至指定的端點，確保適當的系統或使用者在訊息發佈至主題時收到通知。此步驟對於將主題連結至消費者至關重要，無論他們是應用程式、電子郵件收件人或其他 服務，都允許跨系統進行無縫通訊。

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在左導覽窗格中，選擇**訂閱**。

1. 在**訂閱**頁面，選擇**建立訂閱**。

1. 在**建立訂閱**頁面上，於**詳細資訊**區段中，執行以下作業：

   1. 對於**ARN 主題**，選擇主題的 Amazon Resource Name (ARN)。此值是建立 Amazon SNS 主題時產生的 AWS ARN，例如 `arn:aws:sns:us-east-2:123456789012:your_topic`。

   1. 在 **Protocol** (通訊協定)，選擇端點類型。可用的端點類型為：
      + [**HTTP/HTTPS**](sns-http-https-endpoint-as-subscriber.md)
      + [**Email/Email-JSON** (電子郵件/電子郵件-JSON)](sns-email-notifications.md)
      + [****](sns-firehose-as-subscriber.md)
      + [**Amazon SQS**](sns-sqs-as-subscriber.md)
**注意**  
若要訂閱[SNS FIFO 主題](sns-fifo-topics.md)，請選擇此選項。
      + [**AWS Lambda**](sns-lambda-as-subscriber.md)
      + [**平台應用程式端點**](sns-mobile-application-as-subscriber.md)
      + [**SMS**](sns-mobile-phone-number-as-subscriber.md) 

   1. 對於**Endpoint** (端點)，輸入端點值，例如電子郵件地址或 Amazon SQS 佇列的 ARN。

   1. 僅限 Firehose 端點：針對**訂閱角色 ARN**，指定您為寫入 Firehose 交付串流所建立之 IAM 角色的 ARN。如需詳細資訊，請參閱[訂閱 Firehose 交付串流至 Amazon SNS 主題的先決條件](prereqs-kinesis-data-firehose.md)。

   1. （選用） 對於 Firehose、Amazon SQS、HTTP/S 端點，您也可以啟用原始訊息傳遞。如需詳細資訊，請參閱[Amazon SNS 原始訊息交付](sns-large-payload-raw-message-delivery.md)。

   1. (選用) 若要設定篩選政策，請展開 **Subscription filter policy** (訂閱篩選政策) 區段。如需詳細資訊，請參閱[Amazon SNS 訂閱篩選政策](sns-subscription-filter-policies.md)。

   1. (選用) 若要啟用以承載為基礎的篩選，請將 `Filter Policy Scope` 設定為 `MessageBody`。如需詳細資訊，請參閱[Amazon SNS 訂閱篩選政策範圍](sns-message-filtering-scope.md)。

   1. (選用) 若要設定訂閱的無效字母佇列，請展開 **Redrive policy (dead-letter queue)** (重新磁碟機政策 (無效字母佇列)) 區段。如需詳細資訊，請參閱[Amazon SNS 無效字母佇列](sns-dead-letter-queues.md)。

   1. 選擇**建立訂閱**。

      主控台會建立訂閱並開啟訂閱的 **Details** (詳細資訊) 頁面

# 發佈 Amazon SNS 訊息
<a name="sns-publishing"></a>

在您 [create an Amazon SNS topic](sns-create-topic.md) (建立 Amazon SNS 主題) 並讓端點 [subscribe](sns-create-subscribe-endpoint-to-topic.md) (訂閱) 主題之後，您可以將訊息 *publish* (發布) 至主題。發布訊息時，Amazon SNS 會嘗試將訊息傳送到已訂閱的[端點](sns-create-subscribe-endpoint-to-topic.md#sns-endpoints)。

## 使用 將訊息發佈至 Amazon SNS 主題 AWS 管理主控台
<a name="sns-publishing-messages"></a>

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在左側導覽窗格中，選擇 **Topics** (主題)。

1. 在 **Topics** (主題) 頁面上，選取主題然後選擇 **Publish message** (發布訊息)。

   主控台會開啟 **Publish message to topic** (將訊息發布至主題) 頁面。

1. 在 **Message details**(訊息詳細資訊) 區段中，執行下列動作：

   1. (選用) 輸入訊息 **Subject** (主旨)。

   1. 對於 [FIFO topic](sns-fifo-topics.md) (FIFO 主題)，輸入 **Message group ID** (訊息群組 ID)。FIFO 主題需要**訊息群組 ID**。相同訊息群組中的訊息會依發布順序傳遞。

   1. （選用） 對於標準主題，輸入**訊息群組 ID**。此 ID 會轉送至所有 Amazon SQS 標準訂閱，不會用於或傳送至任何其他端點類型。

   1. 對於 FIFO 主題，請輸入 **Message deduplication ID** (訊息重複資料刪除 ID)。如果您啟用**內容為基礎的訊息重複資料刪除**的主題設定，此 ID 是選擇性的。

   1. (選用) 針對 [mobile push notifications](sns-ttl.md) (行動推播通知)，輸入 **Time to Live (TTL)** (存留時間 (TTL)) 值 (以秒為單位)。這是推播通知服務 (例如 Apple 推播通知服務 (APN) 或 Firebase 雲端訊息 (FCM)) 傳送訊息到端點所需的時間量。

1. 在 **Message body** (訊息內文) 區段中，執行下列任一動作：

   1. 選擇 **Identical payload for all delivery protocols** (所有傳送協定的相同酬載) 然後輸入訊息。

   1. 選擇 **Custom payload for each delivery protocol** (各傳送協定自訂酬載)，然後使用 JSON 物件定義傳送至各協定的訊息。

      如需詳細資訊，請參閱 [發佈具有平台特定承載的 Amazon SNS 通知](sns-send-custom-platform-specific-payloads-mobile-devices.md)。

1. 在 **Message attributes** (訊息屬性) 區段中，新增您要讓 Amazon SNS 與 `FilterPolicy` 訂閱屬性比對的任何屬性，用以判斷訂閱的端點是否對發布的訊息感興趣。

   1. 針對 **Type** (類型)，選擇屬性類型，例如 **String.Array**。
**注意**  
針對屬性類型 **String.Array**，將陣列放在方括號 (`[]`) 中。在陣列內，以雙引號括住字串值。您不需要對數字或關鍵字 `true`、`false` 以及 `null` 使用引號。

   1. 輸入屬性 **名稱**，例如 `customer_interests`。

   1. 輸入屬性 **數值**，例如 `["soccer", "rugby", "hockey"]`。

   如果屬性類型為 **String** (字串)、**String.Array**，或 **Number** (數字)，且篩選政策範圍未明確設為 `MessageBody`，Amazon SNS 會以訂閱的[篩選政策](sns-message-filtering.md) (如果在傳送訊息到該訂閱之前出現) 來評估訊息屬性。

   如需詳細資訊，請參閱[Amazon SNS 訊息屬性](sns-message-attributes.md)。

1. 選擇 **Publish message** (發佈訊息)。

   訊息會發布到主題，主控台會開啟主題的 **Details** (詳細資訊) 頁面。

## 使用 AWS SDK 將訊息發佈至主題
<a name="publish-to-topic-aws-sdks"></a>

若要使用 AWS SDK，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

下列程式碼範例示範如何使用 `Publish`。

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)中設定和執行。
發布訊息至主題。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example publishes a message to an Amazon Simple Notification
    /// Service (Amazon SNS) topic.
    /// </summary>
    public class PublishToSNSTopic
    {
        public static async Task Main()
        {
            string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic";
            string messageText = "This is an example message to publish to the ExampleSNSTopic.";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await PublishToTopicAsync(client, topicArn, messageText);
        }

        /// <summary>
        /// Publishes a message to an Amazon SNS topic.
        /// </summary>
        /// <param name="client">The initialized client object used to publish
        /// to the Amazon SNS topic.</param>
        /// <param name="topicArn">The ARN of the topic.</param>
        /// <param name="messageText">The text of the message.</param>
        public static async Task PublishToTopicAsync(
            IAmazonSimpleNotificationService client,
            string topicArn,
            string messageText)
        {
            var request = new PublishRequest
            {
                TopicArn = topicArn,
                Message = messageText,
            };

            var response = await client.PublishAsync(request);

            Console.WriteLine($"Successfully published message ID: {response.MessageId}");
        }
    }
```
將訊息發佈至具有群組、複寫和屬性選項的主題。  

```
    /// <summary>
    /// Publish messages using user settings.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task PublishMessages()
    {
        Console.WriteLine("Now we can publish messages.");

        var keepSendingMessages = true;
        string? deduplicationId = null;
        string? toneAttribute = null;
        while (keepSendingMessages)
        {
            Console.WriteLine();
            var message = GetUserResponse("Enter a message to publish.", "This is a sample message");

            if (_useFifoTopic)
            {
                Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." +
                                  "\r\nAll messages within the same group will be received in the order " +
                                  "they were published.");

                Console.WriteLine();
                var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1");

                if (!_useContentBasedDeduplication)
                {
                    Console.WriteLine("Because you are not using content-based deduplication, " +
                                      "you must enter a deduplication ID.");

                    Console.WriteLine("Enter a deduplication ID for this message.");
                    deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1");
                }

                if (GetYesNoResponse("Add an attribute to this message?"))
                {
                    Console.WriteLine("Enter a number for an attribute.");
                    for (int i = 0; i < _tones.Length; i++)
                    {
                        Console.WriteLine($"\t{i + 1}. {_tones[i]}");
                    }

                    var selection = GetUserResponse("", "1");
                    int.TryParse(selection, out var selectionNumber);

                    if (selectionNumber > 0 && selectionNumber < _tones.Length)
                    {
                        toneAttribute = _tones[selectionNumber - 1];
                    }
                }

                var messageID = await SnsWrapper.PublishToTopicWithAttribute(
                    _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId);

                Console.WriteLine($"Message published with id {messageID}.");
            }

            keepSendingMessages = GetYesNoResponse("Send another message?", false);
        }
    }
```
將使用者的選擇套用至發佈動作。  

```
    /// <summary>
    /// Publish a message to a topic with an attribute and optional deduplication and group IDs.
    /// </summary>
    /// <param name="topicArn">The ARN of the topic.</param>
    /// <param name="message">The message to publish.</param>
    /// <param name="attributeName">The optional attribute for the message.</param>
    /// <param name="attributeValue">The optional attribute value for the message.</param>
    /// <param name="deduplicationId">The optional deduplication ID for the message.</param>
    /// <param name="groupId">The optional group ID for the message.</param>
    /// <returns>The ID of the message published.</returns>
    public async Task<string> PublishToTopicWithAttribute(
        string topicArn,
        string message,
        string? attributeName = null,
        string? attributeValue = null,
        string? deduplicationId = null,
        string? groupId = null)
    {
        var publishRequest = new PublishRequest()
        {
            TopicArn = topicArn,
            Message = message,
            MessageDeduplicationId = deduplicationId,
            MessageGroupId = groupId
        };

        if (attributeValue != null)
        {
            // Add the string attribute if it exists.
            publishRequest.MessageAttributes =
                new Dictionary<string, MessageAttributeValue>
                {
                    { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} }
                };
        }

        var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest);
        return publishResponse.MessageId;
    }
```
+  如需 API 詳細資訊，請參閱 *適用於 .NET 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中設定和執行。

```
//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param message: The message to publish.
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::publishToTopic(const Aws::String &message,
                                 const Aws::String &topicARN,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::PublishRequest request;
    request.SetMessage(message);
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

    if (outcome.IsSuccess()) {
        std::cout << "Message published successfully with id '"
                  << outcome.GetResult().GetMessageId() << "'." << std::endl;
    }
    else {
        std::cerr << "Error while publishing message "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
發佈具有屬性的訊息。  

```
        static const Aws::String TONE_ATTRIBUTE("tone");
        static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious",
                                                       "sincere"};

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);

        if (filteringMessages && askYesNoQuestion(
                "Add an attribute to this message? (y/n) ")) {
            for (size_t i = 0; i < TONES.size(); ++i) {
                std::cout << "  " << (i + 1) << ". " << TONES[i] << std::endl;
            }
            int selection = askQuestionForIntRange(
                    "Enter a number for an attribute. ",
                    1, static_cast<int>(TONES.size()));
            Aws::SNS::Model::MessageAttributeValue messageAttributeValue;
            messageAttributeValue.SetDataType("String");
            messageAttributeValue.SetStringValue(TONES[selection - 1]);
            request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue);
        }

        Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

        if (outcome.IsSuccess()) {
            std::cout << "Your message was successfully published." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::Publish. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
```
+  如需 API 詳細資訊，請參閱 *適用於 C\$1\$1 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)。

------
#### [ CLI ]

**AWS CLI**  
**範例 1：將訊息發布至主題**  
下列 `publish` 範例會將指定的訊息發佈到指定的 SNS 主題。訊息來自文字檔案，可讓您包含換行符號。  

```
aws sns publish \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \
    --message file://message.txt
```
`message.txt` 的內容：  

```
Hello World
Second Line
```
輸出：  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-111122223333"
}
```
**範例 2：將簡訊發布至電話號碼**  
下列 `publish` 範例會將訊息 `Hello world!` 發佈至電話號碼 `+1-555-555-0100`。  

```
aws sns publish \
    --message "Hello world!" \
    --phone-number +1-555-555-0100
```
輸出：  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-333322221111"
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [Publish](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/publish.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)中設定和執行。

```
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
}



// Publish publishes a message to an Amazon SNS topic. The message is then sent to all
// subscribers. When the topic is a FIFO topic, the message must also contain a group ID
// and, when ID-based deduplication is used, a deduplication ID. An optional key-value
// filter attribute can be specified so that the message can be filtered according to
// a filter policy.
func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error {
	publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)}
	if groupId != "" {
		publishInput.MessageGroupId = aws.String(groupId)
	}
	if dedupId != "" {
		publishInput.MessageDeduplicationId = aws.String(dedupId)
	}
	if filterKey != "" && filterValue != "" {
		publishInput.MessageAttributes = map[string]types.MessageAttributeValue{
			filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)},
		}
	}
	_, err := actor.SnsClient.Publish(ctx, &publishInput)
	if err != nil {
		log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err)
	}
	return err
}
```
+  如需 API 詳細資訊，請參閱 *適用於 Go 的 AWS SDK API 參考*中的[發佈](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中設定和執行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
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 PublishTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <topicArn>

                Where:
                   message - The message text to send.
                   topicArn - The ARN of the topic to publish.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String topicArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTopic(snsClient, message, topicArn);
        snsClient.close();
    }

    public static void pubTopic(SnsClient snsClient, String message, String topicArn) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .message(message)
                    .topicArn(topicArn)
                    .build();

            PublishResponse result = snsClient.publish(request);
            System.out
                    .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Java 2.x API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)。

------
#### [ JavaScript ]

**適用於 JavaScript (v3) 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)中設定和執行。
在單獨的模組中建立用戶端並將其匯出。  

```
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 { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
將訊息發佈至具有群組、複寫和屬性選項的主題。  

```
  async publishMessages() {
    const message = await this.prompter.input({
      message: MESSAGES.publishMessagePrompt,
    });

    let groupId;
    let deduplicationId;
    let choices;

    if (this.isFifo) {
      await this.logger.log(MESSAGES.groupIdNotice);
      groupId = await this.prompter.input({
        message: MESSAGES.groupIdPrompt,
      });

      if (this.autoDedup === false) {
        await this.logger.log(MESSAGES.deduplicationIdNotice);
        deduplicationId = await this.prompter.input({
          message: MESSAGES.deduplicationIdPrompt,
        });
      }

      choices = await this.prompter.checkbox({
        message: MESSAGES.messageAttributesPrompt,
        choices: toneChoices,
      });
    }

    await this.snsClient.send(
      new PublishCommand({
        TopicArn: this.topicArn,
        Message: message,
        ...(groupId
          ? {
              MessageGroupId: groupId,
            }
          : {}),
        ...(deduplicationId
          ? {
              MessageDeduplicationId: deduplicationId,
            }
          : {}),
        ...(choices
          ? {
              MessageAttributes: {
                tone: {
                  DataType: "String.Array",
                  StringValue: JSON.stringify(choices),
                },
              },
            }
          : {}),
      }),
    );

    const publishAnother = await this.prompter.confirm({
      message: MESSAGES.publishAnother,
    });

    if (publishAnother) {
      await this.publishMessages();
    }
  }
```
+  如需詳細資訊，請參閱《[適用於 JavaScript 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-publishing-messages.html)》。
+  如需 API 詳細資訊，請參閱 *適用於 JavaScript 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)。

------
#### [ Kotlin ]

**適用於 Kotlin 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中設定和執行。

```
suspend fun pubTopic(
    topicArnVal: String,
    messageVal: String,
) {
    val request =
        PublishRequest {
            message = messageVal
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  如需 API 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》**中的[發佈](https://sdk.amazonaws.com/kotlin/api/latest/index.html)。

------
#### [ PHP ]

**適用於 PHP 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中設定和執行。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Sends a message 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'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  如需詳細資訊，請參閱《[適用於 PHP 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-subscribing-unsubscribing-topics.html#publish-a-message-to-an-sns-topic)》。
+  如需 API 詳細資訊，請參閱 *適用於 PHP 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：此範例示範發佈一則附帶內嵌宣告的單一 MessageAttribute 訊息。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**範例 2：此範例示範發佈多則預先宣告的 MessageAttributes 訊息。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [Publish](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：此範例示範發佈一則附帶內嵌宣告的單一 MessageAttribute 訊息。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**範例 2：此範例示範發佈多則預先宣告的 MessageAttributes 訊息。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [Publish](https://docs.aws.amazon.com/powershell/v5/reference)。

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中設定和執行。
發佈具有屬性的郵件，以便訂閱可以根據屬性進行篩選。  

```
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 publish_message(topic, message, attributes):
        """
        Publishes a message, with attributes, to a topic. Subscriptions can be filtered
        based on message attributes so that a subscription receives messages only
        when specified attributes are present.

        :param topic: The topic to publish to.
        :param message: The message to publish.
        :param attributes: The key-value attributes to attach to the message. Values
                           must be either `str` or `bytes`.
        :return: The ID of the message.
        """
        try:
            att_dict = {}
            for key, value in attributes.items():
                if isinstance(value, str):
                    att_dict[key] = {"DataType": "String", "StringValue": value}
                elif isinstance(value, bytes):
                    att_dict[key] = {"DataType": "Binary", "BinaryValue": value}
            response = topic.publish(Message=message, MessageAttributes=att_dict)
            message_id = response["MessageId"]
            logger.info(
                "Published message with attributes %s to topic %s.",
                attributes,
                topic.arn,
            )
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```
發佈根據訂閱者的通訊協定採用不同形式的訊息。  

```
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 publish_multi_message(
        topic, subject, default_message, sms_message, email_message
    ):
        """
        Publishes a multi-format message to a topic. A multi-format message takes
        different forms based on the protocol of the subscriber. For example,
        an SMS subscriber might receive a short version of the message
        while an email subscriber could receive a longer version.

        :param topic: The topic to publish to.
        :param subject: The subject of the message.
        :param default_message: The default version of the message. This version is
                                sent to subscribers that have protocols that are not
                                otherwise specified in the structured message.
        :param sms_message: The version of the message sent to SMS subscribers.
        :param email_message: The version of the message sent to email subscribers.
        :return: The ID of the message.
        """
        try:
            message = {
                "default": default_message,
                "sms": sms_message,
                "email": email_message,
            }
            response = topic.publish(
                Message=json.dumps(message), Subject=subject, MessageStructure="json"
            )
            message_id = response["MessageId"]
            logger.info("Published multi-format message to topic %s.", topic.arn)
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```

```
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 publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise
```
+  如需 API 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API 參考*中的[發佈](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)中設定和執行。

```
# Service class for sending messages using Amazon Simple Notification Service (SNS)
class SnsMessageSender
  # Initializes the SnsMessageSender with an SNS client
  #
  # @param sns_client [Aws::SNS::Client] The SNS client
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Sends a message to a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param message [String] The message to send
  # @return [Boolean] true if message was successfully sent, false otherwise
  def send_message(topic_arn, message)
    @sns_client.publish(topic_arn: topic_arn, message: message)
    @logger.info("Message sent successfully to #{topic_arn}.")
    true
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error while sending the message: #{e.message}")
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN
  message = 'MESSAGE'         # Should be replaced with the actual message content

  sns_client = Aws::SNS::Client.new
  message_sender = SnsMessageSender.new(sns_client)

  @logger.info('Sending message.')
  unless message_sender.send_message(topic_arn, message)
    @logger.error('Message sending failed. Stopping program.')
    exit 1
  end
end
```
+  如需詳細資訊，請參閱《[適用於 Ruby 的 AWS SDK 開發人員指南](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-send-message.html)》。
+  如需 API 詳細資訊，請參閱 *適用於 Ruby 的 AWS SDK API 參考*中的[發佈](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/Publish)。

------
#### [ Rust ]

**適用於 Rust 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)中設定和執行。

```
async fn subscribe_and_publish(
    client: &Client,
    topic_arn: &str,
    email_address: &str,
) -> Result<(), Error> {
    println!("Receiving on topic with ARN: `{}`", topic_arn);

    let rsp = client
        .subscribe()
        .topic_arn(topic_arn)
        .protocol("email")
        .endpoint(email_address)
        .send()
        .await?;

    println!("Added a subscription: {:?}", rsp);

    let rsp = client
        .publish()
        .topic_arn(topic_arn)
        .message("hello sns!")
        .send()
        .await?;

    println!("Published message: {:?}", rsp);

    Ok(())
}
```
+  如需 API 詳細資訊，請參閱《適用於 Rust 的AWS SDK API 參考》**中的[發佈](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.publish)。

------
#### [ SAP ABAP ]

**適用於 SAP ABAP 的開發套件**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中設定和執行。

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message ).
        MESSAGE 'Message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
將具有屬性的訊息發佈至主題。  

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message
          it_messageattributes = it_msg_attrs ).
        MESSAGE 'Message with attributes published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
將多格式訊息發佈至主題。  

```
    " Build JSON message structure for multi-format message
    DATA(lv_json_message) = |\{ "default": "{ iv_default_message }", "sms": "{ iv_sms_message }", "email": "{ iv_email_message }" \}|.

    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = lv_json_message
          iv_subject = iv_subject
          iv_messagestructure = 'json' ).
        MESSAGE 'Multi-format message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  如需 API 詳細資訊，請參閱《適用於 SAP ABAP 的AWS SDK API 參考》**中的[發佈](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**適用於 Swift 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)中設定和執行。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.publish(
            input: PublishInput(
                message: message,
                topicArn: arn
            )
        )

        guard let messageId = output.messageId else {
            print("No message ID received from Amazon SNS.")
            return
        }
        
        print("Published message with ID \(messageId)")
```
+  如需 API 詳細資訊，請參閱《適用於 Swift 的AWS SDK API 參考》**中的 [Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:))。

------

# 使用 Amazon SNS 和 Amazon S3 發布大型訊息
<a name="large-message-payloads"></a>

若要發布大型 Amazon SNS 訊息，您可以使用[適用於 Java 的 Amazon SNS 擴充用戶端程式庫](https://github.com/awslabs/amazon-sns-java-extended-client-lib/)或[適用於 Python 的 Amazon SNS 擴充用戶端程式庫](https://github.com/awslabs/amazon-sns-python-extended-client-lib)。這些程式庫對於大於目前最大 256 KB 的訊息 (最大 2 GB) 非常有用。程式庫會將實際酬載儲存到 Amazon S3 儲存貯體，並將儲存的 Amazon S3 物件的參考發布到該主題。訂閱的 Amazon SQS 佇列可以使用[適用於 Java 的 Amazon SQS 擴展客戶端程式庫](https://github.com/awslabs/amazon-sqs-java-extended-client-lib)從 Amazon S3 取消參照和擷取酬載資料。其他端點 (例如 Lambda) 可以使用[酬載卸載 Java 通用程式庫 AWS](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws) 來取消引用並截取酬載。

**注意**  
Amazon SNS 延伸用戶端程式庫與標準和 FIFO 主題相容。

# 適用於 Java 的 Amazon SNS 擴充用戶端程式庫
<a name="extended-client-library-java"></a>

## 先決條件
<a name="prereqs-sns-extended-client-library"></a>

下列是使用[適用於 Java 的 Amazon SNS 擴充用戶端程式庫](https://github.com/awslabs/amazon-sns-java-extended-client-lib)的先決條件：
+  AWS 開發套件。本頁面上的範例使用 AWS Java 開發套件。若要安裝和設定 SDK，請參閱《 *適用於 Java 的 AWS SDK 開發人員指南*》中的[設定適用於 Java 的 AWS SDK](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-install.html)。
+  AWS 帳戶 具有適當登入資料的 。若要建立 AWS 帳戶，請導覽至 [AWS 首頁](https://aws.amazon.com/)，然後選擇**建立 AWS 帳戶**。遵循指示。

  如需登入資料的相關資訊，請參閱《 *適用於 Java 的 AWS SDK 開發人員指南*》中的[設定 AWS 登入資料和開發區域](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-credentials.html)。
+ Java 8 或更高版本。
+ 適用於 Java 的 Amazon SNS 擴充用戶端程式庫 (也可從 [Maven](https://maven.apache.org/) 取得)。

## 設定訊息儲存
<a name="large-message-configure-storage"></a>

Amazon SNS 延伸用戶端程式庫使用適用於 的承載卸載 Java 通用程式庫 AWS 進行訊息儲存和擷取。您可以配置以下 Amazon S3 [訊息儲存選項](https://github.com/awslabs/amazon-sns-java-extended-client-lib/blob/main/src/main/java/software/amazon/sns/SNSExtendedClientConfiguration.java)：
+ **自訂訊息大小閾值** – 承載和屬性超過此大小的訊息會自動存放在 Amazon S3 中。
+ **`alwaysThroughS3` flag** – 將此值設定為 `true`，強制將所有訊息承載儲存在 Amazon S3 中。例如：

  ```
  SNSExtendedClientConfiguration snsExtendedClientConfiguration = new
  SNSExtendedClientConfiguration() .withPayloadSupportEnabled(s3Client, BUCKET_NAME).withAlwaysThroughS3(true);
  ```
+ **自訂 KMS 金鑰** – 用於 Amazon S3 儲存貯體中伺服器端加密的金鑰。
+ **儲存貯體名稱** – 用於存放訊息承載的 Amazon S3 儲存貯體名稱。

## 範例：將訊息發布到 Amazon SNS，其中儲存在 Amazon S3 中的有效酬載
<a name="example-s3-large-payloads"></a>

以下程式碼範例顯示做法：
+ 建立範例主題和佇列。
+ 訂閱佇列以接收來自主題的訊息。
+ 發布測試訊息。

訊息酬載儲存在 Amazon S3 中，並發布對該訊息的參考。Amazon SQS 延伸用戶端是用來接收訊息。

**適用於 Java 1.x 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/java/example_code/sns#code-examples)中設定和執行。
若要發布大型訊息，請使用適用於 Java 的 Amazon SNS 擴充用戶端程式庫。您傳送的訊息會參考包含實際訊息內容的 Amazon S3 物件。  

```
import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import com.amazonaws.services.sns.util.Topics;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import software.amazon.sns.AmazonSNSExtendedClient;
import software.amazon.sns.SNSExtendedClientConfiguration;

public class Example {

        public static void main(String[] args) {
                final String BUCKET_NAME = "extended-client-bucket";
                final String TOPIC_NAME = "extended-client-topic";
                final String QUEUE_NAME = "extended-client-queue";
                final Regions region = Regions.DEFAULT_REGION;

                // Message threshold controls the maximum message size that will be allowed to
                // be published
                // through SNS using the extended client. Payload of messages exceeding this
                // value will be stored in
                // S3. The default value of this parameter is 256 KB which is the maximum
                // message size in SNS (and SQS).
                final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32;

                // Initialize SNS, SQS and S3 clients
                final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build();
                final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build();
                final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build();

                // Create bucket, topic, queue and subscription
                s3Client.createBucket(BUCKET_NAME);
                final String topicArn = snsClient.createTopic(
                                new CreateTopicRequest().withName(TOPIC_NAME)).getTopicArn();
                final String queueUrl = sqsClient.createQueue(
                                new CreateQueueRequest().withQueueName(QUEUE_NAME)).getQueueUrl();
                final String subscriptionArn = Topics.subscribeQueue(
                                snsClient, sqsClient, topicArn, queueUrl);

                // To read message content stored in S3 transparently through SQS extended
                // client,
                // set the RawMessageDelivery subscription attribute to TRUE
                final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest();
                subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn);
                subscriptionAttributesRequest.setAttributeName("RawMessageDelivery");
                subscriptionAttributesRequest.setAttributeValue("TRUE");
                snsClient.setSubscriptionAttributes(subscriptionAttributesRequest);

                // Initialize SNS extended client
                // PayloadSizeThreshold triggers message content storage in S3 when the
                // threshold is exceeded
                // To store all messages content in S3, use AlwaysThroughS3 flag
                final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME)
                                .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD);
                final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient,
                                snsExtendedClientConfiguration);

                // Publish message via SNS with storage in S3
                final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above.";
                snsExtendedClient.publish(topicArn, message);

                // Initialize SQS extended client
                final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME);
                final AmazonSQSExtendedClient sqsExtendedClient = new AmazonSQSExtendedClient(sqsClient,
                                sqsExtendedClientConfiguration);

                // Read the message from the queue
                final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl);
                System.out.println("Received message is " + result.getMessages().get(0).getBody());
        }
}
```

## 其他端點通訊協定
<a name="large-payloads-other-protocols"></a>

Amazon SNS 和 Amazon SQS 函式庫都使用 [AWS的酬載卸載 Java 通用程式庫](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws)，以使用 Amazon S3 存放和擷取訊息酬載。任何啟用 Java 的端點 (例如，在 Java 中實作的 HTTPS 端點) 都可以使用相同的庫來解除參照消息內容。

無法使用適用於 的承載卸載 Java 通用程式庫的端點仍然 AWS 可以發佈訊息，其中包含存放在 Amazon S3 中的承載。以下是上述代碼範例發布的 Amazon S3 參考範例：

```
[
  "software.amazon.payloadoffloading.PayloadS3Pointer",
  {
    "s3BucketName": "extended-client-bucket",
    "s3Key": "xxxx-xxxxx-xxxxx-xxxxxx"
  }
]
```

# 適用於 Python 的 Amazon SNS 擴充用戶端程式庫
<a name="extended-client-library-python"></a>

## 先決條件
<a name="prereqs-sns-extended-client-library-python"></a>

下列是使用[適用於 Java 的 Amazon SNS 擴充用戶端程式庫](https://github.com/awslabs/amazon-sns-python-extended-client-lib)的先決條件：
+  AWS 開發套件。本頁面上的範例使用 AWS Python SDK Boto3。若要安裝和設定 SDK，請參閱 [https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 說明文件。
+  AWS 帳戶 具有適當登入資料的 。若要建立 AWS 帳戶，請導覽至 [AWS 首頁](https://aws.amazon.com/)，然後選擇**建立 AWS 帳戶**。遵循指示。

  如需憑證的資訊，請參閱 *AWS SDK for Python 開發人員指南* 中的[憑證](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)。
+ Python 3.x (或更高版本) 和 pip。
+ 適用於 Python 的 Amazon SNS 擴充用戶端程式庫(也可從 [PyPI](https://pypi.org/project/amazon-sns-extended-client/) 取得)。

## 設定訊息儲存
<a name="large-message-configure-storage-python"></a>

下列屬性可在 Boto3 Amazon SNS [用戶端](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#client)、[主題](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/topic/index.html)和[PlatformEndPoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/platformendpoint/index.html) 物件上使用，以設定 Amazon S3 訊息儲存選項。
+ **`large_payload_support`** – 將存放大型訊息的 Amazon S3 儲存貯體名稱。
+ **`use_legacy_attribute`** – 如果為 `True`，則所有發佈的訊息都會使用舊版預留訊息屬性 (`SQSLargePayloadSize`)，而不是目前的預留訊息屬性 (`ExtendedPayloadSize`)。
+ **`message_size_threshold`** – 將郵件儲存在大型訊息儲存貯體中的臨界值。不能小於 `0`，或大於 `262144`。預設值為 `262144`。
+ **`always_through_s3`** – 如果是`True`，則所有訊息都存放在 Amazon S3 中。預設值為 `False`。
+ **`s3_client`** – 用來將`client`物件存放至 Amazon S3 的 Boto3 Amazon S3 物件。如果您想要控制 Amazon S3 用戶端 （例如，自訂 Amazon S3 組態或登入資料），請使用此選項。如果先前未設定，則第一次使用`boto3.client("s3")`時預設為 。

## 範例：將訊息發布到 Amazon SNS，其中儲存在 Amazon S3 中的有效酬載
<a name="example-s3-large-payloads-python"></a>

以下程式碼範例顯示做法：
+ 建立範例 Amazon SNS 主題和 Amazon SQS 佇列。
+ 將政策連接至 Amazon SQS 佇列，以接收來自 Amazon SNS 主題的訊息。
+ 訂閱佇列以接收來自主題的訊息。
+ 使用 Amazon SNS 延伸用戶端、主題資源和 PlatformEndpoint 資源發佈測試訊息。
+ 訊息酬載儲存在 Amazon S3 中，並發布對該訊息的參考。
+ 列印佇列中已發布的訊息以及從 Amazon S3 擷取的原始訊息。

若要發布大型訊息，請使用適用於 Python 的 Amazon SNS 擴充用戶端程式庫。您傳送的訊息會參考包含實際訊息內容的 Amazon S3 物件。

```
import boto3
from sns_extended_client import SNSExtendedClientSession
from json import loads

s3_extended_payload_bucket = "extended-client-bucket-store"  # S3 bucket with the given bucket name is a resource which is created and accessible with the given AWS credentials
TOPIC_NAME = "---TOPIC-NAME---"
QUEUE_NAME = "---QUEUE-NAME---"

def allow_sns_to_write_to_sqs(topicarn, queuearn):
    policy_document = """{{
        "Version": "2012-10-17",		 	 	 
        "Statement":[
            {{
            "Sid":"MyPolicy",
            "Effect":"Allow",
            "Principal" : {{"AWS" : "*"}},
            "Action":"SQS:SendMessage",
            "Resource": "{}",
            "Condition":{{
                "ArnEquals":{{
                "aws:SourceArn": "{}"
                }}
            }}
            }}
        ]
        }}""".format(queuearn, topicarn)

    return policy_document

def get_msg_from_s3(body,sns_extended_client):
    """Handy Helper to fetch message from S3"""
    json_msg = loads(body)
    s3_object = sns_extended_client.s3_client.get_object(
        Bucket=json_msg[1].get("s3BucketName"), Key=json_msg[1].get("s3Key")
    )
    msg = s3_object.get("Body").read().decode()
    return msg


def fetch_and_print_from_sqs(sqs, queue_url,sns_extended_client):
    sqs_msg = sqs.receive_message(
        QueueUrl=queue_url,
        AttributeNames=['All'],
        MessageAttributeNames=['All'],
        VisibilityTimeout=0,
        WaitTimeSeconds=0,
        MaxNumberOfMessages=1
    ).get("Messages")[0]
    
    message_body = sqs_msg.get("Body")
    print("Published Message: {}".format(message_body))
    print("Message Stored in S3 Bucket is: {}\n".format(get_msg_from_s3(message_body,sns_extended_client)))

    # Delete the Processed Message
    sqs.delete_message(
        QueueUrl=queue_url,
        ReceiptHandle=sqs_msg['ReceiptHandle']
    )


sns_extended_client = boto3.client("sns", region_name="us-east-1")
create_topic_response = sns_extended_client.create_topic(Name=TOPIC_NAME)
sns_topic_arn = create_topic_response.get("TopicArn")

# create and subscribe an sqs queue to the sns client
sqs = boto3.client("sqs",region_name="us-east-1")
demo_queue_url = sqs.create_queue(QueueName=QUEUE_NAME).get("QueueUrl")
sqs_queue_arn = sqs.get_queue_attributes(
    QueueUrl=demo_queue_url, AttributeNames=["QueueArn"]
)["Attributes"].get("QueueArn")

# Adding policy to SQS queue such that SNS topic can send msg to SQS queue
policy_json = allow_sns_to_write_to_sqs(sns_topic_arn, sqs_queue_arn)
response = sqs.set_queue_attributes(
    QueueUrl = demo_queue_url,
    Attributes = {
        'Policy' : policy_json
    }
)

# Set the RawMessageDelivery subscription attribute to TRUE if you want to use
# SQSExtendedClient to help with retrieving msg from S3
sns_extended_client.subscribe(TopicArn=sns_topic_arn, Protocol="sqs", 
Endpoint=sqs_queue_arn
, Attributes={"RawMessageDelivery":"true"}
)

sns_extended_client.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of sns_extended_client to use 'us-east-1' region
sns_extended_client.s3_client = boto3.client("s3", region_name="us-east-1")


# Below is the example that all the messages will be sent to the S3 bucket
sns_extended_client.always_through_s3 = True
sns_extended_client.publish(
    TopicArn=sns_topic_arn, Message="This message should be published to S3"
)
print("\n\nPublished using SNS extended client:")
fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3

# Below is the example that all the messages larger than 32 bytes will be sent to the S3 bucket
print("\nUsing decreased message size threshold:")

sns_extended_client.always_through_s3 = False
sns_extended_client.message_size_threshold = 32
sns_extended_client.publish(
    TopicArn=sns_topic_arn,
    Message="This message should be published to S3 as it exceeds the limit of the 32 bytes",
)

fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3


# Below is the example to publish message using the SNS.Topic resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

topic = sns_extended_client_resource.Topic(sns_topic_arn)
topic.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of topic to use 'us-east-1' region
topic.s3_client = boto3.client("s3", region_name="us-east-1")

topic.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
topic.publish(
    Message="This message should be published to S3 using the topic resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "347c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using Topic Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,topic)

# Below is the example to publish message using the SNS.PlatformEndpoint resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

platform_endpoint = sns_extended_client_resource.PlatformEndpoint(sns_topic_arn)
platform_endpoint.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of platform_endpoint to use 'us-east-1' region
platform_endpoint.s3_client = boto3.client("s3", region_name="us-east-1")

platform_endpoint.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
platform_endpoint.publish(
    Message="This message should be published to S3 using the PlatformEndpoint resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "247c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using PlatformEndpoint Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,platform_endpoint)
```

**輸出**

```
Published using SNS extended client:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3

Using decreased message size threshold:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 as it exceeds the limit of the 32 bytes

Published using Topic Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the topic resource

Published using PlatformEndpoint Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the PlatformEndpoint resource
```

# Amazon SNS 訊息屬性
<a name="sns-message-attributes"></a>

Amazon SNS 支援傳遞訊息屬性，可讓您提供與訊息相關的結構化中繼資料項目 (例如時間戳記、地理空間資料、簽章及識別符)。啟用[原始訊息交付](sns-large-payload-raw-message-delivery.md)以後，針對 SQS 訂閱最多可傳送 10 個訊息屬性。如要傳送超過 10 個訊息屬性，則必須停用原始訊息交付。具有 10 個以上訊息屬性且導向已啟用「原始訊息交付」的 Amazon SQS 訂閱的訊息，將會因用戶端錯誤而遭到捨棄。

訊息屬性為選用且與訊息內文分開，但與訊息內文一起傳送。接收者可以使用這項資訊來決定如何處理訊息，而不必先處理訊息內文。

如需使用 AWS 管理主控台 或 以屬性傳送訊息的詳細資訊 適用於 Java 的 AWS SDK，請參閱 [使用 將訊息發佈至 Amazon SNS 主題 AWS 管理主控台](sns-publishing.md#sns-publishing-messages)教學課程。

**注意**  
只有在訊息結構是字串而非 JSON 時，才會傳送訊息屬性。

您也可以使用訊息屬性來協助結構化行動裝置端點的推送通知訊息。在此情況下，訊息屬性只會用來協助結構化推送通知訊息。屬性不會交付到端點，與搭配訊息屬性將訊息傳送到 Amazon SQS 端點時不同。

您也可以使用訊息屬性，讓您的訊息可透過使用訂閱篩選政策進行篩選。您可以將篩選政策套用到主題訂閱。以設為 `MessageAttributes` (預設) 的篩選政策範圍套用篩選政策時，訂閱只會接收到擁有政策所接受屬性的訊息。如需詳細資訊，請參閱[Amazon SNS 訊息篩選](sns-message-filtering.md)。

**注意**  
使用訊息屬性進行篩選時，值必須是有效的 JSON 字串。這樣做可確保訊息傳遞至已啟用訊息屬性篩選的訂閱。

## 訊息屬性項目和驗證
<a name="SNSMessageAttributesNTV"></a>

每項訊息屬性均是由以下項目組成：
+ **Name** - 訊息屬性名稱可包含下列字元：A-Z、a-z、0-9、底線 (\$1)、連字號 (-) 和句號 (.)。名稱不能以句號開頭或結尾，且不可連續使用句號。名稱會區分大小寫，且不能與訊息的其他所有屬性名稱重複。名稱長度上限為 256 個字元。名稱無法以 `AWS.` 或 `Amazon.` (或任何外殼的變體) 開頭，因為這類字首會預訂給 Amazon Web Services 使用。
+ **類型** - 支援的訊息屬性資料類型為 `String`、`String.Array`、`Number` 和 `Binary`。資料類型內容上的限制與訊息內文相同。如需詳細資訊，請參閱 [訊息屬性資料類型和驗證](#SNSMessageAttributes.DataTypes) 一節。
+ **數值** - 使用者指定的訊息屬性數值。對於字串資料類型，值屬性必須遵循與訊息內文相同的內容限制。不過，如果訊息屬性用於篩選，則值必須是有效的 JSON 字串，以確保與 Amazon SNS 訂閱篩選政策的相容性。如需詳細資訊，請參閱 *Amazon Simple Notification Service API 參考*中 [Publish](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) (發佈) 動作。

名稱、類型和值不能為空或 null。此外，訊息本文不能為空或 null。訊息屬性的所有部分，包括名稱、類型和值，均包含在訊息大小限制中，目前限制為 256 KB。

## 訊息屬性資料類型和驗證
<a name="SNSMessageAttributes.DataTypes"></a>

訊息屬性資料類型可識別 Amazon SNS 如何處理訊息屬性的值。例如，如果類型為數字，Amazon SNS 會驗證其是否為數字。

Amazon SNS 支援下列所有端點的邏輯資料類型，除非另有說明：
+ **字串** - 字串為 UTF-8 二進位編碼的 Unicode。如需代碼值的清單，請參閱 [http://en.wikipedia.org/wiki/ASCII\$1ASCII\$1printable\$1characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters)。
**注意**  
訊息屬性不支援代理值。例如，使用代理值來表示表情符號會出現以下錯誤：`Invalid attribute value was passed in for message attribute`。
+ **String.Array** - 格式化為字串的陣列，可包含多個值。值可以是字串、數字或關鍵字 `true`、`false` 和 `null`。數字或布林值類型的 String.Array 不需要引號。以逗號分隔的多個 String.Array 值。

   AWS Lambda 訂閱不支援此資料類型。如果您為 Lambda 端點指定此資料類型，則會以 `String` 資料類型中，Amazon SNS 提供給 Lambda 的 JSON 酬載傳遞。
+ **數字** - 數字為正負整數或浮點數字。數字需有足夠的範圍和精準度，方可涵蓋大多數整數、浮點數、雙精度浮點數一般支援的可能數值。一數字的值可從 -109 至 109，準確度到包含小數點後的 5 位數。前後的零會截去。

   AWS Lambda 訂閱不支援此資料類型。如果您為 Lambda 端點指定此資料類型，則會以 `String` 資料類型中，Amazon SNS 提供給 Lambda 的 JSON 酬載傳遞。
+ **二進位** - 二進位類型屬性可儲存任何二進位資料；例如壓縮資料、加密資料或影像。

## 為行動推播通知保留的訊息屬性
<a name="sns-attrib-mobile-reserved"></a>

下表列出為行動推播通知服務 (您可用來結構化您的推播通知訊息) 保留的訊息屬性：

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sns/latest/dg/sns-message-attributes.html)

1 如果訊息屬性不符合其需求，Apple 將拒絕 Amazon SNS 通知。如需其他詳細資訊，請參閱 Apple 開發人員網站上的[傳送通知請求至 APN](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns)。

# Amazon SNS 訊息批次處理
<a name="sns-batch-api-actions"></a>

## 什麼是訊息批次處理？
<a name="what-is-message-batching"></a>

在單一 `Publish` API 請求中，將訊息發佈至標準或 FIFO 主題的替代方案，在使用 Amazon SNS `PublishBatch` API 於單一 API 請求中發佈多達 10 則訊息。批次傳送訊息可協助您降低與使用 Amazon SNS 連線分散式應用程式 ([A2A 訊息](sns-system-to-system-messaging.md)) 或將通知傳送給人員 ([A2P 訊息](sns-user-notifications.md)) 相關聯的成本，降低成本的倍數高達 10 倍。Amazon SNS 會根據您的營運區域，針對每秒可發佈到主題的訊息數量提供配額。如需 API 配額的詳細資訊，請參閱《AWS 一般參考指南》**中的 [Amazon SNS 端點和配額](https://docs.aws.amazon.com/general/latest/gr/sns.html)頁面。

**注意**  
您在單一 `PublishBatch` API 請求中傳送的所有訊息的總彙總大小不得超過 262，144 位元組 (256 KiB)。  
該 `PublishBatch` API 對 IAM 政策使用相同的 `Publish` API 動作。

## 訊息批次處理如何運作？
<a name="message-batching-how-it-works"></a>

使用 `PublishBatch` API 發佈訊息類似於使用 `Publish` API 發佈訊息。主要區別在於 `PublishBatch` API 請求中的每個訊息需獲得所指派的唯一批次 ID (最多 80 個字元)。如此一來，Amazon SNS 可以針對批次中的每個訊息傳回個別 API 回應，以確認已發佈每個訊息或發佈失敗。對於發佈到 FIFO 主題的訊息，除了包含指派唯一批次 ID 之外，您還需要包含每個訊息的 `MessageDeduplicationID` 和 `MessageGroupId`。

## 範例
<a name="message-batching-examples"></a>

**將 10 則訊息的批次發佈至標準主題**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToTopic(SnsClient snsClient, String topicArn, int batchSize) {
    try {
        // Validate the batch size
        if (batchSize > MAX_BATCH_SIZE) {
            throw new IllegalArgumentException("Batch size cannot exceed " + MAX_BATCH_SIZE);
        }

        // Create the batch entries
        List<PublishBatchRequestEntry> entries = IntStream.range(0, batchSize)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .build())
                .collect(Collectors.toList());

        // Build the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle successful messages
        response.successful().forEach(success -> {
            System.out.println("Successful Batch Id: " + success.id());
            System.out.println("Message Id: " + success.messageId());
        });

        // Handle failed messages
        response.failed().forEach(failure -> {
            System.err.println("Failed Batch Id: " + failure.id());
            System.err.println("Error Code: " + failure.code());
            System.err.println("Sender Fault: " + failure.senderFault());
            System.err.println("Error Message: " + failure.message());
        });

    } catch (SnsException e) {
        // Log and handle exceptions
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    } catch (IllegalArgumentException e) {
        System.err.println("Validation Error: " + e.getMessage());
    }
}
```

**將 10 則訊息的批次發佈至 FIFO 主題**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.BatchResultErrorEntry;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToFifoTopic(SnsClient snsClient, String topicArn) {
    try {
        // Create the batch entries to send
        List<PublishBatchRequestEntry> entries = IntStream.range(0, MAX_BATCH_SIZE)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .messageGroupId("groupId")
                        .messageDeduplicationId("deduplicationId" + i)
                        .build())
                .collect(Collectors.toList());

        // Create the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle the successfully sent messages
        response.successful().forEach(success -> {
            System.out.println("Batch Id for successful message: " + success.id());
            System.out.println("Message Id for successful message: " + success.messageId());
            System.out.println("Sequence Number for successful message: " + success.sequenceNumber());
        });

        // Handle the failed messages
        response.failed().forEach(failure -> {
            System.err.println("Batch Id for failed message: " + failure.id());
            System.err.println("Error Code for failed message: " + failure.code());
            System.err.println("Sender Fault for failed message: " + failure.senderFault());
            System.err.println("Failure Message for failed message: " + failure.message());
        });

    } catch (SnsException e) {
        // Handle any exceptions from the request
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    }
}
```

# 刪除 Amazon SNS 主題和訂閱
<a name="sns-delete-subscription-topic"></a>

刪除主題時，會以非同步方式刪除其相關聯的訂閱。雖然客戶仍然可以存取這些訂閱，但即使您使用相同名稱重新建立主題，訂閱也不再與主題相關聯。如果發佈者嘗試發佈訊息到已刪除的主題，發佈者會收到錯誤訊息，指出主題不存在。同樣地，只要嘗試訂閱已刪除的主題也會產生錯誤訊息。您無法刪除正在進行確認的訂閱。Amazon SNS 會在 48 小時後自動刪除未確認的訂閱，但電子郵件訂閱會在 30 天後刪除。

**重要**  
 已刪除的 Amazon SNS 主題無法復原。建議您先刪除訂閱，再刪除主題。  
 一旦刪除訂閱，就無法復原。發佈到 Amazon SNS 主題的通知將不會交付至該已刪除的訂閱。您必須重新建立訂閱才能接收通知。

## 使用 刪除 Amazon SNS 主題或訂閱 AWS 管理主控台
<a name="sns-delete-subscription-topic-console"></a>

刪除 Amazon SNS 主題或訂閱可確保有效的資源管理、防止不必要的使用，並保持 Amazon SNS 主控台井然有序。此步驟有助於避免閒置資源的潛在成本，並透過移除不再需要的主題或訂閱來簡化管理。

**使用 刪除主題 AWS 管理主控台**

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在左側導覽窗格中，選擇 **Topics** (主題)。

1. 在 **Topics** (主題) 頁面上，選取主題，然後選擇 **Edit** (編輯)。

1. 在 **Delete topic** (刪除主題) 對話方塊中輸入 `delete me`，然後選擇 **Delete** (刪除)。

   主控台刪除主題。

**使用 刪除訂閱 AWS 管理主控台**

1. 登入 [Amazon SNS 主控台](https://console.aws.amazon.com/sns/home)。

1. 在左導覽窗格中，選擇**訂閱**。

1. 在**訂閱**頁面上，選取狀態為**已確認**的訂閱，然後選擇**刪除**。

1. 在 **Delete subscription** (刪除訂閱) 對話方塊中，選擇 **Delete** (刪除)。

   主控台刪除訂閱。

## 使用 AWS SDK 刪除訂閱和主題
<a name="delete-topic-aws-sdks"></a>

若要使用 AWS SDK，您必須使用登入資料進行設定。如需詳細資訊，請參閱 *AWS SDK和工具參考指南*中的[共享的配置和認證文件](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)。

下列程式碼範例示範如何使用 `DeleteTopic`。

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)中設定和執行。
藉由主題 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](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/DeleteTopic)。

------
#### [ C\$1\$1 ]

**適用於 C\$1\$1 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中設定和執行。

```
//! 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\$1\$1 的 AWS SDK API 參考》**中的 [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/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](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/delete-topic.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)中設定和執行。

```
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](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.DeleteTopic)。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中設定和執行。

```
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](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/DeleteTopic)。

------
#### [ JavaScript ]

**適用於 JavaScript (v3) 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)中設定和執行。
在單獨的模組中建立用戶端並將其匯出。  

```
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
  //   }
  // }
};
```
+  如需詳細資訊，請參閱[《適用於 JavaScript 的 AWS SDK 開發人員指南》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-deletetopic)。
+  如需 API 詳細資訊，請參閱《適用於 JavaScript 的 AWS SDK API 參考》**中的 [DeleteTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/DeleteTopicCommand)。

------
#### [ Kotlin ]

**適用於 Kotlin 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中設定和執行。

```
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 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》[https://sdk.amazonaws.com/kotlin/api/latest/index.html](https://sdk.amazonaws.com/kotlin/api/latest/index.html)中的 *DeleteTopic*。

------
#### [ PHP ]

**適用於 PHP 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中設定和執行。

```
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](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/DeleteTopic)。

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中設定和執行。

```
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 詳細資訊，請參閱 *AWS SDK for Python (Boto3) API 參考*中的 [DeleteTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/DeleteTopic)。

------
#### [ SAP ABAP ]

**適用於 SAP ABAP 的開發套件**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中設定和執行。

```
    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 詳細資訊，請參閱《適用於 Kotlin 的AWS SDK API 參考》**中的 [DeleteTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------
#### [ Swift ]

**適用於 Swift 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)中設定和執行。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        _ = try await snsClient.deleteTopic(
            input: DeleteTopicInput(topicArn: arn)
        )
```
+  如需 API 詳細資訊，請參閱《適用於 Swift 的AWS SDK API 參考》**中的 [DeleteTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/deletetopic(input:))。

------

# 後續步驟
<a name="sns-next-steps-getting-started"></a>

現在您已經建立有訂閱的主題，並已將訊息傳送到主題，您可以再試試下列各項：
+ 探索 [AWS 開發人員中心](https://aws.amazon.com/developer/)。
+ 請至[安全性](security.md)章節了解如何保護您的資料。
+ 對主題啟用[伺服器端加密](sns-enable-encryption-for-topic.md)。
+ 對已訂閱的[加密 Amazon Simple Queue Service (Amazon SQS) 佇列](sns-enable-encryption-for-topic-sqs-queue-subscriptions.md)主題啟用伺服器端加密。
+ 訂閱 [AWS 事件分叉管道](sns-subscribe-event-fork-pipelines.md)主題。