

**サポート終了通知:** 2026 年 10 月 30 日に、 AWS は Amazon Pinpoint のサポートを終了します。2026 年 10 月 30 日を過ぎると、Amazon Pinpoint コンソールまたは Amazon Pinpoint のリソース (エンドポイント、セグメント、キャンペーン、ジャーニー、分析) にアクセスできなくなります。詳細については、「[Amazon Pinpoint のサポート終了](https://docs.aws.amazon.com/console/pinpoint/migration-guide)」を参照してください。**注:** SMS、音声、モバイルプッシュ、OTP、電話番号の検証に関連する APIs は、この変更の影響を受けず、 AWS エンドユーザーメッセージングでサポートされています。

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

# Amazon Pinpoint SMS メッセージングで使用する Lambda 関数を作成する
<a name="tutorials-two-way-sms-part-3"></a>

このセクションでは、Amazon Pinpoint SMS メッセージングで使用するための 2 つの Lambda 関数を作成して設定する方法について説明します。後で、特定のイベントが発生したときにこれらの関数を呼び出すように API Gateway および Amazon Pinpoint をセットアップします。これらの関数のどちらも、指定した Amazon Pinpoint プロジェクトにエンドポイントを作成し、更新します。最初の関数では、電話番号検証機能も使用します。

## お客様の情報を検証する関数を作成し、エンドポイントを作成する
<a name="tutorials-two-way-sms-part-3-create-register-function"></a>

最初の関数は、Amazon API Gateway から受信する登録フォームから入力を受けます。この情報を使用して Amazon Pinpoint の[電話番号検証](https://docs.aws.amazon.com/pinpoint/latest/developerguide/validate-phone-numbers.html)機能を使用して、お客様の電話番号に関する情報を取得します。次に、検証されたデータを使用して、指定された Amazon Pinpoint プロジェクトに新しいエンドポイントを作成します。デフォルトでは、関数に作成されるエンドポイントはユーザーからの今後の通信からオプトアウトされますが、このステータスは 2 番目の関数で変更できます。最後に、この関数では、ユーザーから SMS 通信を受信することをお客様が希望することを確認するように求めるメッセージをお客様に送信します。

**Lambda 関数を作成するには**

1. [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) で AWS Lambda コンソールを開きます。

1. [**関数の作成**] を選択してください。

1. **[関数の作成]** で、**[設計図の使用]** を選択します。

1. 検索フィールドに **hello** と入力して Enter キーを押します。結果のリストで、次のイメージに示すように、`hello-world` Node.js 関数を選択します。  
![\[[設計図の使用] が選択されたことを示す [関数の作成] ページ。\]](http://docs.aws.amazon.com/ja_jp/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step1.5.png)

1. **[基本的な情報]** で、以下を実行します。
   + [**名前**] には、**RegistrationForm** など、関数の名前を入力します。
   + [**Role**] で、[**既存のロールを選択**] を選択します。
   + **[既存のロール]** に、「[IAM ロールを作成する](tutorials-two-way-sms-part-2.md#tutorials-two-way-sms-part-2-create-role)」で作成した **[SMSRegistrationForm]** ロールを選択します。

   完了したら、[**関数の作成**] を選択します。

1. コードエディタで **[コードソース]** のサンプル関数を削除し、次のコードを貼り付けます。

   ```
   import { PinpointClient, PhoneNumberValidateCommand, UpdateEndpointCommand, SendMessagesCommand } from "@aws-sdk/client-pinpoint"; // ES Modules import
   const pinClient = new PinpointClient({region: process.env.region});  
   
   // Make sure the SMS channel is enabled for the projectId that you specify.
   // See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-sms-setup.html
   var projectId = process.env.projectId;
   
   // You need a dedicated long code in order to use two-way SMS. 
   // See: https://docs.aws.amazon.com/pinpoint/latest/userguide/channels-voice-manage.html#channels-voice-manage-request-phone-numbers
   var originationNumber = process.env.originationNumber;
   
   // This message is spread across multiple lines for improved readability.
   var message = "ExampleCorp: Reply YES to confirm your subscription. 2 msgs per "
               + "month. No purchase req'd. Msg&data rates may apply. Terms: "
               + "example.com/terms-sms";
               
   var messageType = "TRANSACTIONAL";
   
   export const handler = async (event, context) => {
     console.log('Received event:', event);
     await validateNumber(event);
   };
   
   async function validateNumber (event) {
     var destinationNumber = event.destinationNumber;
     if (destinationNumber.length == 10) {
       destinationNumber = "+1" + destinationNumber;
     }
     var params = {
       NumberValidateRequest: {
         IsoCountryCode: 'US',
         PhoneNumber: destinationNumber
       }
     };
     try{
       const PhoneNumberValidateresponse = await pinClient.send( new  PhoneNumberValidateCommand(params));
       console.log(PhoneNumberValidateresponse);
        if (PhoneNumberValidateresponse['NumberValidateResponse']['PhoneTypeCode'] == 0) {
           await createEndpoint(PhoneNumberValidateresponse, event.firstName, event.lastName, event.source);
           
         } else {
           console.log("Received a phone number that isn't capable of receiving "
                      +"SMS messages. No endpoint created.");
         }
     }catch(err){
       console.log(err);
     }
   }
   
   async function createEndpoint(data, firstName, lastName, source) {
     var destinationNumber = data['NumberValidateResponse']['CleansedPhoneNumberE164'];
     var endpointId = data['NumberValidateResponse']['CleansedPhoneNumberE164'].substring(1);
     
     var params = {
       ApplicationId: projectId,
       // The Endpoint ID is equal to the cleansed phone number minus the leading
       // plus sign. This makes it easier to easily update the endpoint later.
       EndpointId: endpointId,
       EndpointRequest: {
         ChannelType: 'SMS',
         Address: destinationNumber,
         // OptOut is set to ALL (that is, endpoint is opted out of all messages)
         // because the recipient hasn't confirmed their subscription at this
         // point. When they confirm, a different Lambda function changes this 
         // value to NONE (not opted out).
         OptOut: 'ALL',
         Location: {
           PostalCode:data['NumberValidateResponse']['ZipCode'],
           City:data['NumberValidateResponse']['City'],
           Country:data['NumberValidateResponse']['CountryCodeIso2'],
         },
         Demographic: {
           Timezone:data['NumberValidateResponse']['Timezone']
         },
         Attributes: {
           Source: [
             source
           ]
         },
         User: {
           UserAttributes: {
             FirstName: [
               firstName
             ],
             LastName: [
               lastName
             ]
           }
         }
       }
     };
     try{
       const UpdateEndpointresponse = await pinClient.send(new UpdateEndpointCommand(params));
       console.log(UpdateEndpointresponse);
       await sendConfirmation(destinationNumber);
     }catch(err){
       console.log(err);
     }  
   }
   
   async function sendConfirmation(destinationNumber) {
     var params = {
       ApplicationId: projectId,
       MessageRequest: {
         Addresses: {
           [destinationNumber]: {
             ChannelType: 'SMS'
           }
         },
         MessageConfiguration: {
           SMSMessage: {
             Body: message,
             MessageType: messageType,
             OriginationNumber: originationNumber
           }
         }
       }
     };
     try{
       const SendMessagesCommandresponse = await pinClient.send(new SendMessagesCommand(params));
       console.log("Message sent! " 
             + SendMessagesCommandresponse['MessageResponse']['Result'][destinationNumber]['StatusMessage']);
     }catch(err){
       console.log(err);
     }
   }
   ```

1. **[設定]** タブの **[環境変数]** で、**[編集]**、**[環境変数の追加]** の順に選択し、次の操作を行います。
   + 最初の行で、**originationNumber** のキーで変数を作成します。次に、「[ステップ 1.2](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel)」で受け取った専用ロングコードの電話番号に値を設定します。
**注記**  
電話番号には、必ずプラス記号 (\$1) および国コードを含めてください。ハイフン (-)、ピリオド (.)、または括弧など、その他の特殊文字を含めないでください。
   + 2 行目で、**projectId** のキーで変数を作成します。次に、「[ステップ 1.1](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project)」で作成したプロジェクトの一意の ID に値を設定します。
   + 3 行目で、**region** のキーで変数を作成します。次に、**us-east-1** または **us-west-2** など、Amazon Pinpoint を使用するリージョンに値を設定します。

   終了したら、[**環境変数**] セクションは、次のイメージに示す例のようになります。  
![\[originationNumber、projectId、およびリージョンの環境変数。\]](http://docs.aws.amazon.com/ja_jp/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step1.7.png)

1. ページの上部で、[**保存**] を選択します。

### 関数をテストする
<a name="tutorials-two-way-sms-part-3-create-register-function-test"></a>

関数を作成した後、テストして適切に設定されているかどうかを確認します。また、作成した IAM ロールに適切なアクセス許可があることを確認します。

**関数をテストするには**

1. **[テスト]** タブを選択します。

1. **[新しいイベントを作成]** を選択して、次の操作を行います。
   + [**Event name**] で、**MyPhoneNumber** など、テストイベントの名前を入力します。
   + コードエディタのサンプルコードを消去します。次のコードを貼り付けます。

     ```
     {
       "destinationNumber": "+12065550142",
       "firstName": "Carlos",
       "lastName": "Salazar",
       "source": "Registration form test"
     }
     ```
   + 上記のコード例で、`destinationNumber`、`firstName`、および `lastName` 属性の値を、個人の連絡先情報など、テストに使用する値に置き換えます。この関数をテストすると、`destinationNumber` 属性で指定した電話番号に SMS メッセージが送信されます。指定した電話番号が SMS メッセージを受信できることを確認します。
   + **[作成]** を選択します。

1. [**Test**] を選択します。

1. [**実行結果: 成功**] で、[**詳細**] を選択します。[**ログ出力**] セクションで、関数の出力を確認します。関数がエラーなしで実行されたことを確認します。

   指定した `destinationNumber` に関連付けられたデバイスを確認し、テストメッセージを受信したことを確認します。

1. Amazon Pinpoint コンソール ([https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/)) を開きます。

1. **[すべてのプロジェクト]** ページで、「[Amazon Pinpoint でプロジェクトを作成する](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project)」で作成したプロジェクトを選択します。

1. ナビゲーションペインの [**Segments**] を選択します。[**セグメント**] ページで、[**セグメントの作成**] を選択します。

1. [**セグメントグループ 1**] の [**Add filters to refine your segment**] で、[**Filter by user**] を選択します。

1. [**Choose a user attribute**] で、[**FirstName**] を選択します。次に、[**Choose values**] に、テストイベントで指定した名を選択します。

   [**Segment estimate**] セクションに、次のイメージに示すように、適格なエンドポイントがゼロであり、合計エンドポイントが 1 つであることが表示されます。この結果は正常です。関数が新しいエンドポイントを作成すると、エンドポイントがオプトアウトされます。Amazon Pinpoint のセグメントは、オプトアウトされたエンドポイントを自動的に除外します。  
![\[エンドポイントがゼロのセグメントグループ。\]](http://docs.aws.amazon.com/ja_jp/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step8.9.png)

## 通信にお客様をオプトインする関数を作成する
<a name="tutorials-two-way-sms-part-3-create-optin-function"></a>

2 番目の関数は、お客様が最初の関数により送信されるメッセージに返信した場合のみ実行されます。お客様の返信に「[双方向 SMS を有効にする](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel)」で指定したキーワードが含まれている場合、関数はエンドポイントレコードを更新して、お客様を今後の通信にオプトインします。Amazon Pinpoint は、「[双方向 SMS を有効にする](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel)」で指定したメッセージを使い自動的に応答します。

お客様が応答しない場合、または指定されたキーワード以外で応答する場合、何も起こりません。お客様のエンドポイントは Amazon Pinpoint に残っていますが、セグメントの対象となることはできません。

**Lambda 関数を作成するには**

1. [https://console.aws.amazon.com/lambda/](https://console.aws.amazon.com/lambda/) で AWS Lambda コンソールを開きます。

1. [**関数の作成**] を選択してください。

1. [**関数の作成**] で、[**設計図**] を選択します。

1. 検索フィールドに **hello** と入力して Enter キーを押します。結果のリストで、次のイメージに示すように、`hello-world` Node.js 関数を選択します。**[Configure]** (設定) を選択します。

1. **[Basic information]** (基本的な情報) で、以下を実行します。
   + [**名前**] には、**RegistrationForm\$1OptIn** など、関数の名前を入力します。
   + [**Role**] で、[**既存のロールを選択**] を選択します。
   + **[既存のロール]** に、「[IAM ロールを作成する](tutorials-two-way-sms-part-2.md#tutorials-two-way-sms-part-2-create-role)」で作成した [SMSRegistrationForm] ロールを選択します。

   完了したら、[**関数の作成**] を選択します。

1. コードエディタでサンプル関数を削除し、次のコードを貼り付けます。

   ```
   import { PinpointClient, UpdateEndpointCommand } from "@aws-sdk/client-pinpoint"; // ES Modules import
   
   // Create a new Pinpoint client instance with the region specified in the environment variables
   const pinClient = new PinpointClient({ region: process.env.region });
   
   // Get the Pinpoint project ID and the confirm keyword from environment variables
   const projectId = process.env.projectId;
   const confirmKeyword = process.env.confirmKeyword.toLowerCase();
   
   // This is the main handler function that is invoked when the Lambda function is triggered
   export const handler = async (event, context) => {
       console.log('Received event:', event);
   
       try {
           // Extract the timestamp, message, and origination number from the SNS event
           const timestamp = event.Records[0].Sns.Timestamp;
           const message = JSON.parse(event.Records[0].Sns.Message);
           const originationNumber = message.originationNumber;
           const response = message.messageBody.toLowerCase();
   
           // Check if the response message contains the confirm keyword
           if (response.includes(confirmKeyword)) {
               // If the confirm keyword is found, update the endpoint's opt-in status
               await updateEndpointOptIn(originationNumber, timestamp);
           }
       }catch (error) {
           console.error('An error occurred:', error);
           throw error; // Rethrow the error to handle it upstream
       }
   };
   
   // This function updates the opt-in status of a Pinpoint endpoint
   async function updateEndpointOptIn(originationNumber, timestamp) {
       // Extract the endpoint ID from the origination number
       const endpointId = originationNumber.substring(1);
   
        // Prepare the parameters for the UpdateEndpointCommand
       const params = {
           ApplicationId: projectId,
           EndpointId: endpointId,
           EndpointRequest: {
               Address: originationNumber,
               ChannelType: 'SMS',
               OptOut: 'NONE',
               Attributes: {
                   OptInTimestamp: [timestamp]
               },
           }
       };
   
       try {
           // Send the UpdateEndpointCommand to update the endpoint's opt-in status
           const updateEndpointResponse = await pinClient.send(new UpdateEndpointCommand(params));
           console.log(updateEndpointResponse);
           console.log(`Successfully changed the opt status of endpoint ID ${endpointId}`);
       } catch (error) {
           console.error('An error occurred while updating endpoint:', error);
           throw error; // Rethrow the error to handle it upstream
       }
   }
   ```

1. [**Environment variables (環境変数)**] で、以下の操作を実行します。
   + 最初の行で、**projectId** のキーで変数を作成します。次に、「[Amazon Pinpoint でプロジェクトを作成する](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project)」で作成したプロジェクトの一意の ID に値を設定します。
   + 2 行目で、**region** のキーで変数を作成します。次に、**us-east-1** または **us-west-2** など、Amazon Pinpoint を使用するリージョンに値を設定します。
   + 3 行目で、**confirmKeyword** のキーで変数を作成します。次に、値を「[双方向 SMS を有効にする](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-set-up-channel)」で作成した確認キーワードに設定します。
**注記**  
キーワードでは大文字と小文字は区別されません。この関数は、受信メッセージを小文字に変換します。

   終了したら、[**環境変数**] セクションは、次のイメージに示す例のようになります。  
![\[projectId、リージョン、および confirmKeyword の環境変数。\]](http://docs.aws.amazon.com/ja_jp/pinpoint/latest/userguide/images/SMS_Reg_Tutorial_LAM_Step2.7.png)

1. ページの上部で、[**保存**] を選択します。

### 関数をテストする
<a name="tutorials-two-way-sms-part-3-create-optin-function-test"></a>

関数を作成した後、テストして適切に設定されているかどうかを確認します。また、作成した IAM ロールに適切なアクセス許可があることを確認します。

**関数をテストするには**

1. **[テスト]** を選択します。

1. [**テストイベントを設定する**] ページで、以下の操作を行います。

   1. **Create new test event**を選択します。

   1. [**Event name**] で、**MyResponse** など、テストイベントの名前を入力します。

   1. コードエディタのサンプルコードを消去します。次のコードを貼り付けます。

      ```
      {
        "Records":[
          {
            "Sns":{
              "Message":"{\"originationNumber\":\"+12065550142\",\"messageBody\":\"Yes\"}",
              "Timestamp":"2019-02-20T17:47:44.147Z"
            }
          }
        ]
      }
      ```

      上記のコード例では、`originationNumber` 属性の値を、前の Lambda 関数をテストしたときに使用した電話番号と置き換えます。`messageBody` の値を「[双方向 SMS を有効にする](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-enable-two-way)」で指定した双方向 SMS キーワードと置き換えます。オプションで、`Timestamp` の値を現在の日付と時刻と置き換えることができます。

   1. **[作成]** を選択します。

1. [**テスト**] を再度選択します。

1. [**実行結果: 成功**] で、[**詳細**] を選択します。[**ログ出力**] セクションで、関数の出力を確認します。関数がエラーなしで実行されたことを確認します。

1. Amazon Pinpoint コンソール ([https://console.aws.amazon.com/pinpoint/](https://console.aws.amazon.com/pinpoint/)) を開きます。

1. **[すべてのプロジェクト]** ページで、「[Amazon Pinpoint でプロジェクトを作成する](tutorials-two-way-sms-part-1.md#tutorials-two-way-sms-part-1-create-project)」で作成したプロジェクトを選択します。

1. ナビゲーションペインの [**Segments**] を選択します。[**セグメント**] ページで、[**セグメントの作成**] を選択します。

1. [**セグメントグループ 1**] の [**Add filters to refine your segment**] で、[**Filter by user**] を選択します。

1. [**Choose a user attribute**] で、[**FirstName**] を選択します。次に、[**Choose values**] に、テストイベントで指定した名を選択します。

   [**Segment estimate (セグメントの見積もり)**] セクションに、1 つの適格なエンドポイントがあり、合計エンドポイントが 1 つであることが表示されます。

**Next**:[Amazon API Gateway を設定する](tutorials-two-way-sms-part-4.md)