第三方验证信息发送接口调用视图函数构造
urls.py
# 短信验证
re_path('^sendcode/$', views.send_code),
views.py
def send_msg(tel):
import urllib.request
import urllib
import json
import hashlib
import time
# 参数配置
url = "http://www.lokapi.cn/smsUTF8.aspx"
rece = "json"
username = "15955016470"
password = "wsw..177122"
# 验证码
tokenYZM = "d3cc4c0f"
# 参数
# param = "17712345678|张三|2547"
import random
p = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
random.shuffle(p)
res = random.sample(p, 4) # 列表
num = ''
for i in res:
num += i
param = str(tel) + '|' + str(num)
templateid = "494311C0"
def MD5(str):
m = hashlib.md5()
m.update(str.encode(encoding='UTF-8'))
return m.hexdigest().upper()
# 密码加密
passwd = MD5(password)
# 时间戳
ticks = int(time.time() * 1000)
# 构造请求主体
dict = {"action": "sendtemplate", "username": username,
"password": passwd, "token": tokenYZM, "timestamp": ticks}
body = "action=sendtemplate&username={username}&password={password}&token={token}×tamp={timestamp}".format(
username=username, password=passwd, token=tokenYZM, timestamp=ticks
)
sign = MD5(body)
dict["sign"] = sign
dict["rece"] = rece
dict["templateid"] = templateid
dict["param"] = param
headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
}
data = urllib.parse.urlencode(dict).encode('utf-8')
request = urllib.request.Request(url, data, headers)
text_rece = urllib.request.urlopen(request).read().decode('utf-8')
json_rece = json.loads(text_rece) # 字典
# 用户手机上收到的短信,验证码===正确验证码
# 用户在注册表单中填写的验证码===不确定正确性
# num存储到数据库中===正确验证码==标准
json_rece['last_code'] = str(num)
return json_rece
def send_code(request):
mobile = request.GET.get('mobile')
json_res = send_msg(mobile)
# 状态码+验证码
if json_res.get('code') == '0':
check_code = json_res.get('last_code')
request.session[mobile] = check_code
return HttpResponse('')