

 [AWS SDK for JavaScript V3 API リファレンスガイド](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)では、 AWS SDK for JavaScript バージョン3 (V3) のすべての API オペレーションについて詳しく説明します。

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

# Amazon SNS の SMS メッセージの送信
<a name="sns-examples-sending-sms"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**この Node.js コード例は以下を示しています。**
+ Amazon SNS の SMS メッセージングの設定を取得および設定する方法。
+ 電話番号をチェックして SMS メッセージの受信をオプトアウトしたかどうかを確認する方法。
+ SMS メッセージの受信をオプトアウトした電話番号のリストを取得する方法。
+ SMS メッセージを送信する方法。

## シナリオ
<a name="sns-examples-sending-sms-scenario"></a>

Amazon SNS を使用して、SMS 対応デバイスにテキストメッセージ (SMS メッセージ) を送信できます。電話番号をトピックにサブスクライブし、トピックへメッセージを送信することにより、電話番号へメッセージを直接送信または、一度に複数の電話番号にメッセージを送信できます。

この例では、一連の Node.js モジュールを使用して、Amazon SNS から SMS 対応デバイスに SMS テキストメッセージを発行します。Node.js モジュールは SDK for JavaScript を使用し、`SNS` クライアントクラスの以下のメソッドを使用して SMS メッセージを発行します。
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 前提条件タスク
<a name="sns-examples-sending-sms-prerequisites"></a>

この例をセットアップして実行するには、まず次のタスクを完了する必要があります。
+ これらの Node TypeScript の例を実行するようにプロジェクト環境を設定し、必要な AWS SDK for JavaScript モジュールとサードパーティーモジュールをインストールします。「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)」の指示に従います。
+ ユーザーの認証情報を使用して、共有設定ファイルを作成します。共有認証情報ファイルの提供の詳細については、「*AWS SDK とツールのリファレンスガイド*」の「[共有設定ファイルおよび認証情報ファイル](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)」を参照してください。

