

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

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

# Amazon Simple Notification Service の例
<a name="sns-examples"></a>

Amazon Simple Notification Service (Amazon SNS) は、サブスクライブしているエンドポイントまたはクライアントへのメッセージの配信または送信を調整して管理するウェブサービスです。

Amazon SNS には、発行者とサブスクライバーという 2 種類のクライアントが存在し、それぞれ生産者と消費者とも呼ばれます。

![\[JavaScript 環境、SDK、および Amazon SNS の関係\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/code-samples-sns.png)


発行者は、論理アクセスポイントおよび通信チャネルであるトピックにメッセージを作成して送信することで、受信者と非同期的に通信します。サブスクライバー (ウェブサーバー、E メールアドレス、Amazon SQS キュー、 AWS Lambda 関数) は、トピックにサブスクライブするときに、サポートされているプロトコル (Amazon SQS、HTTP/S、E メール、SMS AWS Lambda) のいずれかを介してメッセージまたは通知を消費または受信します。

Amazon SNS 用JavaScript API は[[ Class: SNS ]](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SNS/)を介して公開されます。

**Topics**
+ [Amazon SNS でのトピックの管理](sns-examples-managing-topics.md)
+ [Amazon SNS でのメッセージの公開](sns-examples-publishing-messages.md)
+ [Amazon SNS でのサブスクリプションの管理](sns-examples-subscribing-unsubscribing-topics.md)
+ [Amazon SNS の SMS メッセージの送信](sns-examples-sending-sms.md)

# Amazon SNS でのトピックの管理
<a name="sns-examples-managing-topics"></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 でトピックを作成する方法。
+ Amazon SNS で作成されたトピックを削除する方法。
+ 利用可能なトピックの一覧を取得する方法。
+ トピック属性を取得および設定する方法。

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

この例では、一連の Node.js モジュールを使用して Amazon SNS トピックを作成、一覧表示、および削除し、トピック属性を処理します。Node.js モジュールは、`SNS` クライアントクラスの以下のメソッドを使用してトピックを管理するために SDK for JavaScript を使用します。
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/)

## 前提条件タスク
<a name="sns-examples-managing-topics-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)」を参照してください。

## トピックの作成
<a name="sns-examples-managing-topics-createtopic"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックを作成します。

`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)で見つけられます。

`create-topic.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

`SNS` クライアントクラスの `CreateTopicCommand` メソッドに新しいトピックの `Name` を渡すためのオブジェクトを作成します。`CreateTopicCommand`メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。返された`data`には、トピックの ARN が含まれています。

**注記**  
*TOPIC\$1NAME*は、SNS トピックの名前に置換してください。

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

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

```
node create-topic.js
```

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

## トピックの一覧表示
<a name="sns-examples-managing-topics-listtopics"></a>

この例では、Node.js モジュールを使用してすべての Amazon SNS トピックを一覧表示します。

`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-topics.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

`SNS` クライアントクラスの `ListTopicsCommand` メソッドに渡す空のオブジェクトを作成します。`ListTopicsCommand`メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。返信された`data`には、トピックの Amazon リソースネーム (ARN)の配列が含まれています。

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

export const listTopics = async () => {
  const response = await snsClient.send(new ListTopicsCommand({}));
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ]
  // }
  return response;
};
```

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

```
node list-topics.js
```

 このサンプルコードは、[このGitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-topics.js)にあります。

## トピックの削除
<a name="sns-examples-managing-topics-deletetopic"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックを削除します。

`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)で見つけられます。

`delete-topic.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

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

**注記**  
*[ TOPIC\$1ARN ]*を削除するトピックの Amazon リソースネーム (ARN)に置換してください。

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

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

```
node delete-topic.js
```

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

## トピック属性の取得
<a name="sns-examples-managing-topicsgettopicattributes"></a>

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

