1、創建短信應用 - 應用管理
2、申請短信簽名 - 國內短信 > 簽名管理
3、申請短信模塊 - 國內短信 > 正文模板管理


1)API文檔,接口的使用說明
2)SDK,基於開發語言封裝的可以直接調用的功能(工具)集合
官網sdk使用文檔中找到安裝命令
pip install qcloudsms_py
按照sdk使用說明進行開發:https://cloud.tencent.com/document/product/382/11672


短信驗證碼使用
簡易修改官方SDK
# 所有配置換成申請的數據 # 申請的短信應用 SDK AppID appid = 1400 # 申請的短信應用 SDK AppKey appkey = "ba81" # 申請的短信模板ID,需要在短信控制台中申請 template_id = 5447 # 申請的簽名,參數使用的是`簽名內容`,而不是`簽名ID` sms_sign = "Owen的技術棧" from qcloudsms_py import SmsSingleSender sender = SmsSingleSender(appid, appkey) import random def get_code(): code = '' for i in range(4): code += str(random.randint(0, 9)) return code mobile = 13344556677 # 模板所需參數,和申請的模板中占位符要保持一致 code = get_code() print(code) params = [code, 5] try: result = sender.send_with_param(86, mobile, template_id, params, sign=sms_sign, extend="", ext="") if result and result.get('result') == 0: print('發送成功') except Exception as e: print('短信發送失敗:%s' % e)
短信功能二次封裝
settings.py
# 申請的 SDK AppID APP_ID = 1400325295 # SDK AppID 以1400開頭 # 短信應用 SDK AppKey APP_KEY = "60ba5a6e401239c197bed8e808708541" # 短信模板ID,需要在短信控制台中申請 TEMPLATE_ID = 545122 # NOTE: 這里的模板 ID`7839`只是示例,真實的模板 ID 需要在短信控制台中申請 # 簽名 SIGN = "Paul技術棧" # NOTE: 簽名參數使用的是`簽名內容`,而不是`簽名ID`。這里的簽名"騰訊雲"只是示例,真實的簽名需要在短信控制台中申請
sms.py
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 . import settings from utils.logging import logger sender = SmsSingleSender(settings.APP_ID, settings.APP_KEY) def send_code(mobile,code,exp): try: result = sender.send_with_param(86, mobile, settings.TEMPLATE_ID, (code,exp), sign=settings.SIGN, extend="", ext="") if result and result.get('result') == 0: return True logger.error('短信發送失敗:%s' % result.get('errmsg'))except Exception as e: logger.error('短信發送異常:%s' % e) return False

調用:
from libs import tx_sms code = tx_sms.get_code() print(code) result = tx_sms.send_code('13344556677',code,5) print(result)
