Implementing SMS Verification Code with Python and Tencent Cloud SMS SDK
This tutorial explains how to set up phone‑number verification by installing the Tencent Cloud SMS SDK, configuring an application, applying for a signature and template, and writing a Python class that generates a six‑digit code and sends it via the cloud SMS service.
Many websites and mobile apps require phone‑number verification; this guide shows how to implement an SMS verification code feature using Python and the Tencent Cloud SMS service.
Prerequisites
Operating System: macOS Python >= 3.6.2 Tencent Cloud SMS personal account (free 100 messages per month)
Installation
pip3 install qcloudsms_pyAfter installing the SDK, you must create an application in the Tencent Cloud SMS console to obtain the appid and appkey , then apply for a message signature and a template. The template may contain placeholders such as {1} that will be filled with the verification code.
Code implementation
The following Python class encapsulates the whole process:
import random
from qcloudsms_py import SmsSingleSender
from qcloudsms_py.httpclient import HTTPError
class Captcha():
def create_captcha(self):
"""Create and return a six‑digit verification code"""
captcha = ''
for i in range(6):
now_number = str(random.randint(0, 9))
captcha += now_number
return captcha
def create_ssender(self):
"""Create an SmsSingleSender object"""
appid = ****** # replace with your appid
appkey = '******' # replace with your appkey
ssender = SmsSingleSender(appid, appkey)
return ssender
def send_short_message(self, phone_number):
"""Send the verification code via SMS"""
ssender = self.create_ssender()
params = []
captcha = self.create_captcha()
defult_time = "2"
params.append(captcha)
params.append(defult_time)
template_id = ****** # replace with your template ID
sms_sign = '******' # replace with your signature
try:
result = ssender.send_with_param(86, phone_number, template_id, params, sign=sms_sign, extend="", ext="")
return result['result']
except HTTPError as e:
print(e)
except Exception as e:
print(e)Replace the placeholders marked with asterisks with the values obtained from the Tencent Cloud console. The send_short_message method builds the parameter list according to the template placeholders, sends the SMS, and returns the result code for further handling.
By following these steps you can quickly add phone‑based verification to your web or mobile application.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.