`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-topic-attributes.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

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

**注記**  
返された*[ TOPIC\$1ARN ]*をトピックのARN に置換してください。

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

/**
 * @param {string} topicArn - The ARN of the topic to retrieve attributes for.
 */
export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new GetTopicAttributesCommand({
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Attributes: {
  //     Policy: '{...}',
  //     Owner: 'xxxxxxxxxxxx',
  //     SubscriptionsPending: '1',
  //     TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic',
  //     TracingConfig: 'PassThrough',
  //     EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy":{"headerContentType":"text/plain; charset=UTF-8"}}}',
  //     SubscriptionsConfirmed: '0',
  //     DisplayName: '',
  //     SubscriptionsDeleted: '1'
  //   }
  // }
  return response;
};
```

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

```
node get-topic-attributes.js
```

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

## トピック属性の設定
<a name="sns-examples-managing-topicssttopicattributes"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックの変更可能な属性を設定します。

`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-topic-attributes.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

属性を設定するトピックの `TopicArn`、設定する属性の名前、およびその属性の新しい値など、属性の更新のパラメータを含むオブジェクトを作成します。`Policy`、`DisplayName`、および `DeliveryPolicy` 属性のみ設定できます。`SNS` クライアントクラスの `SetTopicAttributesCommand` メソッドにパラメータを渡します。`SetTopicAttributesCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
*ATTRIBUTE\$1NAME* を設定している属性の名前で、*TOPIC\$1ARN* 設定したい属性のトピックの Amazon リソースネーム (ARN)で、 *NEW\$1ATTRIBUTE\$1VALUE* を属性の新しい値に置き換えてください。

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

