短信验证码(以阿里云短信为例)

1.短信验证码设置

⾸先登陆阿⾥云,到控制台,在"产品和服务"中选择:
短信验证码(以阿里云短信为例)_第1张图片
获取key和sceret
短信验证码(以阿里云短信为例)_第2张图片
短信验证码(以阿里云短信为例)_第3张图片
获取签名
短信验证码(以阿里云短信为例)_第4张图片
获取模板代码
短信验证码(以阿里云短信为例)_第5张图片

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 %}



 
 发送短信
 

{% csrf_token %} 电话号码:

你可能感兴趣的:(短信验证码)