python 实现发送手机短信验证码后台方法

1、生成4位数字验证码

def createPhoneCode(session):
    chars=['0','1','2','3','4','5','6','7','8','9']
    x = random.choice(chars),random.choice(chars),random.choice(chars),random.choice(chars)
    verifyCode = "".join(x)
    session["phoneVerifyCode"] = {"time":int(time.time()), "code":verifyCode}
    return verifyCode

2、发送给外部短信接口(post方式)

def sendTelMsg(msg, phoneID):
    SendTelMsgUrl="http://www.810086.com.cn/jk.aspx"
    params = {"zh":"china",  "mm":"china@10086", 
              "hm":phoneID,"nr":msg,"sms_type":88}
    postData=urllib.urlencode(params)
    req = urllib2.Request(SendTelMsgUrl, postData)
    req.add_header('Content-Type', "application/x-www-form-urlencoded")
    respone = urllib2.urlopen(req)
    res = respone.read()
    return res

其中session参数是django urls.py 后台方法 以request.session传入


3、前端js

	    $("button[name=getVerifyBt]").bind("click", function(){
	    	var self = this;
	    	var userPhoneEl = $("input[name=phoneNum]");
	    	var userPhone = $.trim(userPhoneEl.val());
	    	if (userPhone == ""){
	    		alert("请填写号码!");
	    		return;
	    	}
	    	$.get("/getPhoneVerifyCode/"+userPhone + "/")
	    	.success(function(msg){
	    		console.info(msg);
	    		var ddEl = $(self).siblings("dd.showTag");
	    		if(msg == "ok"){
	    			ddEl.find("span").hide();
	    			ddEl.find("span[name=success]").show();
	    		}else{
	    			ddEl.find("span").hide();
	    			ddEl.find("span[name=error]").show();	    			
	    		}
	    	})
	    	.error(function(msg){
	    		console.info(msg);
	    	});
	    	var step = 60;
	    	$(this).attr("disabled", true);	
	    	$(this).html("重新发送"+step);
	    	var interThread = setInterval(function(){
	    		step-=1;
	    		$(self).html("重新发送"+step);
	    		if(step <=0){
	    			$(self).removeAttr("disabled");
	    			$(self).html("获取验证码");
	    			clearInterval(interThread);
	    		}
	    	}, 1000);
	    	
	    	
	    });


你可能感兴趣的:(python 实现发送手机短信验证码后台方法)