django send mobile verification code

1. Process analysis:

1. The user enters the mobile phone number at the front end of the project, and then clicks [Get Verification Code] to send the mobile phone number to the post to the background.

2. The background verifies whether the mobile phone number is legal and whether it has been occupied. If it passes the verification, a verification code is generated, and by running the script, the SMS operator sends the verification code to the mobile phone number. If the verification fails, an error is returned. information

3. After the user receives the SMS verification code, post all the information to the background again.

4. The data is verified in the background. If the verification is passed, the real-name system authentication is completed. If it fails, an error message will be returned.

In conclusion, one real-name verification requires two ajax+posts

2. Docking with SMS providers:

1. On the cloud network end:

1. Register with Yunpian.com

Address: https://www.yunpian.com/

Background management console page: the most important information in it is APIKEY

 

 2. Developer filing, new signature, and new template (template management)

1. The [test] in the background of Yunpian.com is meaningless. The so-called test is to send a text message directly to your mobile phone. What kind of test is this?

2. On the [Signature/Template Device] page, click [Add Signature] in [Signature Management], and you will be reminded to improve the [Developer Information]. The certification is divided into [Company] and [Individual] of the developer. In the testing phase, you can first select [Personal], and [Personal] want a photo of the ID card and submit the photo.

3. Wait for the SMS notification of the completion of the certification, and then follow the operation guidelines in the background to [Add Signature] on the [Signature Management] page, and [Add Template] on the [Template Management] page. There will be a text message notification when the review is approved.

 

 4. Set the IP whitelist in the background of Yunpian.com, and add the external network IP to the whitelist

 

 The easiest way to get the local external network ip is Baidu ip

2. Write a script to send SMS in the django project

Create a new utils directory in the project directory and create a new 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):
        parmas = {
             ' apikey ' : self.api_key,
             ' mobile ' : mobile,
             ' text ' : ' [**NET] Your verification code is {code}. If it is not done by me, please ignore this message ' .format(code= code)
        }
        # text must be consistent with the template content in the cloud backend, otherwise it cannot be sent! 
        r=requests.post(self.single_send_url,data= parmas)
         print (r)

if __name__=='__main__':
    yun_pian =YunPian( ' ***************(your apikey) ' )
    yun_pian.send_sms( ' ***(Verification code) ' , ' *******(Mobile phone number) ' )

3. Write and send mobile phone verification code related codes in the project:

1. Front-end related code:

<!-- Send button countdown code --> 
< script type = "text/javascript" > 
var countdown = 60 ;
 function settime(obj) {
     if (countdown ==  0 ) {
        obj.removeAttribute("disabled");
        obj.value = " Get verification code for free " ;
        countdown = 60;
        return;
    } else {
        obj.setAttribute("disabled", true);
        obj.value = " resend( "  + countdown +  " ) " ;
        countdown--;
    }
setTimeout(function() {
    settime(obj) }
    ,1000)
}

</script>


<!-- Mobile phone number input box code -->

<div class="form-group">
                    <label for="mobile" class="col-lg-2 col-sm-2 control-label">手机号码:</label>
                    <div class="col-lg-10">
                        <div class="input-group m-bot15">
                    <input type="text" class="form-control" id="mobile" name="mobile" placeholder="手机号码">
                    <span class="input-group-btn">
                         <input type ="button" id ="forcode" onclick ="settime(this)" value ="Get verification code for free" class ="btn btn-success" > 
                    </ span > 
                        </ div > 
                    < p class ="help -block" > Please fill in the bound mobile phone number </ p > 
                    </ div > 
                </ div >


<!-- Send phone number data to the background via ajax --> 
< script > 
    $( ' #forcode ' ).click( function () {
        $.ajax({
            cache:false,
            type:"POST",
            url:"{% url 'users:forcode' %}",
            data:{
               csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val(),
               mobile:$("#mobile").val()
            },
            async:true,
            success:function (data) {
                alert(data)
            }
        })
    })
</script>

Effect picture:

2. Write the code related to sending the verification code in users/views.py:

import re
import random
from xyw.settings import APIKEY
from .models import VerifyCode


class ForCodeView(View):
     """ Get mobile phone verification code """ 
    def post(self,request):
        mobile =request.POST.get( ' mobile ' , '' )
         if mobile:
             #Verify whether it is a valid mobile phone number 
            mobile_pat=re.compile( ' ^(13\d|14[5|7]|15\d|166 |17\d|18\d)\d{8}$ ' )
            res = re.search(mobile_pat,mobile)
             if res:
                 #Generate mobile phone verification code 
                code= VerifyCode()
                code.mobile = mobile
                c = random.randint (1000,9999 )
                code.code=str(c)
                code.save()
                code=VerifyCode.objects.filter(mobile=mobile).first().code
                yunpian = YunPian(APIKEY)
                sms_status=yunpian.send_sms(code=code,mobile=mobile)
                msg=sms_status.msg
                return HttpResponse(msg)
            else:
                msg = ' Please enter a valid mobile phone number! ' 
                return HttpResponse(msg)
         else :
            msg = ' The phone number cannot be empty! ' 
            return HttpResponse(msg)

3. In users/urls.py:

from .views import ForCodeView
......

urlpatterns = [

    ......
    path('forcode/',ForCodeView.as_view(),name='forcode'),
]

4. Add code to settings.py:

#yunpianwang apikey 
APIKEY='Your Yunpianwang's apikey'

So far, the function of sending mobile phone verification code is completed.

In fact, there are also places that can be optimized:

1. Although the front-end is set for 60 seconds before it can be resent, this verification should also be available on the back-end to prevent it from being used by people with intentions.

2. There is no verification whether the mobile phone number has been sent a verification code

3. The verification code does not have a life cycle, and the verification code should be invalidated after a period of time.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324778098&siteId=291194637