騰訊雲短信驗證碼案例
開通騰訊雲短信
"""
1、官網注冊實名賬號:https://cloud.tencent.com
2、選取短信服務創建短信應用
3、申請簽名與短信模板 - 通過微信公眾號申請
"""
安裝 qcloudsms_py
>: pip install qcloudsms_py
騰訊雲短信二次封裝
libs
├── txsms
│ ├── __init__.py
│ ├── settings.py
└ └── sms.py
libs/txsms/settings.py
# 短信應用 SDK AppID - SDK AppID 以1400開頭
APP_ID = ...
# 短信應用 SDK AppKey
APP_KEY = "..."
# 短信模板ID,需要在短信控制台中申請
TEMPLATE_ID = ...
# 簽名 - 是`簽名內容`,而不是`簽名ID`
SMS_SIGN= "..."
# 電話前綴
MOBILE_PREFIX = 86
libs/txsms/sms.py
# 通過MacOS ssl安全認證
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
# 獲取驗證碼的功能
import random
def get_code():
code = ''
for i in range(4):
code += str(random.randint(0, 9))
return code
# 短信發送者
from qcloudsms_py import SmsSingleSender
from .settings import *
sender = SmsSingleSender(APP_ID, APP_KEY)
# 發送驗證碼
from utils.logging import logger
def send_sms(mobile, code, exp):
try:
# 發送短信
response = sender.send_with_param(MOBILE_PREFIX, mobile, TEMPLATE_ID, (code, exp), sign=SMS_SIGN, extend="", ext="")
# 成功
if response and response['result'] == 0:
return True
# 失敗
logger.warning('%s - %s' % ('短信發送失敗', response['result']))
except Exception as e:
# 異常
logger.warning('%s - %s' % ('短信發送失敗', e))
return False
libs/txsms/__init__.py
# 包對外提供的功能方法
from .sms import get_code, send_sms
測試
from libs import txsms
code = txsms.get_code()
print(code)
print(txsms.send_sms('電話', code, 5))
案例
# 發送驗證碼接口
from libs import txsms
class SMSAPIView(APIView):
def post(self, request, *args, **kwargs):
# 再次校驗手機號合法性
mobile = request.data.get('mobile')
# 校驗手機號是否存在及合法
if not mobile or not re.match(r'^1[3-9]\d{9}$', mobile):
return APIResponse(1, '手機號不合法')
# 生成驗證碼
code = txsms.get_code()
# 發送驗證碼
result = txsms.send_sms(mobile, code, SMS_EXP // 60)
if not result:
return APIResponse(1, '驗證碼發送失敗')
# 發送成功保存驗證碼到redis中,方便管理
cache.set(SMS_CACHE_KEY %{'mobile':mobile}, code, SMS_EXP)
return APIResponse(0, '驗證碼發送成功')