

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

# 自定义消息 Lambda 触发器
<a name="user-pool-lambda-custom-message"></a>

如果您对要发送给用户的电子邮件和短信设置了外部标准，或者您想在运行时将自己的逻辑应用于用户消息的格式化，请向您的用户池中添加自定义消息触发器。自定义消息 Lambda 会在您的用户池发送所有电子邮件和短信消息的内容之前先接收这些内容。然后，您的 Lambda 函数就有机会修改消息内容和主题。

Amazon Cognito 在发送电子邮件或电话验证消息或多重验证 (MFA) 代码前调用此触发器。您可以使用自定义消息触发器动态自定义消息。

该请求包括 `codeParameter`。这是一个字符串，用作 Amazon Cognito 传递给用户的代码的占位符。将 `codeParameter` 字符串插入消息正文中用于显示验证码的位置。Amazon Cognito 在收到此响应后，Amazon Cognito 将 `codeParameter` 字符串替换为实际验证码。

**注意**  
使用 `CustomMessage_AdminCreateUser` 触发器源时，自定义消息 Lambda 函数的输入事件将包含用户名和验证码。由于管理员创建的用户必须同时收到其用户名和验证码，因此来自您的函数的响应必须同时包含用户名和验证码的占位符变量。消息的占位符是 `request.usernameParameter` 和 `request.codeParameter` 的值。这些值通常是 `{username}` 和 `{####}`；作为最佳实践，请引用输入值，而不是对变量名称进行硬编码。

