2401_83940696 2024-07-23 18:28 采纳率: 2.1%
浏览 3
已结题

怎样时输入的手机号都可以收到验证码?

以为是我的代码,我利用阿里云短信和ajax实现了给手机发送短信,但现在只能给阿里云绑定测试的手机号发送验证码,而不能使输入的手机号都可以发送验证码,我该如何修改?
前端代码

<html>
<head>
    <meta http-equiv="content-type" content="text/html;
    charset=UTF-8">
    <meta name="viewport" content="width=device-width,
    initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>注册</title>
    {% load static %}
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css'%}">
    <link rel="stylesheet" href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.css'%}">
    <link rel="stylesheet"
          href="{% static 'plugins/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css'%}">

</head>
<body>
<div class="account">
    <h2 style="text-align:center;">用户注册</h2>
    <form id="regForm" method="POST" style="margin-top:20px;" novalidate>
        {% csrf_token %}
        {% for field in form %}
        {% if field.name == 'code' %}
        <div class="form-group" style="margin-top:20px;">
            <label> {{ field.label}}</label>
            <div class="clearfix">
                <div class="col-md-6" style="padding:0;">{{field}}</div>
                <div class="col-md-6"><input id="btnSms" type="button" class="btn btn-default" value="点击获取验证码"></div>
            </div>
            <span class="error-msg" style="color:red;position:absolute"></span>
        </div>
        {% else %}
        <div class="form-group" style="margin-top:20px;">
            <label> {{ field.label}}</label>
            {{field}}
            <span class="error-msg" style="color:red;position:absolute"></span>
            {% endif %}
            {%endfor%}
            <div>
                <input id="btnSubmit" style="height:35px;width:200px; margin-left:90px; font-size:17px;" type="button" value="注册"
                       class="btn btn-info">
            </div>
            <div>
                 <span style="float: right; margin-top:20px;">已有账号.<a style=" text-decoration:none;" href=" ">去登录</a ></span>
            </div>
        </div>
    </form>

</div>

<script src="{% static 'js/jquery-3.5.1/jquery-3.5.1.min.js'%}"></script>
<script>
    //页面加载完
 $(function(){
        bindClickBtnSms();
        });

    //点击获取验证码的按钮绑定事件
        function bindClickBtnSms(){
            $('#btnSms').click(function(){

            $(".error-msg").empty();

            //获取用户输入的手机号
            var mobile=$('#id_mobile').val();

            $.ajax({
                url:"/send/sms/",
                type:"GET",
                data:{mobile: mobile,tpl: "register"},
                dataType: 'json',
                success:function(res){
                    //ajax请求发送成功后,自动执行函数
                    if (res.status){
                        sendSmsRemind();
                    }else{
                        //错误信息
                        $.each(res.error,function(key,value){
                            $('#id_'+key).next().text(value[0]);
                            })
                        }
                    },
                     error:function(xhr,status,error){
                        console.log('ajax请求失败:'+error)}
                })
            })
        }
        //倒计时
        function sendSmsRemind() {
            var $smsBtn=$('#smsBtn');
            $smsBtn.prop('disabled',true);  //禁用
            var time =60;
            var remind=setInterval(function (){
                $smsBtn.val(time + '秒重新发送');
                time=time-1;
                if (time<1){
                    clearInterval(remind);
                    $smsBtn.val('点击获取验证码').prop('disabled',false);
                }
            },1000)
        }
</script>
</body>
</html>


后端代码

def send_sms_lingle(phone_num, template_code, template_param):
    client = create_client('LTAI5tBxR8DkU1BKW39QsiLK', 'TEjXlIqcV31dBwwW8gHqUA6xVSr4DO')
    send_sms_request = dysmsapi_20170525_models.SendSmsRequest(
        sign_name='Python图书管理',
        template_code=template_code,
        phone_numbers=phone_num,
        template_param=template_param
    )
    runtime = util_models.RuntimeOptions()
    try:
        response = client.send_sms_with_options(send_sms_request, runtime)
        return response
    except Exception as error:
        UtilClient.assert_as_string(error.message)
        return {'result': 1000, 'errmsg': "短信发送失败"}
