OTPejemplos de código SDK para usar en Python (Boto3) en Amazon Pinpoint - Amazon Pinpoint

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

OTPejemplos de código SDK para usar en Python (Boto3) en Amazon Pinpoint

Esta sección contiene ejemplos de código que muestran cómo usar Python (Boto3) para enviar y verificar OTP códigos. SDK

Genera un ID de referencia

La siguiente función genera un identificador de referencia único para cada destinatario, basado en el número de teléfono del destinatario, el producto o la marca OTP para el que recibe el mensaje y el origen de la solicitud (que podría ser el nombre de una página de un sitio o una aplicación, por ejemplo). Cuando verifiques el OTP código, debes pasar un identificador de referencia idéntico para que la validación se realice correctamente. Los ejemplos de código de envío y validación utilizan esta función de utilidad.

Esta función no es obligatoria, pero es una forma útil de limitar el proceso de OTP envío y verificación a una transacción específica de forma que se pueda volver a enviar fácilmente durante el paso de verificación. Puede usar cualquier ID de referencia que desee; este es solo un ejemplo básico. Sin embargo, los demás ejemplos de código de esta sección se basan en esta función.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import hashlib def generate_ref_id(destinationNumber,brandName,source): refId = brandName + source + destinationNumber return hashlib.md5(refId.encode()).hexdigest()

Envía códigos OTP

El siguiente ejemplo de código muestra cómo usar Python (Boto3) SDK para enviar un OTP código.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import boto3 from botocore.exceptions import ClientError from generate_ref_id import generate_ref_id ### Some variables that are unlikely to change from request to request. ### # The AWS Region that you want to use to send the message. region = "us-east-1" # The phone number or short code to send the message from. originationNumber = "+18555550142" # The project/application ID to use when you send the message. appId = "7353f53e6885409fa32d07cedexample" # The number of times the user can unsuccessfully enter the OTP code before it becomes invalid. allowedAttempts = 3 # Function that sends the OTP as an SMS message. def send_otp(destinationNumber,codeLength,validityPeriod,brandName,source,language): client = boto3.client('pinpoint',region_name=region) try: response = client.send_otp_message( ApplicationId=appId, SendOTPMessageRequestParameters={ 'Channel': 'SMS', 'BrandName': brandName, 'CodeLength': codeLength, 'ValidityPeriod': validityPeriod, 'AllowedAttempts': allowedAttempts, 'Language': language, 'OriginationIdentity': originationNumber, 'DestinationIdentity': destinationNumber, 'ReferenceId': generate_ref_id(destinationNumber,brandName,source) } ) except ClientError as e: print(e.response) else: print(response) # Send a message to +14255550142 that contains a 6-digit OTP that is valid for 15 minutes. The # message will include the brand name "ExampleCorp", and the request originated from a part of your # site or application called "CreateAccount". The US English message template should be used to # send the message. send_otp("+14255550142",6,15,"ExampleCorp","CreateAccount","en-US")

Valida los códigos OTP

El siguiente ejemplo de código te muestra cómo usar SDK para Python (Boto3) para verificar un OTP código que ya has enviado. Para que el paso de validación se realice correctamente, la solicitud debe incluir un ID de referencia que coincida exactamente con el ID de referencia que se utilizó para enviar el mensaje.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import boto3 from botocore.exceptions import ClientError from generate_ref_id import generate_ref_id # The AWS Region that you want to use to send the message. region = "us-east-1" # The project/application ID to use when you send the message. appId = "7353f53e6885409fa32d07cedexample" # Function that verifies the OTP code. def verify_otp(destinationNumber,otp,brandName,source): client = boto3.client('pinpoint',region_name=region) try: response = client.verify_otp_message( ApplicationId=appId, VerifyOTPMessageRequestParameters={ 'DestinationIdentity': destinationNumber, 'ReferenceId': generate_ref_id(destinationNumber,brandName,source), 'Otp': otp } ) except ClientError as e: print(e.response) else: print(response) # Verify the OTP 012345, which was sent to +14255550142. The brand name ("ExampleCorp") and the # source name ("CreateAccount") are used to generate the correct reference ID. verify_otp("+14255550142","012345","ExampleCorp","CreateAccount")