Lambda 函数中的 JSON 错误 - 使用 AWS Pinpoint 设置 SMS 注册系统

问题描述 投票:0回答:1

我正在尝试使用 AWS Pinpoint 和 SNS 设置 SMS 注册系统。但是,我无法按照他们的说明创建 Lambda 函数(示例)。

我已按照此处的指南设置整个系统,教程:设置 SMS 注册系统,网址为 https://docs.aws.amazon.com/pinpoint/latest/developerguide/tutorials-two-way-sms .html

我按照步骤 3 - 创建 Lambda 函数中的说明进行操作。我已经到了“创建”该函数的地步,下一步是替换现有代码,

console.log('Loading function');

export const handler = async (event, context) => {
    //console.log('Received event:', JSON.stringify(event, null, 2));
    console.log('value1 =', event.key1);
    console.log('value2 =', event.key2);
    console.log('value3 =', event.key3);
    return event.key1;  // Echo back the first key value
    // throw new Error('Something went wrong');
};

示例代码:


var AWS = require('aws-sdk');
var pinpoint = new AWS.Pinpoint({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";

exports.handler = (event, context, callback) => {
  console.log('Received event:', event);
  validateNumber(event);
};

function validateNumber (event) {
  var destinationNumber = event.destinationNumber;
  if (destinationNumber.length == 10) {
    destinationNumber = "+1" + destinationNumber;
  }
  var params = {
    NumberValidateRequest: {
      IsoCountryCode: 'US',
      PhoneNumber: destinationNumber
    }
  };
  pinpoint.phoneNumberValidate(params, function(err, data) {
    if (err) {
      console.log(err, err.stack);
    }
    else {
      console.log(data);
      //return data;
      if (data['NumberValidateResponse']['PhoneTypeCode'] == 0) {
        createEndpoint(data, event.firstName, event.lastName, event.source);
      } else {
        console.log("Received a phone number that isn't capable of receiving "
                   +"SMS messages. No endpoint created.");
      }
    }
  });
}

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
          ]
        }
      }
    }
  };
  pinpoint.updateEndpoint(params, function(err,data) {
    if (err) {
      console.log(err, err.stack);
    }
    else {
      console.log(data);
      //return data;
      sendConfirmation(destinationNumber);
    }
  });
}

function sendConfirmation(destinationNumber) {
  var params = {
    ApplicationId: projectId,
    MessageRequest: {
      Addresses: {
        [destinationNumber]: {
          ChannelType: 'SMS'
        }
      },
      MessageConfiguration: {
        SMSMessage: {
          Body: message,
          MessageType: messageType,
          OriginationNumber: originationNumber
        }
      }
    }
  };

  pinpoint.sendMessages(params, function(err, data) {
    // If something goes wrong, print an error message.
    if(err) {
      console.log(err.message);
    // Otherwise, show the unique ID for the message.
    } else {
      console.log("Message sent! " 
          + data['MessageResponse']['Result'][destinationNumber]['StatusMessage']);
    }
  });
}

我按照说明添加了环境变量,然后进行部署。 下一步是测试该功能,并收到以下结果:

状态:失败

Test Event Name
MyFunctionTest

Response
{
  "errorType": "ReferenceError",
  "errorMessage": "require is not defined in ES module scope, you can use import instead",
  "trace": [
    "ReferenceError: require is not defined in ES module scope, you can use import instead",
    "    at file:///var/task/index.mjs:1:11",
    "    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"
  ]
}

Function Logs
2023-10-28T23:13:35.836Z    undefined   ERROR   Uncaught Exception  {"errorType":"ReferenceError","errorMessage":"require is not defined in ES module scope, you can use import instead","stack":["ReferenceError: require is not defined in ES module scope, you can use import instead","    at file:///var/task/index.mjs:1:11","    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"]}
2023-10-28T23:13:37.506Z    undefined   ERROR   Uncaught Exception  {"errorType":"ReferenceError","errorMessage":"require is not defined in ES module scope, you can use import instead","stack":["ReferenceError: require is not defined in ES module scope, you can use import instead","    at file:///var/task/index.mjs:1:11","    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)"]}
START RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7 Version: $LATEST
Unknown application error occurred
Runtime.Unknown
END RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7
REPORT RequestId: 6b99b840-cc0a-46da-862a-5c3c4014f1e7  Duration: 1932.76 ms    Billed Duration: 1933 ms    Memory Size: 128 MB Max Memory Used: 17 MB

Request ID
6b99b840-cc0a-46da-862a-5c3c4014f1e7
node.js amazon-web-services aws-lambda amazon-sns aws-pinpoint
1个回答
0
投票

在 package.json 中将

type
更改为
commonjs

© www.soinside.com 2019 - 2024. All rights reserved.