web后台,尤其用户权限设置一块,比较频繁用到短信验证码。
笔者以容联云通讯为例,借助云平台服务。其提供的免费试用足够应付代码测试需求。API开发文档中提供了详细的讲解,但是关于python只提供了py2.x,以下直接贴代码:
注:python interpreter 3.x版本,笔者为py3.7
0,以下为笔者项目目录树:
1,以下为CCPRestSDK.py文件:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Bannirui
# Datetime: 2019/7/4 14:53
# Software: PyCharm
import hashlib
import base64
import datetime
import json
import requests
from flask import jsonify
import pysnooper
class REST:
AccountSid = ''
AccountToken = ''
AppId = ''
SubAccountSid = ''
SubAccountToken = ''
ServerIP = ''
ServerPort = ''
SoftVersion = ''
Iflog = False #是否打印日志
Batch = '' #时间戳
Headers = {}
BodyType = 'json'#包体格式,可填值:json 、xml
def __init__(self, ServerIP, ServerPort, SoftVersion):
"""
初始化
:param ServerIP: 必选参数 服务器地址
:param ServerPort: 必选参数 服务器端口
:param SoftVersion: 必选从那时瞳 REST 版本号
"""
self.ServerIP = ServerIP
self.ServerPort = ServerPort
self.SoftVersion = SoftVersion
def setAccount(self, AccountSid, AccountToken):
"""
设置主账号
:param AccountSid: 必选参数 主账号
:param AccountToken: 必选参数 主账号TOKEN
:return:
"""
self.AccountSid = AccountSid
self.AccountToken = AccountToken
def setAppId(self, AppId):
"""
设置应用ID
:param AppId: 必选参数 应用ID
:return:
"""
self.AppId = AppId
def log(self, url, body, data):
"""
打印信息 调试
:param url: 请求网址
:param body: 请求包体
:param data: 响应包体
:return:
"""
print('这是请求的URL:')
print(url)
print('这是请求包体:')
print(body)
print('这是响应包体:')
print(data)
print('********************************')
# @pysnooper.snoop()
def sendTemplateSMS(self, to, datas, tempId):
"""
发送模板短信
:param to: 必选参数,短信接收手机号码集合,用英文逗号隔开
:param datas: 可先参数,内容数据,列表:['1234', '5'] 验证码1234,有效时间5分钟
:param tempId: 模板ID
:return:
"""
self.accAuth()
nowdate = datetime.datetime.now()
self.Batch = nowdate.strftime("%Y%m%d%H%M%S")
# 生成sig
signature = self.AccountSid + self.AccountToken + self.Batch
sig = hashlib.new('md5', signature.encode('utf-8')).hexdigest().upper()
# 拼接URL
url = "https://"+self.ServerIP + ":" + str(self.ServerPort) + "/" + self.SoftVersion + "/Accounts/" + self.AccountSid + "/SMS/TemplateSMS?sig=" + sig
print(url)
# 生成auth
src = self.AccountSid + ":" + self.Batch
auth = base64.b64encode(src.encode(encoding='utf-8')).strip()
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=utf-8',
'Content-Length': '139',
'Authorization': auth
}
data = json.dumps(
{
"to": to,
"datas": str(datas),
"templateId": tempId,
"appId": self.AppId
}
)
try:
req = requests.post(url, headers=headers, data=data)
if req.status_code == 200:
res = json.loads(req.text)
if self.Iflog:
self.log(url, data, res)
return res
except Exception as e:
# print(str(e))
if self.Iflog:
self.log(url, data, str(e))
return jsonify({'172001', '网络错误'})
#主帐号鉴权
def accAuth(self):
if self.ServerIP == "":
print('172004')
print('IP为空')
if self.ServerPort <= 0:
print('172005')
print('端口错误(小于等于0)')
if self.SoftVersion == "":
print('172013')
print('版本号为空')
if self.AccountSid == "":
print('172006')
print('主帐号为空')
if self.AccountToken == "":
print('172007')
print('主帐号令牌为空')
if self.AppId == "":
print('172012')
print('应用ID为空')
#设置包头
def setHttpHeader(self,req):
if self.BodyType == 'json':
self.Headers["Accept"] = "application/json"
self.Headers["Content-Type"] = "application/json;charset=utf-8"
else:
pass
2,以下为SendTenplateSMS.py文件:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Author: Bannirui
# Datetime: 2019/7/4 14:53
# Software: PyCharm
from CCPRestSDK import REST
# 主帐号
accountSid = '主账号'
# 主帐号Token
accountToken = '主账号TOKEN'
# 应用Id
appId = '主账号APPID'
# 请求地址,格式如下,不需要写http://
serverIP = 'app.cloopen.com'
# 请求端口
serverPort = 8883
# 版本号
softVersion = '2013-12-26'
class CCP(object):
"""
自己封装的发送短信的辅助类
"""
# 用于保存对象的类属性
instance = None
def __init__(self):
pass
def __new__(cls):
# 单例模式 判断CCP类是否有已经创建好的对象,如果没有,则创建一个对象并保存,如果有则将保存的对象直接返回
if cls.instance is None:
obj = super(CCP, cls).__new__(cls)
# 初始化REST SDK
obj.rest = REST(serverIP, serverPort, softVersion)
obj.rest.setAccount(accountSid, accountToken)
obj.rest.setAppId(appId)
cls.instance = obj
return cls.instance
def send_template_sms(self, to, datas, temp_id):
"""
发送模板短信
:param to: 手机号码
:param datas: 内容数据,格式为列表,如['1234', '4'] 验证码1234,时间为4分钟
:param temp_id: 模板ID
:return:
"""
result = self.rest.sendTemplateSMS(to, datas, temp_id)
for k, v in result.items():
if k == 'templateSMS':
for k, s in v.items():
print('%s:%s' % (k, s))
else:
print('%s:%s' % (k, v))
if __name__ == '__main__':
ccp = CCP()
ccp.send_template_sms('接收验证码的手机号码', ['1234', '5'], 1)