Aviso de fin de soporte: el 30 de octubre de 2026, AWS finalizará el soporte para Amazon Pinpoint. Después del 30 de octubre de 2026, ya no podrá acceder a la consola de Amazon Pinpoint ni a los recursos de Amazon Pinpoint (puntos de enlace, segmentos, campañas, recorridos y análisis). Para obtener más información, consulte el fin del soporte de Amazon Pinpoint. Nota: en lo APIs que respecta a los SMS, este cambio no afecta a los mensajes de voz, a las notificaciones push móviles, a las OTP y a la validación de números de teléfono, y son compatibles con la mensajería para el usuario AWS final.
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.
Ejemplos de Amazon Pinpoint para usar SDK para Python (Boto3) en Amazon Pinpoint
Esta sección contiene ejemplos de código que muestran cómo usar el SDK para Python (Boto3) para enviar y verificar códigos de OTP.
Generar un ID de referencia
La siguiente función genera un ID de referencia único para cada destinatario, basado en el número de teléfono del destinatario, el producto o la marca para el que el destinatario recibe una OTP 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). Al verificar el código de OTP, debe pasar un ID 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 envío y verificación de la OTP 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()
Enviar códigos de OTP
El siguiente ejemplo de código muestra cómo utilizar el SDK para Python (Boto3) para enviar un código de OTP.
# 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")
Validar códigos de OTP
El siguiente ejemplo de código muestra cómo utilizar el SDK para Python (Boto3) para verificar un código de OTP que ya ha 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")