码迷,mamicode.com
首页 > 其他好文 > 详细

AliYun-sms

时间:2019-12-11 23:43:26      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:关注   ack   global   ecc   sig   param   head   required   mamicode   

AliYun-sms

一、使用详情:

第1步:访问阿里云网址,免费开通

技术图片

技术图片

技术图片

第2步:查看新手引导

技术图片

技术图片

技术图片

技术图片

技术图片

第3步:查看开发指南

技术图片

技术图片

技术图片

技术图片

技术图片

技术图片

技术图片

二、练习:

技术图片
#!/usr/bin/env python
#coding=utf-8

#pip3 install aliyun-python-sdk-core
#pip geetest
#pip requests

from django.conf import settings
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
# client = AcsClient(‘<accessKeyId>‘, ‘<accessSecret>‘, ‘cn-hangzhou‘)
client = AcsClient(settings.ACCESSKEY_ID, settings.ACCESS_KEY_SECRET, cn-hangzhou)

def send_sms(phone,code):
    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)
    request.add_query_param(SignName, settings.SMS_TEMPLATE_CONF.get(SignName))
    request.add_query_param(TemplateCode, settings.SMS_TEMPLATE_CONF.get(TemplateCode))
    request.add_query_param(TemplateParam, "{‘code‘:%s}"%(code))

    response = client.do_action(request)
    # python2:  print(response)
    print(str(response, encoding = utf-8))


import random
def get_code():
    return "".join(random.sample([str(i) for i in range(0,10)],6))
utils/sms.py
技术图片
# 邮箱
EMAIL_HOST = smtp.exmail.qq.com  # 如果是 163 改成 smtp.163.com
EMAIL_PORT = 465
EMAIL_HOST_USER = ‘‘  # 帐号
EMAIL_HOST_PASSWORD = ‘‘  # 密码
# DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_USE_SSL = True

# 滑动验证
# pc_geetest_id = "b46d1900d0a894591916ea94ea91bd2c"
# pc_geetest_key = "36fc3fe98530eea08dfc6ce76e3d24c4"
PC_GEETEST_ID = "13e4f7b3b8323da2b0ff9950b7ab76bc"
PC_GEETEST_KEY = "2b7352c63ed6252df1762fb29c54ee92"

# 短信
ACCESSKEY_ID = ‘***********‘
ACCESS_KEY_SECRET = ***********
SMS_TEMPLATE_CONF = {
    "TemplateCode": "SMS_178466533",
    "TemplateParam": "{‘code‘:%s}",
    "SignName": "枝桠", }
settings.py
技术图片
    re_path(r^sign/$, views.sign,name=sign),
    re_path(r^pc-geetest/register, views.pcgetcaptcha, name=pcgetcaptcha),
    re_path(r^pc-geetest/ajax_validate, views.pcajax_validate, name=pcajax_validate),
    re_path(r^pc-geetest/get_phone_code, views.get_phone_code, name=get_phone_code),
urls.py
技术图片
from geetest import GeetestLib
from django.conf import settings
from utils import sms

def pcajax_validate(request):
    if request.method == "POST":
        gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
        challenge = request.POST.get(gt.FN_CHALLENGE, ‘‘)
        validate = request.POST.get(gt.FN_VALIDATE, ‘‘)
        seccode = request.POST.get(gt.FN_SECCODE, ‘‘)
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]
        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)

        #================
        if result:
            result = {"status": "success"}

            user = request.POST.get("user")
            pwd = request.POST.get("pwd")
            user = auth.authenticate(username=user, password=pwd)
            if not user:
                result[status] = "fail"
                result[msg] = 用户名或者密码错误
            else:
                auth.login(request, user)  # request.user== 当前登录对象  模板中{{ request.user.username }}

            rmb = request.POST.get("rmb")
            if rmb:
                request.session.set_expiry(60 * 60 * 24 * 30)

        else:
            result = {"status":"fail"}

        #===================
        return HttpResponse(json.dumps(result))
    return HttpResponse("error")

def pcgetcaptcha(request):
    user_id = test
    gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)