export const setTopicAttributes = async (
  topicArn = "TOPIC_ARN",
  attributeName = "DisplayName",
  attributeValue = "Test Topic",
) => {
  const response = await snsClient.send(
    new SetTopicAttributesCommand({
      AttributeName: attributeName,
      AttributeValue: attributeValue,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

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

```
node set-topic-attributes.js
```

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

# Amazon SNS でのメッセージの公開
<a name="sns-examples-publishing-messages"></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 トピックにメッセージを発行する方法。

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

この例では、一連の Node.js モジュールを使用して Amazon SNS からトピックのエンドポイント、E メール、または電話番号にメッセージを発行します。Node.js モジュールは SDK for JavaScript を使用して、`SNS` クライアントクラスのこのメソッドを使用してメッセージを送信します。
+ [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-publishing-messages-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)」を参照してください。

## SNS トピックへのメッセージの発行
<a name="sns-examples-publishing-text-messages"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックにメッセージを発行します。

`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-topic.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

メッセージテキストと Amazon SNSトピックの Amazon Resource Name(ARN)を含む、メッセージを発行するためのパラメータを含むオブジェクトを作成します。利用可能な SMS 属性の詳細については、「[SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)」を参照してください。

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

**注記**  
*MESSAGE\$1TEXT* をメッセージテキストで、*TOPIC\$1ARN*をSNS トピックのARNに置き換えてください。

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

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

```
node publish-topic.js
```

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

# Amazon SNS でのサブスクリプションの管理
<a name="sns-examples-subscribing-unsubscribing-topics"></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 トピックへのすべてのサブスクリプションを一覧表示する方法。
+ E メールアドレス、アプリケーションエンドポイント、または AWS Lambda 関数を Amazon SNS トピックにサブスクライブする方法。
+ Amazon SNS トピックのサブスクライブを解除する方法。

## シナリオ
<a name="sns-examples-subscribing-unsubscribing-topics-scenario"></a>

この例では、一連の Node.js モジュールを使用して通知メッセージを Amazon SNS トピックに発行します。Node.js モジュールは、`SNS` クライアントクラスの以下のメソッドを使用してトピックを管理するために SDK for JavaScript を使用します。
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/)

## 前提条件タスク
<a name="sns-examples-subscribing-unsubscribing-topics-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)」を参照してください。

## サブスクリプションのトピックへの一覧表示
<a name="sns-examples-list-subscriptions-email"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックへのすべてのサブスクリプションを一覧表示します。

`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-subscriptions-by-topic.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

サブスクリプションを一覧表示するトピックの `TopicArn` パラメータを含むオブジェクトを作成します。`SNS` クライアントクラスの `ListSubscriptionsByTopicCommand` メソッドにパラメータを渡します。`ListSubscriptionsByTopicCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能を作成し、パラメータオブジェクトを渡します。

**注記**  
*TOPIC\$1ARN* をサブスクリプションを一覧表示したいトピックのAmazon リソースネーム (ARN) に置き換えてください。

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

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions.
 */
export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   Subscriptions: [
  //     {
  //       SubscriptionArn: 'PendingConfirmation',
  //       Owner: '901487484989',
  //       Protocol: 'email',
  //       Endpoint: 'corepyle@amazon.com',
  //       TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic'
  //     }
  //   ]
  // }
  return response;
};
```

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

```
node list-subscriptions-by-topic.js
```

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

## E メールアドレスのトピックへのサブスクライブ
<a name="sns-examples-subscribing-email"></a>

この例では、Node.js モジュールを使用して E メールアドレスをサブスクライブし、Amazon SNS トピックから SMTP E メールメッセージを受信するようにします。

`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)で見つけられます。

`subscribe-email.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

`email` プロトコル、サブスクライブするトピックの `TopicArn`、およびメッセージの `Endpoint` としての E メールアドレスを指定するための `Protocol` パラメータを含むオブジェクトを作成します。`SNS` クライアントクラスの `SubscribeCommand` メソッドにパラメータを渡します。このトピックの他の例が示すように、渡されたパラメータに使用される値に応じて、`subscribe` メソッドを使用して Amazon SNS トピックにいくつかの異なるエンドポイントをサブスクライブすることができます。

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

**注記**  
*TOPIC\$1ARN* をトピックの Amazon リソースネーム (ARN) に、*EMAIL\$1ADDRESS* をサブスクライブする E メールアドレスに置き換えます。

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

/**
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 * @param {string} emailAddress - The email address that is subscribed to the topic.
 */
export const subscribeEmail = async (
  topicArn = "TOPIC_ARN",
  emailAddress = "usern@me.com",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "email",
      TopicArn: topicArn,
      Endpoint: emailAddress,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
};
```

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

```
node subscribe-email.js
```

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

### サブスクリプションを確認する
<a name="sns-confirm-subscription-email"></a>

この例では、Node.jsモジュールを使用し、以前の Subscribe アクションでエンドポイントに送信したトークンを検証することによって、メッセージを受信するというエンドポイントの所有者の意思を確認します。

`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)で見つけられます。

`confirm-subscription.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

`TOPIC_ARN`と`TOKEN`を含むパラメータを定義し、`AuthenticateOnUnsubscribe`に対して`TRUE`または`FALSE`の値を定義します。

トークンは、以前の`SUBSCRIBE`アクションの期間にエンドポイントの所有者に送信される短期間のトークンです。たとえば、電子メールエンドポイントの場合、`TOKEN`は、E メールの所有者に送信されたサブスクリプションの確認メールのURLにあります。例えば、`abc123`は次のURLのトークンです。

![\[Amazon Web Services Simple Notification Service subscription confirmation page.\]](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/token.png)


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

**注記**  
*TOPIC\$1ARN*をトピックの Amazon リソースネーム (ARN)に、*TOKEN*を以前の`Subscribe`アクションでエンドポイント所有者に送信されたURLのトークン値に置き換えてください。そして、定義*AuthenticateOnUnsubscribe*を`TRUE`か`FALSE`の値で定義します。

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

/**
 * @param {string} token - This token is sent the subscriber. Only subscribers
 *                         that are not AWS services (HTTP/S, email) need to be confirmed.
 * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription.
 */
export const confirmSubscription = async (
  token = "TOKEN",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    // A subscription only needs to be confirmed if the endpoint type is
    // HTTP/S, email, or in another AWS account.
    new ConfirmSubscriptionCommand({
      Token: token,
      TopicArn: topicArn,
      // If this is true, the subscriber cannot unsubscribe while unauthenticated.
      AuthenticateOnUnsubscribe: "false",
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

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

```
node confirm-subscription.js
```

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

## アプリケーションエンドポイントのトピックへのサブスクライブ
<a name="sns-examples-subscribing-apps"></a>

この例では、Node.js モジュールを使用してモバイルアプリケーションのエンドポイントをサブスクライブし、Amazon SNS トピックから通知を受信するようにします。

`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)で見つけられます。

`subscribe-app.js`というファイル名で Node.js モジュールを作成します。必要なモジュールとパッケージのインストールを含め、前述のようにSDKを設定します。

`application`プロトコルを指定する`Protocol`パラメータ、サブスクライブするトピックの`TopicArn`、そして`Endpoint`パラメータのモバイルアプリケーションエンドポイントのAmazon リソースネーム(ARN)を含むオフジェクトを作成します。`SNS` クライアントクラスの `SubscribeCommand` メソッドにパラメータを渡します。

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

**注記**  
*TOPIC\$1ARN* をトピックのAmazon リソースネーム (ARN)に、 *MOBILE\$1ENDPOINT\$1ARN* をトピックスにサブスクライブしているエンドポイントに置き換えてください。

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

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created
 *                            when an application registers for notifications.
 */
export const subscribeApp = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "application",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```

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

```
node subscribe-app.js
```

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

## Lambda 関数のトピックへのサブスクライブ
<a name="sns-examples-subscribing-lambda"></a>

この例では、Node.js モジュールを使用して AWS Lambda 関数をサブスクライブし、Amazon SNS トピックから通知を受信します。

`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)で見つけられます。

`subscribe-lambda.js`というファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

`Protocol` パラメータを含むオブジェクトを作成し、`lambda`プロトコル、サブスクライブするトピック`TopicArn`の 、および AWS Lambda 関数の Amazon リソースネーム (ARN) を `Endpoint`パラメータとして指定します。`SNS` クライアントクラスの `SubscribeCommand` メソッドにパラメータを渡します。

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

**注記**  
*TOPIC\$1ARN* をトピックの Amazon リソースネーム(ARN)に、*RAMBDA\$1FUNCTION\$1ARN*をLambda 関数のAmazonリソースネーム(ARN)に置き換えてください。

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

/**
 * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to.
 * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function.
 */
export const subscribeLambda = async (
  topicArn = "TOPIC_ARN",
  endpoint = "ENDPOINT",
) => {
  const response = await snsClient.send(
    new SubscribeCommand({
      Protocol: "lambda",
      TopicArn: topicArn,
      Endpoint: endpoint,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   SubscriptionArn: 'pending confirmation'
  // }
  return response;
};
```

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

```
node subscribe-lambda.js
```

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

## トピックからのサブスクリプションの解除
<a name="sns-examples-unsubscribing"></a>

この例では、Node.js モジュールを使用して Amazon SNS トピックのサブスクリプションを解除します。

`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)で見つけられます。

`unsubscribe.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

サブスクリプションを解除するAmazon リソースネーム(ARN)を指定して、`SubscriptionArn` パラメータを含むオブジェクトを作成します。`SNS` クライアントクラスの `UnsubscribeCommand` メソッドにパラメータを渡します。

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

**注記**  
*TOPIC\$1SUBSCRIPTION\$1ARN* をサブスクリプションを解除するAmazon リソースネーム(ARN)に置き換えてください。

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

/**
 * @param {string} subscriptionArn - The ARN of the subscription to cancel.
 */
const unsubscribe = async (
  subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
) => {
  const response = await snsClient.send(
    new UnsubscribeCommand({
      SubscriptionArn: subscriptionArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '0178259a-9204-507c-b620-78a7570a44c6',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

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

```
node unsubscribe.js
```

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

# 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)で見つけられます。