1. 程式人生 > >微信掃碼登錄實現

微信掃碼登錄實現

check ppc hid con values inf nco enum 用戶名

微信登錄驗證基於OAuth2.0

流程如下:

  1. 先申請公眾號 ,然後在公眾號裏面配置應用的return域名
  2. 讓用戶通過掃碼授權綁定微信號(綁定的時候就是將該用戶的unioid和自己系統中的用戶做一個對應關系,將unionid存下來)

具體程序流程:

A.通過初始url到微信獲取登錄二維碼(如果是手機端則會直接彈出是否授權)url包含你的appid 和 redirect_uri(接收微信返回信息的API地址)例子:https://open.weixin.qq.com/connect/qrconnect?appid=wxXXXXXXXXXXX&redirect_uri=https%3A%2F%2Fpassport.XYZ.cn%2Fpassport2%2Flogin%3Fappid%3DCxaOne%26scope%3Duserinfo%26returnurl%3Dhttp%253A%252F%252Fdemo3.XYZ.cn%252Fauth%253Fr%253Dhttps%25253A%25252F%25252Fdemo3.XYZ.cn%25252Fme&response_type=code&scope=snsapi_login&state=XXXXa5

B.用戶掃碼登錄/點擊授權後,微信會返回一個appid+code回來到接收微信返回信息的API地址

C.API獲取到code之後,通過appid+secret+code到微信獲取該微信用戶的信息,其中信息包括unionid(微信用戶唯一id),還會返回一個openid 這個id是你這個應用內部針對這個微信用戶的唯一id

D.如果正常返回unionid則表示用戶登錄成功,如果返回了errmsg,則失敗

代碼:

WechatLogin

技術分享圖片
 [Route("wechatlogin")]
        [HttpGet]
        [ResponseType(typeof
(EmployeeSession))] public IHttpActionResult WechatLogin() { var allUrlKeyValues = ControllerContext.Request.GetQueryNameValuePairs(); string appid = allUrlKeyValues.LastOrDefault(x => x.Key == "appid").Value; string state = allUrlKeyValues.LastOrDefault(x => x.Key == "
state").Value; string code = allUrlKeyValues.LastOrDefault(x => x.Key == "code").Value; //根據不同的appid,獲取不同的key,因pc端和手機端的appid不同 var oauth_app_key = ConfigurationManager.AppSettings[appid]; string send_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + oauth_app_key + "&code=" + code + "&grant_type=authorization_code"; //發送並接受返回值 string result = HttpGet(send_url); if (result.Contains("errmsg")) { throw new Exception(result);//登錄失敗 } try { //取到對應的unionid等信息 Dictionary<string, object> ssoUserInfo = JsonConvert.DeserializeObject<Dictionary<string, object>>(result); //初始化時使用模板數據庫 var initialContext = new ApolloAppContextImp(ConfigurationManager.AppSettings["CLIENT_DB_TEMPLATE_NAME"]); using (var serviceContext = new ServiceContext(initialContext)) { var loginDataWeChat = serviceContext.AuthenticationService.GetCurrentLoginDataWeChat(ssoUserInfo); if (null != loginDataWeChat) {//已綁定,使用真實公司名稱進入登錄流程,並返回EmployeeSession initialContext = new ApolloAppContextImp(loginDataWeChat.ClientId); using (var serviceContextClient = new ServiceContext(initialContext)) { var employeeSession = serviceContextClient.AuthenticationService.WechatLogin(ssoUserInfo, loginDataWeChat); return Ok(employeeSession); } } else //未綁定,彈出公司ID,用戶名,密碼頁面,讓用戶進行綁定 //用戶輸入後,mapping表添加數據 { HttpContext.Current.Session["ssoUserInfo"] = ssoUserInfo;//暫存到session,往loginDataWeChat添加紀錄的時候需要 var employeeSession = new EmployeeSession(); employeeSession.HasBeenBindWechat = false; return Ok(employeeSession); } } } catch (Exception ex) { throw new Exception(ex.Message); } }
View Code

WechatLoginbind

技術分享圖片
[Route("wechatloginbind")]
        [HttpPost]
        [ResponseType(typeof(EmployeeSession))]
        public IHttpActionResult WechatLoginbind(UserCredentials userCredentials)
        {
            var initialContext = new ApolloAppContextImp(userCredentials.ClientName);
            //This is all we know at the moment. If the client id is wrong, it will be handled in the exception.
            try
            {
                using (var serviceContext = new ServiceContext(initialContext))
                {
                    EmployeeSession employeeSession;
                    Dictionary<string, object> ssoUserInfo = HttpContext.Current.Session["ssoUserInfo"] as Dictionary<string, object>;
                    if (serviceContext.AuthenticationService.UserLoginCheckAndBind(userCredentials, ssoUserInfo, out employeeSession))
                    {
                        return Ok(employeeSession);
                    }
                    else
                    {
                        throw new ApiException(ExceptionLevel.Normal, ExceptionCode.UnAuthorized, "You have provided the wrong credentials.Please check your entries again.");
                    }
                }
            }
            catch (ClientNotFoundException)
            {
                var appContext = new ApolloAppContextImp(userCredentials.ClientName);
                using (var serviceContext = new ServiceContext(appContext))
                {
                    throw new ApiException(ExceptionLevel.Critical, ExceptionCode.NotFound, serviceContext.GlobalizationService.GetLocalizationMessage(MessageDictionary.CLIENT_NOT_FOUND, CXA.Common.Enums.Globalization.LanguageEnum.enus, userCredentials.ClientName));
                }
            }
        }
        public static string HttpGet(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                var result = client.GetAsync(url).Result;
                if (result.IsSuccessStatusCode == true)
                {
                    return result.Content.ReadAsStringAsync().Result;
                }
                else
                {
                    return "errmsg:" + result.Content.ReadAsStringAsync().Result;
                }
            }
        }
View Code

需要註意的就是pc端和手機端對微信來說屬於不同的應用

微信掃碼登錄實現