def sign(request):
    mode=request.GET.get(mode,password)
    if request.method == "POST":
        phone = request.POST.get("phone")
        code = request.POST.get("code")
        if code != request.session.get(code):
            result = {"code": "1","msg":手机验证码不正确}
            return HttpResponse(json.dumps(result))

        res = models.Customer.objects.filter(phone=phone).exists()

        if res:
            result = {"code": "0", "msg": 登陆成功,url:reverse(index)}
            return HttpResponse(json.dumps(result))
        else:
            result = {"code": "2", "msg": 手机号不存在}
            return HttpResponse(json.dumps(result))



    return render(request,sign/sign.html,{mode:mode})


def get_phone_code(request):
    if request.method == "POST":
        gt = GeetestLib(settings.PC_GEETEST_ID, settings.PC_GEETEST_KEY)
        challenge = request.POST.get(gt.FN_CHALLENGE, ‘‘)
        validate = request.POST.get(gt.FN_VALIDATE, ‘‘)
        seccode = request.POST.get(gt.FN_SECCODE, ‘‘)
        status = request.session[gt.GT_STATUS_SESSION_KEY]
        user_id = request.session["user_id"]
        if status:
            result = gt.success_validate(challenge, validate, seccode, user_id)
        else:
            result = gt.failback_validate(challenge, validate, seccode)

        #================

        if result:
            result = {"status": "success"}
            #二次校验成功,发短信
            code=sms.get_code()
            phone = request.POST.get("phone")
            sms.send_sms(phone,code)
            request.session[code]=code

        else:
            result = {"status":"fail"}


        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user = auth.authenticate(username=user, password=pwd)
        if not user:
            result[status] = "fail"
            result[msg] = 用户名或者密码错误
        else:
            auth.login(request, user)  # request.user== 当前登录对象  模板中{{ request.user.username }}

        rmb = request.POST.get("rmb")
        if rmb:
            request.session.set_expiry(60 * 60 * 24 * 30)
        #===================
        return HttpResponse(json.dumps(result))
    return HttpResponse("error")
views.py
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户登录</title>
    <!-- animate动画库 -->
    <link rel="stylesheet" href="/static/sign/animate.css">
    <!-- 全局样式 -->
    <link rel="stylesheet" href="/static/sign/global.css">
    <!-- html样式 -->
    <link rel="stylesheet" href="/static/sign/signin.css">

    <link href="/static/sign/style_https.css" rel="stylesheet">
