1. 程式人生 > >python 實現傳送手機簡訊驗證碼後臺方法

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":"[email protected]", 
              "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);
	    	
	    	
	    });