短信验证码发送实现(详细教程)

 

图片[1]-短信验证码发送实现(详细教程)-初晴小屋

 

首先,我们需要创建一个HTML表单

<!DOCTYPE html>

<html lang="en">


<head>


    <meta charset="UTF-8">


    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>Send Verification Code</title>


</head>


<body>


    <form action="/send-code" method="post">


        <label for="contact">Phone or Email:</label>


        <input type="text" id="contact" name="contact" required>


        <button type="submit">Send Code</button>


    </form>


</body>


</html>

2. 服务器端处理

在服务器端,我们需要处理表单提交,生成验证码,并发送到用户的手机号或邮箱。以下是一个简单的Python Flask示

例:

import random


import smtplib


app = Flask(__name__)


@app.route('/send-code', methods=['POST'])


def send_code():


    contact = request.form['contact']


    code = str(random.randint(1000, 9999))


    # 发送验证码到手机或邮箱


    if '@' in contact:


        send_email(contact, code)


    else:


        send_sms(contact, code)


    return jsonify({'message': 'Verification code sent!'})


def send_email(to, code):


    from_email = 'your_email@example.com'


    password = 'your_password'


    server = smtplib.SMTP('smtp.example.com', 587)


    server.starttls()


    server.login(from_email, password)


    server.sendmail(from_email, to, f'Subject: Your verification codennYour code is {code}')


    server.quit()


def send_sms(to, code):


    # 使用第三方短信API发送短信


    pass


if __name__ == '__main__':


    app.run(debug=True)

二、利用JavaScript进行异步请求

与表单提交相比,利用JavaScript进行异步请求能带来更好的用户体验,不需要页面刷新。

 

1. 修改HTML表单

<!DOCTYPE html>

<html lang="en">


<head>


    <meta charset="UTF-8">


    <meta name="viewport" content="width=device-width, initial-scale=1.0">


    <title>Send Verification Code</title>


</head>


<body>


    <form id="verification-form">


        <label for="contact">Phone or Email:</label>


        <input type="text" id="contact" name="contact" required>


        <button type="submit">Send Code</button>


    </form>


    <script>


        document.getElementById('verification-form').addEventListener('submit', function(event) {


            event.preventDefault();


            var contact = document.getElementById('contact').value;


            fetch('/send-code', {


                method: 'POST',


                headers: {


                    'Content-Type': 'application/json'


                },


                body: JSON.stringify({ contact: contact })


            })


            .then(response => response.json())


            .then(data => alert(data.message))


            .catch(error => console.error('Error:', error));


        });


    </script>


</body>


</html>

 

© 版权声明
THE END
喜欢就支持一下吧
点赞5赞赏 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容