

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 自訂訊息 Lambda 觸發程序
<a name="user-pool-lambda-custom-message"></a>

當您具有要傳送給使用者的電子郵件和簡訊的外部標準時，或您想要在執行時間將自己的邏輯套用至使用者訊息的格式時，請將自訂訊息觸發條件新增至您的使用者集區。自訂訊息 Lambda 會在您的使用者集區傳送所有電子郵件和簡訊之前收到訊息的內容。然後，您的 Lambda 函數有機會修改訊息內容和主旨。

Amazon Cognito 會在傳送電子郵件或電話驗證訊息或多重要素驗證 (MFA) 碼之前，叫用此觸發程序。您可以使用自訂的訊息觸發程序來動態自訂訊息。

請求中包含 `codeParameter`。此字串作為 Amazon Cognito 提供給使用者的代碼的預留位置。請將 `codeParameter` 字串插入訊息內文中您要顯示驗證碼的位置。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 函數的自訂輸入提供的一個或多個鍵值組，該函數是您用於自訂訊息觸發程序所指定。叫用自訂訊息函數的請求不包括傳遞至 [AdminInitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminInitiateAuth.html) 和 [InitiateAuth](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_InitiateAuth.html) 中的 ClientMetadata 參數的 API 操作的資料。若要將此資料傳遞至您的 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**  
要傳送給使用者的自訂簡訊。必須包含您在請求中收到的 `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 屬性為 `DEVELOPER`，那麼您只能使用 `emailSubject` 參數。如果使用者集區的 `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 函數可讓您在服務要求應用程式傳送驗證碼給使用者時，自訂電子郵件或簡訊的訊息。

Amazon Cognito 可在多個事件中叫用 Lambda 觸發程序：註冊後、重新傳送驗證碼、恢復忘記的密碼，或驗證使用者屬性。回應同時包含簡訊和電子郵件的訊息。訊息必須包含代碼參數 `"####"`。此參數是使用者接收驗證碼的預留位置。

一封電子郵件的長度上限為 20,000 個 UTF-8 字元，此長度包括驗證碼。您可以在這些電子郵件訊息中使用 HTML 標籤。

簡訊的長度上限為 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`和 的值插入回應物件`emailMessage`中的 `usernameParameter``smsMessage`和 。在此範例中，函數會將相同的訊息寫入回應欄位 `event.response.smsMessage`和 `event.response.emailMessage`。

一封電子郵件的長度上限為 20,000 個 UTF-8 字元。此長度包括驗證碼。您可以在這些電子郵件中使用 HTML 標籤。簡訊的長度上限為 140 個 UTF-8 字元。此長度包括驗證碼。

回應同時包含簡訊和電子郵件的訊息。

------
#### [ 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>"
  }
}
```

------