django手机号短信验证码登录

一、流程分析:

1.用户在项目前端,输入手机号,然后点击【获取验证码】,将手机号发到post到后台。

2.后台验证手机号是否合法,是否已被占用,如果通过验证,则生成验证码,并通过运行脚本,让短信运营商向该手机号,发送该验证码,如果没通过验证,则返回错误信息

3.用户收到短信验证码以后,再次将所有信息post到后台。

4.后台验证各个数据,通过验证则完成实名制认证,如果没通过则返回错误信息。

总结,一次实名验证,需要两次ajax+post

二、对接短信商:

1.在云片网端:

1-注册云片网

地址:https://www.yunpian.com/

后台管理控制台页面:其中最重要的信息是APIKEY

image.png-47.1kB

2-开发者备案、新增签名、新增模板(模板管理)

  • 云片网后台的【测试】是没有意义的,所谓的测试,就是直接给你手机发送一条短信,这算哪门子测试?

  • 【签名/模板设备】页,【签名管理】点击【新增签名】,到这里会被提醒完善【开发者信息】,认证分为开发者的【公司】和【个人】,现在是开发测试阶段,可以先选择【个人】,【个人】要身份证的照片,提交照片。

  • 等待认证完成的短信通知,然后按照后台的操作指引,在【签名管理】页【新增签名】,在【模板管理】页【新增模板】,这些都要等待云片网的审核,审核通过会有短信通知。

image.png-63kB
  • 在云片网后台设置ip白名单,将外网ip加入白名单
image.png-49.9kB
  • 获取本机外网ip最简单的方法,就是百度ip
image.png-47.6kB

views.py

from django.shortcuts import render
from django.http import JsonResponse
from .models import CheckCode
import random, time
from django.conf import settings
from .yunpian import YunPian

# Create your views here.


def author_register(request):
    if request.method == 'GET':
        return render(request, 'author/register.html')
    elif request.method == 'POST':
        p_code = request.POST.get('check_code')
        phone = request.POST.get('phone')
        try:
            check_code = CheckCode.objects.get(phone_code=p_code, phone=phone)
            if float(time.time()) - float(check_code.c_time) > 60:
                check_code.delete()
                return '验证码超时已被删除'
            print(21333333333)
            check_code.delete()
            return '登录成功'
        except:
            print(1233333333)


def author_login(request):
    if request.method == 'GET':
        pass


def author_logout(request):
    if request.method == 'GET':
        pass

def code():
    a = ''
    for x in range(4):
        a += str(random.randint(0, 9))
    return a




def author_code(request):
    if request.method == 'POST':
        mobile = request.POST.get('mobile')
        phone_code = code()
        a = YunPian(settings.API_KEY)
        a.send_sms(phone_code, mobile)
        try:
            check_code = CheckCode.objects.get(phone=mobile)

            check_code.phone_code = phone_code
            check_code.save()
        except:
            print(phone_code, mobile, 1111111111)
            check_code = CheckCode(phone_code=phone_code, phone=mobile)
            check_code.save()
        return JsonResponse({'data': '验证码发送成功'})

yunpian.py



```import requests


class YunPian(object):
    def __init__(self, api_key):
        self.api_key = api_key
        self.single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json'

    def send_sms(self, code, mobile):
        params = {
            'apikey': self.api_key,
            'mobile': mobile,
            'text': '【李甲楠】您的验证码是{code}。如非本人操作,请忽略本短信'.format(code=code)
        }
        # text必须要跟云片后台的模板内容 保持一致,不然发送不出去!
        r = requests.post(self.single_send_url, data=params)
        print(r)


if __name__ == '__main__':
    yun_pian = YunPian('APP_KEY')
    yun_pian.send_sms('1862', '17613701708')

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% load static %}
    <link rel="shortcut icon" href="{% static '/dayu/favicon.ico' %}" type="image/x-icon" >
    <script src="{% static 'js/jquery-2.2.4.js/' %}"></script>
    <script src="{% static 'js/phone_code.js/' %}"></script>
    <title>用户注册</title>
</head>
<body>

<script type="text/javascript">
    var countdown = 60
    function settime(obj) {
        if(countdown == 0 ){
            obj.removeAttribute('disable');
            obj.value = '免费获取验证码';
            countdown = 60;
            return;
        }else{
            obj.setAttribute('disable', true);
            obj.value = '重新发送(' + countdown + ")";
            countdown--;
        }
    setTimeout(function() {
    settime(obj) }
    ,1000)
    }
</script>


<form action="{% url 'author:author_register' %}" method="post">
    {% csrf_token %}
        手机号: <input type="text" name="phone" id="phone" placeholder="请输入手机号"><br>
    密码: <input type="password" name="pwd" id="pwd"> <br>
    <input type="text" name="check_code" id="check_code" placeholder="请输入验证码">
    <input type="button" id="code" value="获取验证码">
    <input type="submit" value="注册">
</form>


</body>
</html>

phone_code.js

$(function () {
    var check = false;
   $('#phone').blur(function () {
        var a = $(this).val();
       e = /^1[34578]\d{9}$/;
       if(!e.test(a)){
          check = false
       }else{
           check = true;
       }

   });

        $('#code').click(function () {
            if(check){


            $.ajax({
                type: 'post',
                url: '/author/author_code/',
                data:{
                    csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val(),
                    mobile: $('#phone').val()
                },
                success:function (ad) {
                    alert(ad.data)
                },

            })
         }else(alert('请输入正确的手机号')) });


});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。