

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 设置 Amazon SNS 中的短信收发首选项
<a name="sms_preferences"></a>

使用 Amazon SNS 指定 SMS 消息的首选项。例如，您可以指定是否要优化传输以确保成本或可靠性、您的每月支出限额、如何记录传输以及是否要订阅每日 SMS 使用情况报告。

这些首选项对从您的账户发送的每个 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. 选择[支持 SMS 消息收发的区域](https://docs.aws.amazon.com/general/latest/gr/end-user-messaging.html)。

1. 在导航面板上，选择**移动**，然后选择**文本消息(SMS)**。

1. 在**移动文本消息(SMS)** 页上，在**文本消息发送首选项**部分中，选择**编辑**。

1. 在 **Edit text messaging preferences (编辑文本消息发送首选项)** 页上，在 **Details (详细信息)** 部分中，执行以下操作：

   1. 对于**默认消息类型**，选择下列选项之一：
      + **促销**（默认）– 非重要消息（例如营销消息）。Amazon SNS 以产生最低成本为基准来优化消息传输。
      + **事务性**（默认）– 为客户事务处理提供支持的重要消息，例如多重身份验证的一次性密码。Amazon SNS 以实现最高可靠性为基准来优化消息传输。

      有关促销和事务处理消息的定价信息，请参阅[全球 SMS 定价](https://aws.amazon.com/sns/sms-pricing/)。

   1. （可选）对于 **Account spend limit (账户花费限额)**，请输入您在每个日历月想要为 SMS 消息支付的金额，以 USD 为单位。
**重要**  
默认情况下，支出配额设为 1.00 USD。如果要提高服务配额，[请提交请求](https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-sns)。
如果在控制台中设置的金额超过您的服务配额，Amazon SNS 会停止发布 SMS 消息。
由于 Amazon SNS 是分布式系统，它会在超过支出配额的几分钟内停止发送 SMS 消息。在该间隔内，如果您继续发送 SMS 消息，可能会产生超出配额的成本。

1. （可选）对于**默认发件人 ID**，请输入一个自定义 ID（如您的企业品牌），它显示为接收设备的发送者。
**注意**  
对发件人的支持因国家/地区 IDs 而异。

1. （可选）输入 **Amazon S3 bucket name for usage reports**（使用情况报告的 Amazon S3 存储桶名称）的名称。
**注意**  
Amazon S3 存储桶策略必须授予对 Amazon SNS 的写入权限。

1. 选择**保存更改**。

## 设置首选项 (AWS SDKs)
<a name="sms_preferences_sdk"></a>

要使用其中一个来设置您的短信偏好 AWS SDKs，请使用该软件开发工具包中与 Amazon SNS `SetSMSAttributes` API 中的请求相对应的操作。通过此请求，您可以将值分配给不同的 SMS 属性，例如您的每月支出配额和默认 SMS 类型（促销或事务）。有关所有短信属性，请参阅《*亚马逊简单通知服务 API 参考*》SMSAttributes中的 “[设置](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)”。

以下代码示例演示如何使用 `SetSMSAttributes`。

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

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。
如何使用 Amazon SNS 设置默认SMSType 属性。  

```
//! 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 参考SMSAttributes*中的[设置](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/SetSMSAttributes)。

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

**AWS CLI**  
**设置 SMS 消息属性**  
以下 `set-sms-attributes` 示例将 SMS 消息的默认发件人 ID 设置为 `MyName`。  

```
aws sns set-sms-attributes \
    --attributes DefaultSenderID=MyName
```
此命令不生成任何输出。  
+  有关 API 的详细信息，请参阅SMSAttributes《*AWS CLI 命令参考*》中的 [“设置](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/set-sms-attributes.html)”。

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

**适用于 Java 的 SDK 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 参考SMSAttributes*中的[设置](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/SetSMSAttributes)。

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

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 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 Developer Guide》](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-sending-sms.html#sending-sms-setattributes)。
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 AWS SDK API 参考SMSAttributes*中的[设置](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](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-sending-sms.html#set-sms-attributes)。
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 AWS SDK API 参考SMSAttributes*中的[设置](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/SetSMSAttributes)。

------

## 为特定于国家/地区的传送设置短信收发首选项
<a name="sms_preferences_country_specific"></a>

您可以通过仅向特定目标国家/地区发送消息来管理和控制短信流量。这样可以确保您的消息仅发送到经批准的国家/地区，从而避免不必要的短信费用。以下说明使用 Amazon Pinpoint 的保护配置来指定您想要允许或阻止的国家/地区。

1. 打开 AWS SMS 控制台，网址为[https://console.aws.amazon.com/sms-voice/](https://console.aws.amazon.com/sms-voice/)。

1. 在导航窗格的**概述**下的**快速入门**部分，选择**创建保护配置**。

1. 在 “**保护配置详细信息**” 下，为您的保护配置输入**适合企业使用的名称**（例如， Allow-Only-AU）。

1. 在**短信国家/地区规则**下，选中**地区/国家**复选框以阻止向所有支持的国家/地区发送消息。

1. 取消选中要将消息发送到的国家/地区的复选框。例如，要仅允许向澳大利亚发送消息，请取消选中**澳大利亚**对应的复选框。

1. 在**保护配置关联**部分的**关联类型**下，选择**账户默认**。这将确保 AWS End User Messaging SMS 保护配置影响通过亚马逊 SNS、Amazon Cogn [ito 和 Amazon](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html) Pinpoint API 调用发送的所有消息。[https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-sms.html](https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-sms.html)

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