1. 程式人生 > >個人網站實現掃碼登入asp.net 掃碼登入

個人網站實現掃碼登入asp.net 掃碼登入

後臺處理: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Asxsyd92.Entity;
using System.Web.SessionState;
namespace 愛上歆隨懿恫.asxsyd92
{
    /*===========================================================================
    // Copyright (C) 2016  愛上歆隨懿恫
    // 作者: 愛上歆隨懿恫    郵箱:
[email protected]
qq:1316227882
    // 功能描述:登入功能


    // 更新日期:2016年3月28日     更新人:陳良富      更新原因/內容
    //
    ===========================================================================*/
    public class Handler1 : IHttpHandler, IRequiresSessionState
    {
        System.Web.Script.Serialization.JavaScriptSerializer jsS = new System.Web.Script.Serialization.JavaScriptSerializer();
        string result = string.Empty;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string type = context.Request["type"];
            if (string.IsNullOrEmpty(type))
            {
                context.Response.Write(result = jsS.Serialize(new { Success = false, data = "", msg = "無效請求!" }));
            }
            else {
                switch (type) {
                    case "login": Login(context); break;
                    case "reg": Reg(context); break;
                    case "creatqrcde": Qrcode(context); break;
                    case "check": CheckQrcode(context); break;
                    case "appcheck": AppCheckQrcode(context); break;
                    default: break;
                }
            }
         




        }
        #region+手機端掃描
        /// <summary>
        /// 手機端掃描驗證
        /// </summary>
        /// <returns></returns>
        private void AppCheckQrcode(HttpContext context)
        {
            var user = context.Request["user"];
            var u_qrcde = context.Request["u_qrcde"];
            if (string.IsNullOrEmpty(user) && string.IsNullOrEmpty(u_qrcde))
            {
                context.Response.Write(result = jsS.Serialize(new { msg = "無效請求", Success = false }));
            
            }
            else {
                Asxsyd92.Entity.login d = new login();
                if (d.Update(u_qrcde,user))
                {
                    context.Response.Write(result = jsS.Serialize(new { msg = "掃描成功", Success = true, User = user, Qrcode = u_qrcde }));
                }
                else {
                    context.Response.Write(result = jsS.Serialize(new { msg = "掃描異常", Success = false }));
                }
               
            }
        }
        #endregion
        #region+註冊模組
        /// <summary>
        /// 註冊模組
        /// </summary>
        /// <returns></returns>
        private void Reg(HttpContext context)
        {
            try
            {
                string user = context.Request["reguser"];
                string pw = context.Request["regpw"];
                if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pw))
                {
                    context.Response.Write(result = jsS.Serialize(new { Success = false, data = "", msg = "使用者名稱或者密碼不能為空!" }));
                }
                else
                {


                    Asxsyd92.Entity.login d = new login();


                    if (d.goreg(user, pw))
                    {


                        context.Response.Write(result = jsS.Serialize(new { msg = "恭喜成功!", Success = true }));
                    }
                    else
                    {
                        context.Response.Write(result = jsS.Serialize(new { msg = "對不起,公測版禁止註冊請以測試使用者登入,使用者名稱和密碼admin", Success = false }));
                    }


                }


            }
            catch (Exception e)
            {
                context.Response.Write(result = jsS.Serialize(new { msg = e.Message, Success = false }));
            }
        }
        #endregion
        #region+登入模組
        /// <summary>
        /// 登入模組
        /// </summary>
        /// <returns></returns>
        public void Login( HttpContext context) {
            try
            {
                string user = context.Request["user"];
                string pw = context.Request["pw"];
                if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(pw))
                {
                    context.Response.Write(result = jsS.Serialize(new { Success = false, data = "", msg = "使用者名稱或者密碼不能為空!" }));
                }
                else
                {
                    Asxsyd92.Entity.login d = new login();


                    if (d.gologin(user.ToString().Trim(), pw.ToString().Trim()))
                    {
                        System.Web.HttpContext.Current.Session["user"] = user.ToString().Trim();
                        context.Response.Write(result = jsS.Serialize(new { msg = "登入成功!", Success = true }));
                    }
                    else
                    {
                        context.Response.Write(result = jsS.Serialize(new { msg = "使用者名稱或者密碼!", Success = false }));
                    }
                }
            }
            catch (Exception e) {
                context.Response.Write(result = jsS.Serialize(new { msg = e.Message, Success = false }));
            }
        }
        #endregion
        #region+生成二維碼字串
        /// <summary>
        /// 生成二維碼字串
        /// </summary>
        /// <returns></returns>
        public void Qrcode(HttpContext context) {
            Asxsyd92.Tools.Tool.Token t = new Asxsyd92.Tools.Tool.Token();
            Asxsyd92.Entity.login d = new login();
            string qrcode = t.Create().ToString().ToLower();
            d.AddQrcde(qrcode);
            context.Session["qrcode"] = qrcode;
            context.Response.Write(result = jsS.Serialize(new { msg = "獲取成功!", Success = true, Qrcode = qrcode }));
        }
        #endregion
        #region+迴圈檢查手機登入狀態
        /// <summary>
        /// +迴圈檢查手機登入狀態
        /// </summary>
        /// <returns></returns>
        public void CheckQrcode(HttpContext context)
        {
            Asxsyd92.Entity.login d = new login();


            if (context.Session["qrcode"] == null)
            {
                context.Response.Write(result = jsS.Serialize(new { msg = "驗證碼失效!", Success = false }));
            }
            else
            {
                var ks = d.UserQrcdeLogin(context.Session["qrcode"].ToString());
                if (ks != null)
                {
                    context.Session["user"] = ks;
                    context.Response.Write(result = jsS.Serialize(new { msg = "登入成功", Success = true, user = ks }));
                }
                else
                {
                    context.Response.Write(result = jsS.Serialize(new { msg = "請用手機掃描二維碼", Success = false }));
                }
            }


        }
        #endregion
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

