微信掃碼登錄網站,且與小程序打通。html
1.申請微信開放平臺網站應用。前端
2.你須要Appid和secretjson
3.設置你的回調域名。是回調域名,不是回調方法地址小程序
4.申請好了以後就能夠寫代碼啦api
4.1.獲取二維碼。按照官方文檔,有兩種方式,一種是後臺獲取,返回一個html。另外一種是前端js獲取。如今咱們主要說後臺獲取緩存
/// <summary> /// 掃碼登錄請求 /// 第一步獲取返回的code /// </summary> [HttpGet] public void ScanLogin() { BaseBLL<weixin_open> bll = new BaseBLL<weixin_open>(); var weixin_open = bll.Find(o => o.appid != null && o.secret != null); string appid = weixin_open.appid; string secret = weixin_open.secret; string server = Util.getServerPath(); string redirect_uri = System.Web.HttpUtility.UrlEncode("掃碼成功後跳轉的頁面,須要此頁面調用獲取下一步獲取access_token和用戶信息的方法"); LogHelper.Info("redirect_uri:" + redirect_uri); string state = sys.getRandomCode(16);//隨機生成 //緩存state HttpContext.Current.Session["weixin_login_state"] = state; WeixinOpenAPI api = new WeixinOpenAPI(appid, secret); LogHelper.Info(api.GetCode("登錄的code:" + redirect_uri, state)); string result = api.GetCode(redirect_uri, state); result = result.Replace("/connect/qrcode/", "https://open.weixin.qq.com/connect/qrcode/"); HttpContext.Current.Response.Write(result); HttpContext.Current.Response.End(); }
/// <summary> /// 第一步:請求CODE /// </summary> /// <param name="redirect_uri">回調域名</param> /// <param name="state"></param> public string GetCode(string redirect_uri,string state) { string url = "https://open.weixin.qq.com/connect/qrconnect?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_login&state=" + state + "#wechat_redirect"; string s = Util.MethodGET(url); return s; }
調用結果微信
4.2.掃碼成功後會調到回調頁,在回調頁面請求access_token與openidcookie
/// <summary> /// 回調函數 /// </summary> /// <param name="code">請求微信返回的code</param> /// <param name="state">請求微信的參數state</param> /// <returns></returns> public ApiResult LoginReturn(string code, string state) { ApiResult apiResult = new ApiResult(); LogHelper.Info("code:" + code + ",state:" + state); //必須用cookie或者session var session = HttpContext.Current.Session["weixin_login_state"]; string session_state = session == null ? "" : session.ToString(); if (state == _state) { BaseBLL<weixin_open> bll = new BaseBLL<weixin_open>(); var weixin_open = bll.Find(o => o.appid != null && o.secret != null); string appid = weixin_open.appid; string secret = weixin_open.secret; WeixinOpenAPI api = new WeixinOpenAPI(appid, secret); api.GetAccessToken(code); LogHelper.Info("access_token:" + api.access_token); string user_json = api.GetUserInfo(api.openid); LogHelper.Info("user_json:" + user_json); JObject obj = JObject.Parse(user_json); string openid = obj["openid"] == null ? "" : obj["openid"].ToString(); LogHelper.Info("openid:" + openid); BaseBLL<weixin_applet> weixinAppletBll = new BaseBLL<weixin_applet>(); weixin_applet weixinApplet = weixinAppletBll.Find(x => x.appcode == "ZHIYIN"); weixin_user userInfo = new weixin_user { openid = obj["openid"] == null ? "" : obj["openid"].ToString(), unionid = obj["unionid"] == null ? "" : obj["unionid"].ToString(), nickname = obj["nickname"] == null ? "" : obj["nickname"].ToString(), sex = obj["sex"] == null ? 0 : int.Parse(obj["sex"].ToString()), language = obj["language"] == null ? "" : obj["language"].ToString(), city = obj["city"] == null ? "" : obj["city"].ToString(), province = obj["province"] == null ? "" : obj["province"].ToString(), country = obj["country"] == null ? "" : obj["country"].ToString(), headimgurl = obj["headimgurl"] == null ? "" : obj["headimgurl"].ToString(), source_code = weixinApplet.appcode, weixin_applet_id = weixinApplet.id }; if (!Util.isNotNull(openid)) { return new ApiResult() { success = false, message = "openid爲空" }; } #region 微信登錄,保存信息 //若是不存在則要建立,建立時,先建立 iuser ,再建立 weixin_user bool first_login = false; BaseBLL<weixin_user> weixinUserBll = new BaseBLL<weixin_user>(); if (Util.isNotNull(userInfo.unionid)) { var weixinUser = weixinUserBll.Find(o => o.unionid == userInfo.unionid); //多是第一次登錄,在網頁端登錄 if (weixinUser == null) { first_login = true; //先存iuser var iuser = new iuser(); BaseBLL<iuser> iuserBll = new BaseBLL<iuser>(); iuser.random = sys.getRandomStr(); iuser.createtime = DateTime.Now; iuser.updatetime = DateTime.Now; iuser = iuserBll.Add(iuser); //再存weixin_user userInfo.uid = iuser.id; userInfo.sub_time = DateTime.Now; userInfo.first_sub_time = DateTime.Now; LogHelper.Info("first_login:" + first_login + ",userInfo:" +Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUser = weixinUserBll.Add(userInfo); } else { weixinUser.nickname = userInfo.nickname; weixinUser.headimgurl = userInfo.headimgurl; LogHelper.Info("first_login:" + first_login + ",userInfo:" + Newtonsoft.Json.JsonConvert.SerializeObject(userInfo)); weixinUserBll.Update(weixinUser); } apiResult.success = true; apiResult.data = new { first_login = first_login, weixinUser = weixinUser }; apiResult.status = ApiStatusCode.OK; } else { return new ApiResult() { success = false, message = "微信開發平臺未獲取到unionid" }; } #endregion } else { return new ApiResult() { success = false, message = "請求超時" }; } return apiResult; }
/// <summary> /// 第二步:獲取access_token /// </summary> /// <param name="code"></param> /// <returns></returns> public void GetAccessToken(string code) { string s = Util.MethodGET("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code", "UTF-8"); try { LogHelper.Info("code換取access_token:" + s); JObject jo = JObject.Parse(s); access_token = jo["access_token"].ToString(); access_token_time = System.DateTime.Now.AddSeconds(double.Parse(jo["expires_in"].ToString())).ToString(); refresh_token = jo["refresh_token"].ToString(); openid = jo["openid"].ToString(); } catch (Exception e) { LogHelper.Error("獲取微信開發平臺access_token失敗:" + e.Message); } }
/// <summary> /// 第三步:獲取用戶信息 /// </summary> /// <returns></returns> public string GetUserInfo(string openid) { string url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid; return Util.MethodGET(url, "UTF-8"); }
如此如此,這般這般就算是完了session