</head>
<body>
<div class="main">
    <header>
        <section class="head-nav">
            <div class="nav-content">
                <div class="nav-logo">
                    <p class="logo">
                        <a href="/" class="logo-img1">
                            <img src="/static/sign/logo.png" alt="">
                        </a>
                        <a href="/" class="logo-img2">
                            <img src="/static/sign/logo.png" alt="">
                        </a>
                    </p>
                    <span class="pipe"></span>
                    <div class="region-toggle">登录学员系统</div>
                </div>
                <div class="nav-num">
                    <img src="/static/sign/singin-img1.jpg" alt="">
                    <div>
                        <h2>400-609-2893</h2>
                        <p>周一至周日 09:00 - 18:00</p>
                    </div>
                </div>
            </div>
        </section>
    </header>
    <div class="clearfix">
        <div class="card">
            <div class="server">
                <img src="/static/sign/logo.png" alt="" class="logo-img">
                <ul>
                    <li>
                        <img src="/static/sign/singin-img2.jpg" alt="">
                        <article>
                            <h4>免费</h4>
                            <p>全站课程免费学</p>
                        </article>
                    </li>
                    <li>
                        <img src="/static/sign/singin-img3.jpg" alt="">
                        <article>
                            <h4>前沿</h4>
                            <p>热门技术全覆盖 </p>
                        </article>
                    </li>
                    <li>
                        <img src="/static/sign/singin-img4.jpg" alt="">
                        <article>
                            <h4>口碑</h4>
                            <p>万千学子强烈推荐 </p>
                        </article>
                    </li>
                </ul>
            </div>
            <div class="login-wrap">
                <p class="tab-title">
                    {% csrf_token %}
                    <a href="{% url ‘sign‘ %}"><span class=" {% if mode == ‘password‘ %} this {% endif %} ">密码登录</span></a>
                    <a href="{% url ‘sign‘ %}?mode=sms"><span
                            class=" {% if mode == ‘sms‘ %} this {% endif %} ">短信登录</span></a>


                </p>
                <div class="auxiliary">
                    <p class="error-wrap">
                        <img src="/static/sign/singin-icon8.jpg" alt="">
                        <span class="error-text">请输入正确的手机号并获取验证码</span>
                    </p>


                    {% if mode == ‘password‘ %}
                        <div class="passwrod-login">
                            <div class="name i-box">
                                <img src="/static/sign/singin-icon1.jpg" alt="" class="icon1">
                                <img src="/static/sign/singin-icon1-1.jpg" alt="" class="icon2">
                                <input type="text" id="user" placeholder="请输入用户名" required="">
                            </div>
                            <div class="pwd i-box">
                                <img src="/static/sign/singin-icon3.jpg" alt="" class="icon1">
                                <img src="/static/sign/singin-icon2-1.jpg" alt="" class="icon2">
                                <input type="password" id="password" placeholder="请输入账户密码" required="">
                                <div class="toggle">
                                    <img src="/static/sign/singin-icon4.png" alt="" class="icon3">
                                    <img src="/static/sign/singin-icon4-1.jpg" alt="" class="icon4">
                                </div>
                            </div>
                            <a href="#" class="forget">忘记密码?</a>
                            <div class="sliding">
                                <div id="embed-captcha"></div>
                            </div>
                            <span class="login p-login">立即登录</span>
                        </div>
                    {% else %}
                        <div class="sms-login">
                            <div class="phone i-box">
                                <img src="/static/sign/singin-icon2.jpg" alt="" class="icon1">
                                <img src="/static/sign/singin-icon3-1.jpg" alt="" class="icon2">
                                <input type="text" id="phone" placeholder="请输入手机号">
                            </div>



                            <div class="validate i-box">
                                <img src="/static/sign/singin-icon5.jpg" alt="" class="icon1">
                                <img src="/static/sign/singin-icon5-1.jpg" alt="" class="icon2">
                                <input type="text" id="code" placeholder="请输入验证码">
                                <button class="getcode">获取验证码</button>
                                <button class="countdown" id="countdown"><span>60</span>后重新发送...</button>
                            </div>
                            <div class="sliding">


                                <div id="embed-captcha"></div>

                            </div>
                            <span class="login s-login">立即登录</span>
                        </div>
                    {% endif %}



                    <p class="bottom">
                        <span href="" class="wx"><img src="/static/sign/singin-icon6.jpg" alt="">微信登录</span>
                        <a href="https://new.oldboyedu.com/signup.html" class="signup">还没有学员账号?<span>立即注册</span></a>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 为使用方便,直接使用jquery.js库,如您代码中不需要,可以去掉 -->
<script src="http://code.jquery.com/jquery-1.12.3.min.js"></script>

