

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

# 在 Amazon SNS 中設定簡訊偏好設定
<a name="sms_preferences"></a>

使用 Amazon SNS 指定 SMS 訊息的偏好設定。例如，您可以指定是否針對成本或可靠性最佳化傳遞、您的每月花費限制、如何記錄傳遞，以及是否訂閱每日簡訊用量報告。

這些喜好設定會對您從帳戶傳送的每個簡訊生效，但是您可以在傳送個別訊息時覆寫部分設定。如需詳細資訊，請參閱[使用 Amazon SNS 將簡訊發佈到行動電話](sms_sending-overview.md#sms_publish-to-phone)。

## 使用 設定簡訊偏好設定 AWS 管理主控台
<a name="sms_preferences_console"></a>

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

1. 選擇一個[支援簡訊的區域](https://docs.aws.amazon.com/general/latest/gr/end-user-messaging.html)。

1. 在導覽面板上，選擇**行動**，然後選擇**簡訊 (SMS)**。

1. 在 **Mobile text messaging (SMS)** (行動裝置簡訊 (SMS)) 頁面上，於 **Text messaging preference** (簡訊喜好設定) 區段中，選擇 **Edit** (編輯)。

1. 在 **Edit text messaging preferences** (編輯簡訊喜好設定) 頁面上，在 **Details** (詳細資訊) 中，執行以下作業：

   1. 針對 **Default message type** (預設訊息類型)，選擇以下其中一個項目：
      + **行銷活動** - 非關鍵訊息 (例如行銷)。Amazon SNS 會將訊息傳遞最佳化為產生最低的成本。
      + **交易** (預設) - 支援客戶交易的重要訊息，例如多重要素驗證用的一次性密碼。Amazon SNS 會將訊息傳遞最佳化為達成最高的可靠性。

      如需有關宣傳和交易訊息的定價資訊，請參閱[全球簡訊定價](https://aws.amazon.com/sns/sms-pricing/)。

   1. (選用) 針對 **Account spend limit** (帳戶費用限制)，請輸入您每個月要花費在簡訊上的金額上限 (單位為 USD)。
**重要**  
根據預設，費用配額會設為 1.00 USD。如果您想要提高服務配額，[請提交請求](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-sns)。
若主控台中設定的金額超過您的服務配額，Amazon SNS 會停止發布簡訊。
因為 Amazon SNS 是分散式的系統，它會在超過費用配額的數分鐘內停止傳送簡訊。在此間隔期間，若您繼續傳送簡訊，您可能會產生超過您配額的成本。

1. (選用) 針對 **Default sender ID** (預設寄件者 ID)，輸入自訂 ID (例如您的商業品牌)，該 ID 會顯示為接收裝置的寄件者。
**注意**  
寄件者 ID 的支援情況會因國家或區域而不同。

1. (選用) 輸入**Amazon S3 儲存貯體用量報告名稱**。
**注意**  
Amazon S3 儲存貯體政策必須授予 Amazon SNS 的寫入存取權。

1. 選擇**儲存變更**。

## 設定偏好設定AWS SDKs)
<a name="sms_preferences_sdk"></a>

若要使用其中一個 AWS SDKs 設定您的 SMS 偏好設定，請使用該 SDK 中對應至 Amazon SNS API 中`SetSMSAttributes`請求的動作。透過此請求，您可以指派值給不同簡訊屬性，例如您的每月費用配額以及您的預設簡訊類型 (促銷或交易)。如需所有 SMS 屬性，請參閱 *Amazon Simple Notification Service API 參考* 中的 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)。

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

------
#### [ 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)中設定和執行。
如何使用 Amazon SNS 設定 DefaultSMSType 屬性。  

```
//! Set the default settings for sending SMS messages.
/*!
  \param smsType: The type of SMS message that you will send by default.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::setSMSType(const Aws::String &smsType,
                             const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::SetSMSAttributesRequest request;
    request.AddAttributes("DefaultSMSType", smsType);

    const Aws::SNS::Model::SetSMSAttributesOutcome outcome = snsClient.SetSMSAttributes(
            request);

    if (outcome.IsSuccess()) {
        std::cout << "SMS Type set successfully " << std::endl;
    }
    else {
        std::cerr << "Error while setting SMS Type: '"
                  << outcome.GetError().GetMessage()
                  << "'" << std::endl;
    }

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

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

**AWS CLI**  
**若要設定簡訊屬性**  
下列 `set-sms-attributes` 範例會將簡訊的預設寄件者 ID 設定為 `MyName`。  

```
aws sns set-sms-attributes \
    --attributes DefaultSenderID=MyName
```
此命令不會產生輸出。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [SetSMSAttributes](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-sms-attributes.html)。

------
#### [ 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.SetSmsAttributesRequest;
import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse;
import software.amazon.awssdk.services.sns.model.SnsException;
import java.util.HashMap;

/**
 * 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 SetSMSAttributes {
    public static void main(String[] args) {
        HashMap<String, String> attributes = new HashMap<>(1);
        attributes.put("DefaultSMSType", "Transactional");
        attributes.put("UsageReportS3Bucket", "janbucket");

        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        setSNSAttributes(snsClient, attributes);
        snsClient.close();
    }

    public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) {
        try {
            SetSmsAttributesRequest request = SetSmsAttributesRequest.builder()
                    .attributes(attributes)
                    .build();

            SetSmsAttributesResponse result = snsClient.setSMSAttributes(request);
            System.out.println("Set default Attributes to " + attributes + ". Status was "
                    + result.sdkHttpResponse().statusCode());

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

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

/**
 * @param {"Transactional" | "Promotional"} defaultSmsType
 */
export const setSmsType = async (defaultSmsType = "Transactional") => {
  const response = await snsClient.send(
    new SetSMSAttributesCommand({
      attributes: {
        // Promotional – (Default) Noncritical messages, such as marketing messages.
        // Transactional – Critical messages that support customer transactions,
        // such as one-time passcodes for multi-factor authentication.
        DefaultSMSType: defaultSmsType,
      },
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '1885b977-2d7e-535e-8214-e44be727e265',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```
+  如需詳細資訊，請參閱[《適用於 JavaScript 的 AWS SDK 開發人員指南》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-sending-sms.html#sending-sms-setattributes)。
+  如需 API 詳細資訊，請參閱 *適用於 JavaScript 的 AWS SDK API 參考*中的 [SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/SetSMSAttributesCommand)。

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

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

```
$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

try {
    $result = $SnSclient->SetSMSAttributes([
        'attributes' => [
            'DefaultSMSType' => 'Transactional',
        ],
    ]);
    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-sending-sms.html#set-sms-attributes)》。
+  如需 API 詳細資訊，請參閱 *適用於 PHP 的 AWS SDK API 參考*中的 [SetSMSAttributes](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/SetSMSAttributes)。

------

## 設定特定國家/地區交付的簡訊偏好設定
<a name="sms_preferences_country_specific"></a>

您可以僅將訊息傳送到特定目的地國家/地區，來管理和控制 SMS 流量。這可確保您的訊息只會傳送到核准的國家/地區，避免不必要的簡訊費用。下列指示使用 Amazon Pinpoint 的 Protect 組態來指定您要允許或封鎖的國家/地區。

1. 在 https：//[https://console.aws.amazon.com/sms-voice/](https://console.aws.amazon.com/sms-voice/) 開啟 AWS SMS 主控台。

1. 在導覽窗格的**概觀**下，於**快速入門**區段中，選擇**建立保護組態**。

1. 在**保護組態詳細資訊**下，輸入保護組態的**易用名稱 **（例如 Allow-Only-AU)。

1. 在**簡訊國家/地區規則**下，選取**區域/國家/地區**核取方塊，以封鎖傳送訊息至所有支援的國家/地區。

1. 取消選取您要傳送訊息的國家/地區的核取方塊。例如，若要僅允許傳送至澳洲的訊息，請取消選取**澳洲**的核取方塊。

1. 在**保護組態關聯**區段的**關聯類型**下，選取**帳戶預設**。這將確保 AWS End User Messaging SMS 保護組態會影響透過 Amazon SNS、[Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) 和 Amazon Pinpoint [https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-sms.html](https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-sms.html) API 呼叫傳送的所有訊息。

1. 選擇**建立保護組態**以儲存您的設定。

   隨即顯示下列確認訊息：

   ```
   Success Protect configuration protect-abc0123456789 has been created.
   ```

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

1. [**發佈訊息**](sns-publishing.md)到其中一個封鎖的國家/地區，例如印度。

   訊息將不會傳送。您可以使用 [CloudWatch](sms_stats_cloudwatch.md) 在交付失敗日誌中驗證這一點。搜尋日誌群組 **sns/region/AccountID/DirectPublishToPhoneNumber/Failure**，以取得類似下列範例的回應：

   ```
   {
   "notification": {
   "messageId": "bd59a509-XXXX-XXXX-82f8-fbdb8cb68217",
   "timestamp": "YYYY-MM-DD XX:XX:XX.XXXX“
   },
   "delivery": {
   "destination": "+91XXXXXXXXXX",
   "smsType": "Transactional",
   "providerResponse": "Cannot deliver message to the specified destination country",
   "dwellTimeMs": 85
   },
   "status": "FAILURE"
   }
   ```