1.短信验证码设置
⾸先登陆阿⾥云,到控制台,在"产品和服务"中选择:
获取key和sceret
获取签名
获取模板代码
2.安装阿⾥云短信验证码库
安装阿⾥云SDK核⼼库,在虚拟开发环境⾥,执⾏:
pip install aliyun-python-sdk-core
在安装完成后,您可以使⽤OpenAPI Explorer来⽣成相关API的Demo并应⽤在您
的项⽬中
短信验证码类
import random
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
ACCESS_KEY_ID = "xxx" #⽤户AccessKey 需要根据⾃⼰的账户修改
ACCESS_KEY_SECRET = "xxxxxx" #Access Key Secret 需要根据⾃⼰的账
户修改
class SMS:
def __init__(self,signName,templateCode):
self.signName = signName #签名
self.templateCode = templateCode #模板code
self.client = client = AcsClient(ACCESS_KEY_ID,
ACCESS_KEY_SECRET, 'cn-hangzhou')
def send(self,phone_numbers,template_param):
request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https') # https | http
request.set_version('2017-05-25')
request.set_action_name('SendSms')
request.add_query_param('RegionId', "cn-hangzhou")
request.add_query_param('PhoneNumbers', phone_numbers)
request.add_query_param('SignName', self.signName)
request.add_query_param('TemplateCode',
self.templateCode)
request.add_query_param('TemplateParam', template_param)
response = self.client.do_action_with_exception(request)
return response
if __name__ == "__main__":
# 使⽤⾃⼰的签名(xxx)和模板代码(xxxxxx)
sms = SMS("xxx","xxxxxx")
phone = input("请输⼊⼿机号:")
#验证码
num = random.randint(10000,99999)
# 设置模板参数
para = "{'number':'%d'}"%num
# 发送验证码
res = sms.send(phone,para)
print(res.decode('utf-8'))
3.实现
在app的urls中设置路由
视图函数的实现
@csrf_exempt
def send(request):
if request.method == 'POST':
if request.is_ajax():
phone = request.POST.get('phone')
sms = SMS(自己的签名, 自己的模板代码)
code = randint(1000, 9999)
para = "{'number':'%d'}" % code
request.session['code'] = code
res = sms.send(phone,para)
return JsonResponse({'ok':1})
return render(request,"app01/message.html")
前端页面的实现
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送短信</title>
</head>
<body>
<form action="{% url 'App01:sms' %}" method="post">
{% csrf_token %}
<input type="hidden" name="hello" value="123">
电话号码: <input type="text" name="phone" id="phone">
<input type="button" id="yzm" value="发送验证码">
<input type="submit">
</form>
</body>
</html>
<script src="{% static 'jquery.min.js' %}"></script>
<script>
var second = 30;
$("#yzm").click(function () {
$(this).prop('disabled',true);
_this = this;
let oTimer = setInterval(function () {
$(_this).prop('value',''+second+"后发送");
second--;
if (second <= 0){
clearTimeout(oTimer);
oTimer = null;
$(_this).prop('value',"发送验证码")
}
},1000);
let sPhone = $('#phone').val();
console.log(sPhone)
$.post("{% url 'App01:sms' %}","phone="+sPhone,function
(data) {
console.log(data)
})
})
</script>