Esempi di codice OTP per l'utilizzo di SDK for Python (Boto3) in Amazon Pinpoint - Amazon Pinpoint

Avviso di fine del supporto: il 30 ottobre 2026, AWS terminerà il supporto per Amazon Pinpoint. Dopo il 30 ottobre 2026, non potrai più accedere alla console Amazon Pinpoint o alle risorse Amazon Pinpoint (endpoint, segmenti, campagne, percorsi e analisi). Per ulteriori informazioni, consulta la pagina relativa alla fine del supporto di Amazon Pinpoint. Nota: per quanto APIs riguarda gli SMS, i comandi vocali, i messaggi push su dispositivi mobili, l'OTP e la convalida del numero di telefono non sono interessati da questa modifica e sono supportati da AWS End User Messaging.

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di codice OTP per l'utilizzo di SDK for Python (Boto3) in Amazon Pinpoint

Questa sezione contiene esempi di codice che mostrano come utilizzare SDK per Python (Boto3) per inviare e verificare codici OTP (One-Time Password).

Genera un ID di riferimento

La seguente funzione genera un ID di riferimento univoco per ogni destinatario, in base al numero di telefono del destinatario, al prodotto o al marchio per cui il destinatario riceve un codice OTP (One-Time Password) e all'origine della richiesta (che, ad esempio, può essere il nome di una pagina di un sito o di un'app). Quando verifichi il codice OTP, devi fornire un ID di riferimento identico affinché la convalida abbia esito positivo. Sia l'esempio di codice di invio che quello di convalida utilizzano questa funzione di utilità.

Questa funzione non è obbligatoria, ma è un valido strumento per adattare il processo di invio e verifica del codice OTP a una transazione specifica in un modo da semplificarne il nuovo invio durante la fase di verifica. Puoi utilizzare qualsiasi ID di riferimento: questo infatti è solo un esempio di base. Tuttavia, gli altri esempi di codice in questa sezione si basano su questa funzione.

# 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()

Invia codici OTP

L'esempio di codice seguente mostra come utilizzare SDK per Python (Boto3) per inviare un codice OTP (One-Time Password).

# 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")

Convalida i codici OTP

L'esempio di codice seguente mostra come utilizzare SDK per Python (Boto3) per verificare un codice OTP (One-Time Password) già inviato. Affinché la fase di convalida abbia esito positivo, la richiesta deve includere un ID di riferimento che corrisponda esattamente all'ID di riferimento utilizzato per inviare il messaggio.

# 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")