後臺包含pc端和手機端看看原始碼就知道了, 手機端獲取二維碼程式碼片段:
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    //顯示掃描到的內容
                    mTts.startSpeaking("正在處理請稍等。", mTtsListener);
                    webView.loadUrl("http://182.254.140.26/app/weblogin.html?id="+bundle.getString("result"));
                }
                break;
        }
    } 
接下來看看WebApp處理程式碼(片段) 
     <script>
        $(function () {
            if (window.sessionStorage["user"] == null || window.sessionStorage["user"] == undefined) {
                window.location.href = "login1.html";
            } else {
                $.ajax({
                    type: "Post",
                    url: "../asxsyd92/ashx/Login.ashx",
                    data: { type: "appcheck", u_qrcde: GetQueryString("id"), user: window.sessionStorage["user"] },
                    dataType: "json",
                    success: function (data) {
                        if (data.Success) {
                            show_msg(data.msg, "index.html");
                      }
                        else {
                             show_err_msg(data.msg);
                        }
                    },
                    error: function () {
                          show_err_msg('請求超時!');
                    }
                });
            }
            });
        function GetQueryString(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    </script>
pc端生的處理程式碼:
 $(function () {
    $('#_qrcode').click(function () {
        if ($('#zy').val() == "zh") {
            $('#login_form').hide();
            $("#qrcodeTable").show();
            $('#zy').val('er');
            $('#_qrcode').addClass('btn-account');
            $('#_qrcode').removeClass('btn-code');
            loingshow("正在搬運二維碼");
            $.ajax({
                type: "Post",
                url: "../../asxsyd92/ashx/Login.ashx",
                data: { type: "creatqrcde" },
                dataType: "json",
                success: function (data) {
                    if (data.Success) {
                    
                        asxsyd92.createQrcode(data.Qrcode);
                        $('.msg_bg').remove();
                        $('.sub_err').remove();
                        check();
                    }
                    else {
                         show_err_msg(data.msg);
                    }
                },
                error: function () {
                      show_err_msg('請求超時!');
                }
            });
           // 
        } else {
   
            $("#qrcodeTable").hide();
            $('#login_form').show();
            $('#zy').val('zh');
    
     
         $('#_qrcode').addClass('btn-code');
            $('#_qrcode').removeClass('btn-account');
        }
    });
    if (window.sessionStorage["user"] != null || window.sessionStorage["user"] != undefined) {
        show_msg('您已登入!  正在為您跳轉...', "/");
    } else {


        //提交表單
        $('#submit_btn').click(function () {


            //var myReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/; //郵件正則
            //if ($('#email').val() == '') {
            //    show_err_msg('使用者名稱不能為空!');
            //    $('#email').focus();
            //}else 
            //var inputCode = document.getElementById("inputCode").value;
            //if (inputCode.length <= 0) {
            //    alert("請輸入驗證碼!");
            //}
            //else if (inputCode.toUpperCase() != code.toUpperCase()) {
            //    alert("驗證碼輸入有誤!");
            //    createCode();
            //}
            //else {
            //    alert("驗證碼正確!");
            //}


            if ($('#email').val() == '') {
                show_err_msg('使用者名稱不能為空!');
                $('#email').focus();
            } else if ($('#password').val() == '') {
                show_err_msg('密碼還沒填呢!');
                $('#password').focus();
            } else if ($('#j_captcha').val() == '') {
                show_err_msg('請輸入驗證碼!');
                $('#j_captcha').focus();
             
                asxsyd92.createCode();
            }
            else {


                if ($('#j_captcha').val().toUpperCase() == window.sessionStorage["code"].toUpperCase()) {
                    loingshow("親!正在為您拼命載入,請稍等。。。");
                    $.ajax({
                        type: "Post",
                        url: "../../asxsyd92/ashx/Login.ashx",
                        data: { user: $('#email').val(), pw: $('#password').val(), type: "login" },
                        dataType: "json",
                        success: function (data) {
                            $('.msg_bg').remove();
                            $('.sub_err').remove();
                            if (data.Success) {
                                window.sessionStorage["user"] = $('#email').val();
                                sessionStorage.removeItem("code");
                                show_msg('登入成功咯!  正在為您跳轉...', "/");
                            } else {
                                show_err_msg(data.msg);
                                asxsyd92.createCode();
                            }
                        },
                        error: function () {
                            show_err_msg('請求超時!');
                            sessionStorage.removeItem("code");
                            asxsyd92.createCode();
                        }
                    });
                } else {
                    show_err_msg('驗證碼錯誤!');
                    sessionStorage.removeItem("code");
                    asxsyd92.createCode();
                }
            }
        });


        $('#submit_btn_reg').click(function () {
            if ($('#user').val() == '') {
                show_err_msg('使用者名稱不能為空!');
                $('#user').focus();
            } else if ($('#pw').val() == '') {
                show_err_msg('密碼還沒填呢!');
                $('#pw').focus();
            } else if ($('#npw').val() == '') {
                show_err_msg('密碼還沒填呢!');
                $('#npw').focus();
            }
            else if ($('#pw').val() != $('#npw').val()) {
                show_err_msg('親!兩次輸入密碼不一致!');
            }
            else {
                loingshow("親!正在為您註冊,請稍等片刻。。。");
                $.ajax({
                    type: "Post",
                    url: "../../asxsyd92/ashx/Login.ashx",
                    data: { reguser: $('#user').val(), regpw: $('#pw').val(), type: "reg" },
                    dataType: "json",
                    success: function (data) {
                        $('.msg_bg').remove();
                        $('.sub_err').remove();
                        if (data.Success) {
                            show_err_msg(data.msg);
                            $('#regModal').modal('hide');
                        } else {
                            show_err_msg(data.msg);
                        }
                    },
                    error: function () {
                        show_err_msg('請求超時!');
                    }
                });
            }
        });
    }
});
var tz;
function check() {
    $.ajax({
        type: "Post",
        url: "../../asxsyd92/ashx/Login.ashx",
        data: { type: "check" },
        dataType: "json",
        success: function (data) {
            if (data.Success) {
                window.sessionStorage["user"] = data.user;
                show_msg('掃描成功正在為您登入...', "/");
                // alert(data.msg);
                clearInterval(tz);


            }
            else {
                tz = setInterval(check, 5000);
                // show_err_msg(data.msg);
            }
        },
        error: function () {
            //  show_err_msg('請求超時!');
        }
    });
};
function tingzhi() {
    alert("停止");
    clearInterval(tz);
}
setTimeout(tingzhi, 1000 * 60 * 2);