1. 程式人生 > >簡訊驗證(阿里雲)

簡訊驗證(阿里雲)

簡訊驗證(阿里雲)

  1. 下載
  • 下載官方的demohttps://help.aliyun.com/document_detail/55359.html?spm=a2c4g.11186623.4.3.SK7RE

2.安裝配置

到demo目錄中做一下安裝

pyenv activate env3.6.6  # 開啟虛擬開發環境
python setup.py install  # 需要選擇python的版本
  • 配置傳送的const.py

    ACCESS_KEY_ID = “LTAIDHOYSjYcvyVt” #
    ACCESS_KEY_SECRET = “qrEgykmXX4e6GUMFOqzuiLZ5gsUxSC”

3.程式碼實現

class SMS:
    def __init__(self,sign_name,template_code):
        self.__business_id = uuid.uuid1()
        self.sign_name = sign_name  #簽名
        self.template_code = template_code  #模板程式碼

    #傳送簡訊
    def send_sms(self, phone_numbers,  template_param):
        template_param = "{\"number\":\"" + str(template_param) + "\"}"
        smsRequest = SendSmsRequest.SendSmsRequest()
        # 申請的簡訊模板編碼,必填
        smsRequest.set_TemplateCode(self.template_code)

        # 簡訊模板變數引數
        if template_param is not None:
            smsRequest.set_TemplateParam(template_param)

        # 設定業務請求流水號,必填。
        smsRequest.set_OutId(self.__business_id)

        # 簡訊簽名
        smsRequest.set_SignName(self.sign_name)

        # 資料提交方式
        # smsRequest.set_method(MT.POST)

        # 資料提交格式
        # smsRequest.set_accept_format(FT.JSON)

        # 簡訊傳送的號碼列表,必填。
        smsRequest.set_PhoneNumbers(phone_numbers)

        # 呼叫簡訊傳送介面,返回json
        smsResponse = acs_client.do_action_with_exception(smsRequest)

        # TODO 業務處理
        return smsResponse

4.前端程式碼

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登入</title>
    <script src="{% static 'jquery-1.11.3/jquery.min.js' %}"></script>
</head>
<body>
<form action="/vc/dologin/" method="post">
    使用者名稱: <input type="text" name="username" placeholder="請輸入使用者名稱"> <br>
    手機號: <input type="text" name="phone" id="phone"> <br>
    驗證碼:<input type="text" name="yzm"> <input type="button" value="獲取驗證碼" id="yzm">  <br>
    <input type="submit" value="登入">
</form>
</body>
</html>
<script>
    var time = 10
    var timer
    $('#yzm').click(function () {
        var _this = this;//設定區域性變量表示當前按鈕
        // 按鈕不可用
        this.disabled = true //當前按鈕不可用
        timer = setInterval(function(){
            time--
            _this.value = '' + time + "後重新發送"
            if (time < 1){
                clearInterval(timer)
                timer = null
                _this.value = "獲取驗證碼"
                _this.disabled = false
                time = 10
            }
        },1000);
        phone = $('#phone').val()
        // 傳送手機號給檢視函式
        $.get('{% url "vc:sms" %}',{'phone':phone},'json')
    })

</script>

5.檢視函式

def send(request):
    sms = SMS('浮東源', 'SMS_102315005')
    phone = request.GET.get('phone')
    num = randint(1000, 9999)  # 驗證碼
    sms.send_sms(phone, num)
    return HttpResponse("code")