**重要**  
これらの例は、ECMAScript6 (ES6) を使用してクライアントサービスオブジェクトとコマンドをimport/export する方法を示します。  
これには Node.js バージョン13.x以降が必要です。Node.js の最新バージョンをダウンロードしてインストールするには、「[Node.js ダウンロード](https://nodejs.org/en/download)」を参照してください。
CommonJS 構文を使用する場合は、「[JavaScript ES6/CommonJS 構文](sdk-example-javascript-syntax.md)」を参照してください。

## SMS 属性の取得
<a name="sending-sms-getattributes"></a>

Amazon SNS を使用して、配信の最適化の方法 (コストに対してか、確実な配信に対してか)、毎月の使用量の上限、メッセージ配信がログに記録される方法、SMS の毎日の使用状況レポートをサブスクライブするかどうかなど、SMS メッセージのプリファレンスを指定します。これらのプリファレンスが取得され、Amazon SNS の SMS 属性として設定されます。

この例では、Node.js モジュールを使用して Amazon SNS の現在の SMS 属性を取得します。

`libs`ディレクトリを作成し、ファイル名`snsClient.js`でNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。*REGION* を自分の AWS リージョンに置き換えます。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

 `get-sms-attributes.js`というファイル名で Node.js モジュールを作成します。

前述のように、必要なクライアントとパッケージのダウンロードを含め、SDKを設定します。取得する個々の属性の名前など、SMS 属性を取得するためのパラメータを含むオブジェクトを作成します。利用可能な SMS 属性の詳細については、Amazon Simple Notification Service API リファレンスの [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html) を参照してください。

この例では、`DefaultSMSType` 属性を取得します。これは、SMS メッセージが `Promotional` (コストが最も低くなるようにメッセージ配信が最適化されます) として送信されるのか、`Transactional` (信頼性が最も高くなるようにメッセージ配信が最適化されます) として送信されるのかを制御します。`SNS` クライアントクラスの `SetTopicAttributesCommand` メソッドにパラメータを渡します。`SetSMSAttributesCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
*ATTRIBUTE\$1NAME*を属性の名前に置き換えてください。

```
import { GetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const getSmsAttributes = async () => {
  const response = await snsClient.send(
    // If you have not modified the account-level mobile settings of SNS,
    // the DefaultSMSType is undefined. For this example, it was set to
    // Transactional.
    new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   attributes: { DefaultSMSType: 'Transactional' }
  // }
  return response;
};
```

この例を実行するには、コマンドプロンプトで以下を入力します。

```
node get-sms-attributes.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-sms-attributes.js)で見つけられます。

## SMS 属性の設定
<a name="sending-sms-setattributes"></a>

この例では、Node.js モジュールを使用して Amazon SNS の現在の SMS 属性を取得します。

`libs`ディレクトリを作成し、ファイル名`snsClient.js`でNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。*REGION* を自分の AWS リージョンに置き換えます。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

 `set-sms-attribute-type.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。設定する個々の属性の名前とそれぞれに設定する値を含む、SMS 属性を設定するためのパラメータを含むオブジェクトを作成します。利用可能な SMS 属性の詳細については、Amazon Simple Notification Service API リファレンスの [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html) を参照してください。

この例では、`DefaultSMSType` 属性を `Transactional` に設定します。これにより、信頼性が最も高くなるようにメッセージ配信が最適化されます。`SNS` クライアントクラスの `SetTopicAttributesCommand` メソッドにパラメータを渡します。`SetSMSAttributesCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

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

この例を実行するには、コマンドプロンプトで以下を入力します。

```
node set-sms-attribute-type.js 
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js)で見つけられます。

## 電話番号がオプトアウトしているかどうかの確認
<a name="sending-sms-checkifphonenumberisoptedout"></a>

この例では、Node.js モジュールを使用して電話番号をチェックし、SMS メッセージの受信をオプトアウトしたかどうかを確認します。

`libs`ディレクトリを作成し、ファイル名`snsClient.js`でNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。*REGION* を自分の AWS リージョンに置き換えます。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

`check-if-phone-number-is-opted-out.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。パラメータとして確認する電話番号を含むオブジェクトを作成します。

この例では、確認する電話番号を指定するために `PhoneNumber` パラメータを設定します。`SNS` クライアントクラスの `CheckIfPhoneNumberIsOptedOutCommand` メソッドにオブジェクトを渡します。`CheckIfPhoneNumberIsOptedOutCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  

*PHONE\$1NUMBER* を電話番号に置き換えてください。

```
import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns";

import { snsClient } from "../libs/snsClient.js";

export const checkIfPhoneNumberIsOptedOut = async (
  phoneNumber = "5555555555",
) => {
  const command = new CheckIfPhoneNumberIsOptedOutCommand({
    phoneNumber,
  });

  const response = await snsClient.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   isOptedOut: false
  // }
  return response;
};
```

この例を実行するには、コマンドプロンプトで以下を入力します。

```
node check-if-phone-number-is-opted-out.js 
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js)で見つけられます。

## オプトアウトした電話番号の一覧表示
<a name="sending-sms-listphonenumbersoptedout"></a>

この例では、Node.js モジュールを使用して、SMS メッセージの受信からオプトアウトされた電話番号のリストを取得します。

`libs`ディレクトリを作成し、ファイル名`snsClient.js`でNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。*REGION* を自分の AWS リージョンに置き換えます。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

`list-phone-numbers-opted-out.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。空のオブジェクトをパラメータとして作成します。

`SNS` クライアントクラスの `ListPhoneNumbersOptedOutCommand` メソッドにオブジェクトを渡します。`ListPhoneNumbersOptedOutCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

```
import { ListPhoneNumbersOptedOutCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listPhoneNumbersOptedOut = async () => {
  const response = await snsClient.send(
    new ListPhoneNumbersOptedOutCommand({}),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '44ff72fd-1037-5042-ad96-2fc16601df42',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   phoneNumbers: ['+15555550100']
  // }
  return response;
};
```

この例を実行するには、コマンドプロンプトで以下を入力します。

```
node list-phone-numbers-opted-out.js 
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js)で見つけられます。

## SMS メッセージの発行
<a name="sending-sms-publishsms"></a>

この例では、Node.js モジュールを使用して SMS メッセージを電話番号に送信します。

`libs`ディレクトリを作成し、ファイル名`snsClient.js`でNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。*REGION* を自分の AWS リージョンに置き換えます。

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

`publish-sms.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。`Message` および `PhoneNumber` パラメータを含むオブジェクトを作成します。

SMS メッセージを送信するときは、E.164 形式を使用して電話番号を指定します。E.164 は、国際的な音声通信に使用される電話番号の構造の規格です。この形式に従う電話番号には最大 15 桁を設定でき、プラス記号 (\$1) および国コードのプレフィックスがついています。たとえば、E.164 形式の米国の電話番号は \$11001XXX5550100 として表示されます。

この例では、メッセージを送信するための電話番号を指定する `PhoneNumber` パラメータを設定します。`SNS` クライアントクラスの `PublishCommand` メソッドにオブジェクトを渡します。`PublishCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
*TEXT\$1MESSAGE*をテキストメッセージに、*PHONE\$1NUMBER*を電話番号に置き換えてください。

```
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 {*} phoneNumber - The phone number to send the message to.
 */
export const publish = async (
  message = "Hello from SNS!",
  phoneNumber = "+15555555555",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      // One of PhoneNumber, TopicArn, or TargetArn must be specified.
      PhoneNumber: phoneNumber,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '7410094f-efc7-5f52-af03-54737569ab77',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

この例を実行するには、コマンドプロンプトで以下を入力します。

```
node publish-sms.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-sms.js)で見つけられます。