public CommEntityUpdater(WxConfig wxConfig, JzDbContext db) { _wxConfig = wxConfig; this.db = db; basicToken = db.BasicTokens.FirstOrDefault(); if (basicToken == null) { LogService.GetInstance().AddLog("CommEntityUpdater:ctor", null, "Create a new basic token record", "", "Info"); basicToken = new BasicToken(); db.BasicTokens.Add(basicToken); db.SaveChanges(); } else if (string.IsNullOrEmpty(ComponentKeys.GetInstance().VerifyData.Ticket)) { //load token from db to memory when component ticket is null ComponentKeys.GetInstance().VerifyData.Ticket = basicToken.Ticket; ComponentKeys.GetInstance().VerifyData.RefreshOn = basicToken.TicketRefreshOn; ComponentKeys.GetInstance().AccessData.AccessCode = basicToken.AccessToken; ComponentKeys.GetInstance().AccessData.ExpiresIn = basicToken.AccessTokenExpiresIn; ComponentKeys.GetInstance().AccessData.RefreshOn = basicToken.AccessTokenRefreshOn; ComponentKeys.GetInstance().PreAuthData.PreAuthCode = basicToken.PreAuthCode; ComponentKeys.GetInstance().PreAuthData.RefreshOn = basicToken.PreAuthCodeRefreshOn; ComponentKeys.GetInstance().PreAuthData.ExpiresIn = basicToken.PreAuthCodeExpiresIn; } }
public override string OnAuthorizedRequest(RequestMessageAuthorized requestMessage) { // create new entity AppAuthInfo appInfo = new AppAuthInfo(); appInfo.AuthorizerAppId = requestMessage.AuthorizerAppid; // db table key appInfo.AppId = requestMessage.AppId; // 第三方平台的 appid appInfo.Authorized = true; appInfo.Code = requestMessage.AuthorizationCode; appInfo.ExpiredTime = requestMessage.AuthorizationCodeExpiredTime; appInfo.CreateOn = DateTime.Now; appInfo.LastUpdateOn = DateTime.Now; //, var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, requestMessage.AuthorizerAppid); var authorizerInfo = authorizerInfoResult.authorizer_info; var authorizerInfoEntity = new JinZhou.Models.DbEntities.AuthorizerInfo() { UserName = authorizerInfo.user_name, NickName = authorizerInfo.nick_name, HeadImg = authorizerInfo.head_img, ServiceType = (int)authorizerInfo.service_type_info.id, VerifyType = (int)authorizerInfo.verify_type_info.id, PrincipalName = authorizerInfo.principal_name, BizStore = authorizerInfo.business_info.open_store, BizPay = authorizerInfo.business_info.open_pay, BizCard = authorizerInfo.business_info.open_card, BizScan = authorizerInfo.business_info.open_scan, BizShake = authorizerInfo.business_info.open_shake, Alias = authorizerInfo.alias, QrcodeUrl = authorizerInfo.qrcode_url }; appInfo.Authorizer = authorizerInfoEntity; db.AppAuths.Add(appInfo); db.SaveChanges(); return(base.OnAuthorizedRequest(requestMessage)); }
public void Update() { if (ComponentKeys.GetInstance().AccessData.ExpireAfterSecs(600)) { UpdateAccessData(); } if (ComponentKeys.GetInstance().PreAuthData.ExpireAfterSecs(600)) { UpdatePreAuthCode(); } try { db.SaveChanges(); } catch (Exception ex) { LogService.GetInstance().AddLog("CommEntityUpdater:Update", null, "Saving changes to db", ex.Message, "Error"); } }
public IActionResult UserAuth(string code, string state, string appid) { try { if (string.IsNullOrEmpty(appid)) { return(Content("无效的请求")); } string wxAuthRedirectUri = _wxConfig.UserAuthRedirectUri; string wxAuthUrlFmt = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state={2}&component_appid={3}#wechat_redirect"; //state is null indicates it's first time to get here. if (string.IsNullOrEmpty(state)) { //第一次进入,跳转到微信授权页 string wxAuthUrl = string.Format(wxAuthUrlFmt, appid, HttpUtility.UrlEncode(wxAuthRedirectUri), "wxAuth1stStep", _wxConfig.AppId); LogService.GetInstance().AddLog("state", null, wxAuthUrl, "", "VISIT"); return(Redirect(wxAuthUrl)); } if (string.IsNullOrEmpty(code)) { // user reject the auth return(Content("用户未授权,无法继续。")); } LogService.GetInstance().AddLog("/Home/UserAuth", null, "获得用户授权提供的code。开始获取accesstoken", "", "Info"); //通过code换取access_token string wxAccessTokenUrlFmt = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={0}&code={1}&grant_type=authorization_code&component_appid={2}&component_access_token={3}"; string wxAccessTokenUrl = string.Format(wxAccessTokenUrlFmt, appid, code, _wxConfig.AppId, ComponentKeys.GetInstance().AccessData.AccessCode); LogService.GetInstance().AddLog("state", null, wxAccessTokenUrl, "", "VISIT"); LogService.GetInstance().AddLog("state", null, "access token is " + ComponentKeys.GetInstance().AccessData.AccessCode, "", "AccessCode"); string accessTokenJsonStr = string.Empty; var handler = new HttpClientHandler(); handler.ServerCertificateCustomValidationCallback = new Func <HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool>(CheckValidationResult); HttpClient client = new HttpClient(handler); try {//TODO:解决SSL GET的问题 accessTokenJsonStr = client.GetStringAsync(wxAccessTokenUrl) .Result; //Senparc.CO2NET.HttpUtility.RequestUtility.HttpGet(wxAccessTokenUrl, null); } catch (Exception reqEx) { LogService.GetInstance().AddLog("state", null, "access token get failed " + reqEx.Message, null, "Exception"); } var accessTokenJsonObj = JObject.Parse(accessTokenJsonStr); var accessCode = accessTokenJsonObj.GetValue("access_token"); var openid = accessTokenJsonObj.GetValue("openid"); LogService.GetInstance().AddLog("/Home/UserAuth", null, "获取到Access code。开始获取用户信息", "", "Info"); //获取用户的基本信息 string wxUserInfoUrlFmt = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN"; string wxUserInfoUrl = string.Format(wxUserInfoUrlFmt, accessCode, openid); LogService.GetInstance().AddLog("state", null, wxUserInfoUrl, "", "VISIT"); string userInfoJsonStr = client.GetStringAsync(wxUserInfoUrl).Result; //Senparc.CO2NET.HttpUtility.RequestUtility.HttpGet(wxUserInfoUrl, null); var userInfoJsonObj = JObject.Parse(userInfoJsonStr); string openIdStr = openid.ToString(); var wxUserinfoEntity = db.WxUserInfos.FirstOrDefault(c => c.OpenId == openIdStr); if (wxUserinfoEntity == null) { wxUserinfoEntity = new WxUserInfo() { OpenId = userInfoJsonObj.GetValue("openid").ToString(), NickName = userInfoJsonObj.GetValue("nickname").ToString(), Sex = int.Parse(userInfoJsonObj.GetValue("sex").ToString()), Country = userInfoJsonObj.GetValue("country").ToString(), Province = userInfoJsonObj.GetValue("province").ToString(), City = userInfoJsonObj.GetValue("city").ToString(), HeadImgUrl = userInfoJsonObj.GetValue("headimgurl").ToString() }; JToken unionIdProperty = null; if (userInfoJsonObj.TryGetValue("unionid", out unionIdProperty)) { wxUserinfoEntity.UnionId = unionIdProperty.ToString(); } db.WxUserInfos.Add(wxUserinfoEntity); db.SaveChanges(); } return(Content("您好," + userInfoJsonObj.GetValue("nickname"))); } catch (Exception e) { return(Content(e.ToString())); } }