**Topics**
+ [自定义消息 Lambda 触发器源](#cognito-user-pools-lambda-trigger-syntax-custom-message-trigger-source)
+ [自定义消息 Lambda 触发器参数](#cognito-user-pools-lambda-trigger-syntax-custom-message)
+ [用于注册的自定义消息示例](#aws-lambda-triggers-custom-message-example)
+ [管理员创建用户的自定义消息示例](#aws-lambda-triggers-custom-message-admin-example)

## 自定义消息 Lambda 触发器源
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-trigger-source"></a>


| triggerSource 值 | 事件 | 
| --- | --- | 
| CustomMessage\$1SignUp | 自定义消息 – 在注册后发送确认码。 | 
| CustomMessage\$1AdminCreateUser | 自定义消息 – 向新用户发送临时密码。 | 
| CustomMessage\$1ResendCode | 自定义消息 – 向现有用户重新发送确认码。 | 
| CustomMessage\$1ForgotPassword | 自定义消息 – 针对“忘记密码”请求发送确认码。 | 
| CustomMessage\$1UpdateUserAttribute | 自定义消息 – 当用户的电子邮件或电话号码发生更改时，此触发器自动向用户发送验证码。不可用于其他属性。 | 
| CustomMessage\$1VerifyUserAttribute | 自定义消息 – 当用户针对新的电子邮件或电话号码手动请求验证码时，此触发器向用户发送验证码。 | 
| CustomMessage\$1Authentication | 自定义消息 – 在身份验证过程中发送 MFA 代码。 | 

## 自定义消息 Lambda 触发器参数
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message"></a>

Amazon Cognito 传递给此 Lambda 函数的请求是以下参数和 Amazon Cognito 添加到所有请求中的[常用参数](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared)的组合。

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        }
        "codeParameter": "####",
        "usernameParameter": "string",
        "clientMetadata": {
            "string": "string",
            . . .
        }
    },
    "response": {
        "smsMessage": "string",
        "emailMessage": "string",
        "emailSubject": "string"
    }
}
```

------

### 自定义消息请求参数
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-request"></a>

**userAttributes**  
表示用户属性的一个或多个名称/值对。

**codeParameter**  
一个字符串，用作自定义消息中验证码的占位符。

**usernameParameter**  
用户名。Amazon Cognito 在管理员创建的用户发出的请求中包含此参数。

**clientMetadata**  
一个或多个键值对，您可以将其作为自定义输入内容提供给为自定义消息触发器指定的 Lambda 函数。调用自定义消息函数的请求不包括在 [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html)API 操作中的 ClientMetadata 参数中[AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html)传递的数据。要将此数据传递给您的 Lambda 函数，您可以在以下 API 操作中使用 ClientMetadata 参数：  
+  [AdminResetUserPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminResetUserPassword.html) 
+  [AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html) 
+  [AdminUpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html)
+  [ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html)
+  [GetUserAttributeVerificationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_GetUserAttributeVerificationCode.html)
+  [ResendConfirmationCode](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ResendConfirmationCode.html)
+  [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)
+  [UpdateUserAttributes](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_UpdateUserAttributes.html)

### 自定义消息响应参数
<a name="cognito-user-pools-lambda-trigger-syntax-custom-message-response"></a>

在响应中，指定要在发送给用户的消息中使用的自定义文本。有关 Amazon Cognito 适用于这些参数的字符串限制，请参阅。[MessageTemplateType](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_MessageTemplateType.html)

**smsMessage**  
要发送给用户的自定义 SMS 消息。必须包含您在请求中收到的 `codeParameter` 值。

**emailMessage**  
发送给用户的自定义电子邮件。您可以在 `emailMessage` 参数中使用 HTML 格式。必须包含您在请求中收到的 `codeParameter` 值作为变量 `{####}`。只有在用户池的 `EmailSendingAccount` 属性为 `DEVELOPER` 时，Amazon Cognito 才可以使用`emailMessage` 参数。如果用户池的 `EmailSendingAccount` 属性不是 `DEVELOPER` 且返回了 `emailMessage` 参数，Amazon Cognito 会生成 400 错误代码 `com.amazonaws.cognito.identity.idp.model.InvalidLambdaResponseException`。当您选择使用 Amazon Simple Email Service (Amazon SES) 发送电子邮件时，用户池的 `EmailSendingAccount` 属性为 `DEVELOPER`。否则，该值为 `COGNITO_DEFAULT`。

**emailSubject**  
自定义消息的主题行。只有当用户池的 EmailSendingAccount属性为时，您才能使用该`emailSubject`参数`DEVELOPER`。如果用户池的 `EmailSendingAccount` 属性不是 `DEVELOPER` 且 Amazon Cognito 返回了 `emailSubject` 参数，Amazon Cognito 会生成 400 错误代码 `com.amazonaws.cognito.identity.idp.model.InvalidLambdaResponseException`。当您选择使用 Amazon Simple Email Service (Amazon SES) 发送电子邮件时，用户池的 `EmailSendingAccount` 属性为 `DEVELOPER`。否则，该值为 `COGNITO_DEFAULT`。

## 用于注册的自定义消息示例
<a name="aws-lambda-triggers-custom-message-example"></a>

当服务要求应用程序向用户发送验证码时，此示例 Lambda 函数自定义电子邮件或 SMS 消息。

Amazon Cognito 可以在多个事件中调用 Lambda 触发器：注册后、重新发送验证码时、恢复忘记的密码时或验证用户属性时。响应包括电子邮件和 SMS 消息。该消息必须包含代码参数 `"####"`。此参数是用户收到的验证码的占位符。

电子邮件的最大长度为 20000 个 UTF-8 字符。此长度包括验证码。您可以在这些电子邮件中使用 HTML 标签。

SMS 消息的最大长度为 140 个 UTF-8 个字符。此长度包括验证码。

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (event.triggerSource === "CustomMessage_SignUp") {
    const message = `Thank you for signing up. Your confirmation code is ${event.request.codeParameter}.`;
    event.response.smsMessage = message;
    event.response.emailMessage = message;
    event.response.emailSubject = "Welcome to the service.";
  }
  return event;
};

export { handler };
```

------

Amazon Cognito 将事件信息传递给 Lambda 函数。随后，该函数将相同事件对象随同响应中的任何更改返回给 Amazon Cognito。在 Lambda 控制台中，您可以设置一个测试事件，该事件包含与您的 Lambda 触发器相关的数据。以下是此代码示例的一个测试事件：

------
#### [ JSON ]

```
{
	"version": "1",
	"region": "us-west-2",
	"userPoolId": "us-west-2_EXAMPLE",
	"userName": "test-user",
	"callerContext": {
		"awsSdkVersion": "aws-sdk-unknown-unknown",
		"clientId": "1example23456789"
	},
	"triggerSource": "CustomMessage_SignUp",
	"request": {
		"userAttributes": {
			"sub": "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111",
			"cognito:user_status": "CONFIRMED",
			"email_verified": "true",
			"phone_number_verified": "true",
			"phone_number": "+12065551212",
			"email": "test-user@example.com"
		},
		"codeParameter": "{####}",
		"linkParameter": "{##Click Here##}",
		"usernameParameter": "None"
	},
	"response": {
		"smsMessage": "None",
		"emailMessage": "None",
		"emailSubject": "None"
	}
}
```

------

## 管理员创建用户的自定义消息示例
<a name="aws-lambda-triggers-custom-message-admin-example"></a>

Amazon Cognito 向此示例自定义消息 Lambda 函数发送的请求的 `triggerSource` 值为 `CustomMessage_AdminCreateUser`，并且拥有用户名和临时密码。该函数根据请求中的临时密码填入 `${event.request.codeParameter}`，并根据请求中的用户名填入 `${event.request.usernameParameter}`。

您的自定义消息必须将 `codeParameter` 和 `usernameParameter` 的值插入响应对象中的 `smsMessage` 和 `emailMessage`。在此示例中，该函数将相同的消息写入响应字段 `event.response.smsMessage` 和 `event.response.emailMessage`。

电子邮件的最大长度为 20000 个 UTF-8 字符。此长度包括验证码。您可以在这些电子邮件中使用 HTML 标签。SMS 消息的最大长度为 140 个 UTF-8 个字符。此长度包括验证码。

响应包括电子邮件和 SMS 消息。

------
#### [ Node.js ]

```
const handler = async (event) => {
  if (event.triggerSource === "CustomMessage_AdminCreateUser") {
    const message = `Welcome to the service. Your user name is ${event.request.usernameParameter}. Your temporary password is ${event.request.codeParameter}`;
    event.response.smsMessage = message;
    event.response.emailMessage = message;
    event.response.emailSubject = "Welcome to the service";
  }
  return event;
};

export { handler };
```

------

Amazon Cognito 将事件信息传递给 Lambda 函数。随后，该函数将相同事件对象随同响应中的任何更改返回给 Amazon Cognito。在 Lambda 控制台中，您可以设置一个测试事件，该事件包含与您的 Lambda 触发器相关的数据。以下是此代码示例的一个测试事件：

------
#### [ JSON ]

```
{
  "version": 1,
  "triggerSource": "CustomMessage_AdminCreateUser",
  "region": "<region>",
  "userPoolId": "<userPoolId>",
  "userName": "<userName>",
  "callerContext": {
      "awsSdk": "<calling aws sdk with version>",
      "clientId": "<apps client id>",
      ...
  },
  "request": {
      "userAttributes": {
          "phone_number_verified": false,
          "email_verified": true,
           ...
      },
      "codeParameter": "####",
      "usernameParameter": "username"
  },
  "response": {
      "smsMessage": "<custom message to be sent in the message with code parameter and username parameter>"
      "emailMessage": "<custom message to be sent in the message with code parameter and username parameter>"
      "emailSubject": "<custom email subject>"
  }
}
```

------