class SendSmsForm(forms.Form):
    code = random.randrange(100000, 999999)
    mobile = forms.CharField(label="手机号",
                             validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile(self):
        """手机号校验的勾子"""
        mobile = self.cleaned_data['mobile']
        # 判断短信模板是否有问题
        tpl = self.request.GET.get('tpl')
        template_id = settings.ALIYUN_SMS_TEMPLATE.get(tpl)
        if not template_id:
            raise ValidationError("短信模板错误")
        # 校验数据库中是否已有手机号
        exist = Username.objects.filter(mobile=mobile).exists()
        if exist:
            raise forms.ValidationError('手机号已存在')

        # 发短信 & 写redis
        code = random.randrange(100000, 999999)
        send_sms_lingle(mobile, template_id, '{"code":"' + str(code) + '"}')


        return mobile
def create_client(access_key_id, access_key_secret):
    config = open_api_models.Config(
        access_key_id=access_key_id,
        access_key_secret=access_key_secret
    )
    config.endpoint = f'dysmsapi.aliyuncs.com'
    return Dysmsapi20170525Client(config)


def send_sms(request):
    """发送短信"""
    from library.utils.forms import SendSmsForm
    form = SendSmsForm(request, data=request.GET)
    # 校验手机号,不能为空
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2024-07-23 18:36
    关注

    以下内容由AIGC及阿里嘎多学长共同生成、有用望采纳:


    根据您提供的代码和需求,下面是一些具体的步骤和代码示例,帮助您实现验证码发送功能:

    1. 前端手机号获取

    确保您的前端表单中手机号的输入框具有正确的id属性,例如id="id_mobile"。在JavaScript中使用以下代码获取手机号:

    var mobile = $('#id_mobile').val();
    

    2. AJAX请求处理

    在点击获取验证码按钮的事件处理函数中,使用AJAX请求将用户手机号发送到后端。您已经提供了相关的代码,确保data对象中包含mobiletpl参数。

    3. 后端手机号验证

    SendSmsForm类中,使用正则表达式和数据库查询来验证手机号的格式和唯一性。您已经实现了这部分逻辑,确保调用clean_mobile方法时传入正确的参数。

    4. 短信模板和参数传递

    send_sms_lingle函数中,确保使用正确的模板ID和参数。您需要从前端传递的tpl参数中获取模板ID,并将其作为template_code参数传递给send_sms_lingle函数。

    5. 错误处理

    在AJAX请求的error回调函数中,打印错误信息,并在后端的send_sms视图函数中返回错误信息给前端。例如:

    error: function(xhr, status, error) {
        console.log('ajax请求失败:' + error);
        // 可以在这里添加代码,将错误信息显示给用户
    }
    

    后端视图函数中,如果发送短信失败,返回错误信息:

    return JsonResponse({'status': False, 'error': form.errors})
    

    6. 其他注意事项

    • 确保您的后端服务可以接收来自前端的AJAX请求,并且正确处理GET请求。
    • 检查您的阿里云短信服务配置,确保没有限制只能发送到特定的测试手机号。
    • 确保您的前端和后端代码中使用的URL和参数名称一致。

    通过上述步骤,您应该能够实现验证码发送功能,并向用户输入的任何手机号发送验证码。如果遇到具体问题,可以根据错误信息进行调试。

    评论 编辑记录

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月23日
  • 创建了问题 7月23日

悬赏问题

  • ¥15 如何在vue.config.js中读取到public文件夹下window.APP_CONFIG.API_BASE_URL的值
  • ¥50 浦育平台scratch图形化编程
  • ¥20 求这个的原理图 只要原理图
  • ¥15 vue2项目中,如何配置环境,可以在打完包之后修改请求的服务器地址
  • ¥20 微信的店铺小程序如何修改背景图
  • ¥15 UE5.1局部变量对蓝图不可见
  • ¥15 一共有五道问题关于整数幂的运算还有房间号码 还有网络密码的解答?(语言-python)
  • ¥20 sentry如何捕获上传Android ndk 崩溃
  • ¥15 在做logistic回归模型限制性立方条图时候,不能出完整图的困难
  • ¥15 G0系列单片机HAL库中景园gc9307液晶驱动芯片无法使用硬件SPI+DMA驱动,如何解决?