<!-- 动效 -->
{#<script src="/static/sign/signin.js"></script>#}
<!-- 滑动验证码 -->
<script src="/static/sign/gt.js"></script>

<!-- 引入封装了failback的接口--initGeetest -->
{#<script src="http://static.geetest.com/static/tools/gt.js"></script>#}

<script>
    // 手机验证
    var outercaptchaObj = null;
    var handlerPopup = function (captchaObj) {
        // 成功的回调
        outercaptchaObj = captchaObj;
        captchaObj.onSuccess(function () {
            var validate = captchaObj.getValidate();

            //验证通过后先隐藏提示
            $(.error-wrap).hide();
            $(.sms-login .validate).removeClass(error-box);


            $(".p-login").click(function () {
                $.ajax({
                    url: "/pc-geetest/ajax_validate", // 进行二次验证
                    type: "post",
                    dataType: "json",
                    data: {
                        user: $(#user).val(),
                        pwd: $(#password).val(),
                        csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(),
                        geetest_challenge: validate.geetest_challenge,
                        geetest_validate: validate.geetest_validate,
                        geetest_seccode: validate.geetest_seccode
                    },
                    success: function (data) {
                        if (data && (data.status === "success")) {
                            location.href = "/"
                        } else {
                            console.log(data.msg);
                            $("#error_msg").text(data.msg).css({"color": "red", "margin-left": "10px"});
                            setTimeout(function () {
                                $("#error_msg").text("");
                            }, 4000)

                        }
                    }
                });
            });

        });

        // 将验证码加到id为captcha的元素里
        captchaObj.appendTo("#embed-captcha");

        // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
    };

    // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
    $.ajax({
        url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {
            // 使用initGeetest接口
            // 参数1:配置参数
            // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
                offline: !data.success, // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerPopup);
        }
    });

    //免密
    $(.toggle).click(function () {
        $(.error-wrap).hide();
        if ($(.pwd input).attr(type) == password) {
            $(.pwd input).attr(type, text);
            $(.icon3).show();
            $(.icon4).hide();
        } else {
            $(.pwd input).attr(type, password);
            $(.icon4).show();
            $(.icon3).hide();
        }
    });


    //获取验证码倒计时
    var num = 60;
    $(.getcode).click(function (e) {

        //验证手机号格式是否正确
        flag = /^1[3-9][0-9]{9}$/.test($(#phone).val());

        if (!flag) {
            $(.error-wrap).show();
            $(.sms-login .phone).addClass(error-box);
            return
        }

        var validate = outercaptchaObj.getValidate();
        if (!validate) {
            $(.error-wrap).show();
            $(.error-wrap span).text(请先通过滑动验证);
            $(.sms-login .validate).addClass(error-box);
            return
        }


        $.ajax({
            url: "/pc-geetest/get_phone_code", // 获取验证码
            type: "post",
            dataType: "json",
            data: {
                phone: $(#phone).val(),
                csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(),
                geetest_challenge: validate.geetest_challenge,
                geetest_validate: validate.geetest_validate,
                geetest_seccode: validate.geetest_seccode
            },
            success: function (data) {
                if (data && (data.status === "success")) {

                } else {


                }
            }
        });

        var _this = $(this);
        $(.countdown).find(span).text(num);
        var timer = setInterval(function () {
            if (num > 0) {
                $(.countdown).find(span).text(num--);
                _this.hide();
                $(.countdown).show();
            } else {
                clearInterval(timer);
                num = 60;
                _this.show();
                $(.countdown).hide();
            }
        }, 1000)

    });

    //input获取焦点
    $(input).focus(function () {
        $(.error-wrap).hide();
        $(.login-wrap .i-box).removeClass(error-box);
    });


    //登录btn
    /*
    $(‘.p-login‘).click(function () {
        $(‘.error-wrap‘).show();
        $(‘.passwrod-login .name‘).addClass(‘error-box‘);
        $(‘.passwrod-login .pwd‘).addClass(‘error-box‘);
    });
    $(‘.s-login‘).click(function () {
        $(‘.error-wrap‘).show();
        $(‘.sms-login .phone‘).addClass(‘error-box‘);
        $(‘.sms-login .validate‘).addClass(‘error-box‘);
    });

    */
    $(.s-login).click(function () {
        $.ajax({
            url: "", // 获取验证码
            type: "post",
            dataType: "json",
            data: {
                phone: $(#phone).val(),
                code: $(#code).val(),
                csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(),
            },
            success: function (data) {
                if (data && (data.code === 0)) {
                    location.href = data.url
                } else {
                    console.log(data.msg);
                    $("#error_msg").text(data.msg).css({"color": "red", "margin-left": "10px"});
                    setTimeout(function () {
                        $("#error_msg").text("");
                    }, 4000)

                }
            }
        });

    })


</script>


</body>
</html>
sign.html

AliYun-sms

标签:关注   ack   global   ecc   sig   param   head   required   mamicode   

原文地址:https://www.cnblogs.com/bubu99/p/12026368.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!