/// <summary> /// 获取可用的GetAuthorizerInfoResult /// </summary> /// <param name="componentAppId"></param> /// <param name="authorizerAppid"></param> /// <param name="getNewTicket">是否强制重新获取新的Ticket</param> /// <returns></returns> ///// <exception cref="WeixinOpenException">此公众号没有高级权限</exception> public static GetAuthorizerInfoResult GetAuthorizerInfoResult(string componentAppId, string authorizerAppid, bool getNewTicket = false) { TryRegister(componentAppId, authorizerAppid); var authorizerBag = TryGetItem(authorizerAppid); using (Cache.BeginCacheLock(LockResourceName + ".GetAuthorizerInfoResult", authorizerAppid))//同步锁 { //更新AuthorizerInfo if (getNewTicket || authorizerBag.AuthorizerInfo.user_name == null) { var componentVerifyTicket = ComponentContainer.TryGetComponentVerifyTicket(componentAppId); var componentAccessToken = ComponentContainer.GetComponentAccessToken(componentAppId, componentVerifyTicket); //已过期,重新获取 var getAuthorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentAccessToken, componentAppId, authorizerAppid);//TODO:如果是过期,可以通过刷新的方式重新获取 //AuthorizerInfo authorizerBag.AuthorizerInfo = getAuthorizerInfoResult.authorizer_info; //AuthorizationInfo var getAuthorizationInfoResult = GetAuthorizationInfo(componentAppId, authorizerAppid, getNewTicket); authorizerBag.AuthorizationInfo = getAuthorizationInfoResult; //var componentBag = ComponentContainer.TryGetItem(componentAppId); //if (string.IsNullOrEmpty(authorizerBag.AuthorizerInfoResult.authorization_info.authorizer_access_token)) //{ // //账号没有此权限 // throw new WeixinOpenException("此公众号没有高级权限", componentBag); //} } } return(authorizerBag.FullAuthorizerInfoResult); }
private AuthorizerInfo GetAuthorizationInfo(string authorizerAppId) { string token = ZRui.Web.BLL.AuthorizerHelper.GetComponentAccessToken(); GetAuthorizerInfoResult authorizerInfoResult = ComponentApi.GetAuthorizerInfo(token, wechatOpenOptions.AppId, authorizerAppId, 0x2710); return(authorizerInfoResult.authorizer_info); }
public void RefreshAuthorizerTokenTest() { var componentAccessTokenResult = ComponentContainer.GetComponentAccessTokenResult(base._appId, base._ticket); Assert.IsNotNull(componentAccessTokenResult.component_access_token); var authorizerId = "wxd7a61edcdce336b0"; var authorizerInfo = ComponentApi.GetAuthorizerInfo(componentAccessTokenResult.component_access_token, base._appId, authorizerId); var authorizer_access_token = authorizerInfo.authorization_info.authorizer_access_token; var authorizer_refresh_token = authorizerInfo.authorization_info.authorizer_refresh_token; Assert.IsNotNull(authorizerInfo.authorization_info.authorizer_access_token); Assert.IsNotNull(authorizerInfo.authorization_info.authorizer_refresh_token); Console.WriteLine("authorizer_access_token:" + authorizer_access_token); Console.WriteLine("authorizer_refresh_token:" + authorizer_refresh_token); var result = ComponentApi.RefreshAuthorizerToken(componentAccessTokenResult.component_access_token, base._appId, authorizerId, authorizerInfo.authorization_info.authorizer_refresh_token); ; Console.WriteLine("authorizer_access_token:" + result.authorizer_access_token); Console.WriteLine("authorizer_access_token:" + result.authorizer_refresh_token); }
/// <summary> /// 获取可用的GetAuthorizerInfoResult /// </summary> /// <param name="componentAppId"></param> /// <param name="authorizerAppid"></param> /// <param name="getNewTicket">是否强制重新获取新的Ticket</param> /// <returns></returns> ///// <exception cref="WeixinOpenException">此公众号没有高级权限</exception> public static GetAuthorizerInfoResult GetAuthorizerInfoResult(string componentAppId, string authorizerAppid, bool getNewTicket = false) { TryRegister(componentAppId, authorizerAppid); var authorizerBag = ItemCollection[authorizerAppid]; lock (authorizerBag.Lock) { if (getNewTicket || authorizerBag.AuthorizationInfoExpireTime <= DateTime.Now) { var componentVerifyTicket = ComponentContainer.TryGetComponentVerifyTicket(componentAppId); var componentAccessToken = ComponentContainer.GetComponentAccessToken(componentAppId, componentVerifyTicket); //已过期,重新获取 var getAuthorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentAccessToken, componentAppId, authorizerAppid);//TODO:如果是过期,可以通过刷新的方式重新获取 TryUpdateAuthorizationInfo(authorizerAppid, getAuthorizerInfoResult.authorization_info); var authorizer_info = getAuthorizerInfoResult.authorizer_info; authorizerBag.AuthorizerInfo = authorizer_info; //var componentBag = ComponentContainer.TryGetItem(componentAppId); //if (string.IsNullOrEmpty(authorizerBag.AuthorizerInfoResult.authorization_info.authorizer_access_token)) //{ // //账号没有此权限 // throw new WeixinOpenException("此公众号没有高级权限", componentBag); //} } } return(authorizerBag.AuthorizerInfoResult); }
/// <summary> /// 获取可用的GetAuthorizerInfoResult /// </summary> /// <param name="componentAppId"></param> /// <param name="authorizerAppid"></param> /// <param name="getNewTicket">是否强制重新获取新的Ticket</param> /// <returns></returns> /// <exception cref="WeixinOpenException">此公众号没有高级权限</exception> public static GetAuthorizerInfoResult GetAuthorizerInfoResult(string componentAppId, string authorizerAppid, bool getNewTicket = false) { if (!CheckRegistered(authorizerAppid)) { throw new WeixinException("此authorizer_appid尚未注册,请先使用AuthorizerContainer.Register完成注册(全局执行一次即可)!"); } var authorizerBag = ItemCollection[authorizerAppid]; lock (authorizerBag.Lock) { if (getNewTicket || authorizerBag.AuthorizerInfoExpireTime <= DateTime.Now) { var componentVerifyTicket = ComponentContainer.TryGetComponentVerifyTicket(componentAppId); var componentAccessToken = ComponentContainer.GetComponentAccessToken(componentAppId, componentVerifyTicket); //已过期,重新获取 authorizerBag.AuthorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentAccessToken, componentAppId, authorizerAppid);//TODO:如果是过期,可以通过刷新的方式重新获取 var componentBag = ComponentContainer.TryGetItem(componentAppId); if (string.IsNullOrEmpty(authorizerBag.AuthorizerInfoResult.authorization_info.authorizer_access_token)) { //账号没有此权限 throw new WeixinOpenException("此公众号没有高级权限", componentBag); } authorizerBag.AuthorizerInfoExpireTime = DateTime.Now.AddSeconds(authorizerBag.AuthorizerInfoResult.authorization_info.expires_in); } } return(authorizerBag.AuthorizerInfoResult); }
public override Task <GetInfoResponse> GetInfo(GetInfoRequest request, ServerCallContext context) { var resp = new GetInfoResponse(); var data = ComponentApi.GetAuthorizerInfo(_componentAccessToken, _componentAppId, request.AppId); if (data.ErrCode == 0) { _redis.StringSet(CacheKey.UserRefreshTokenPrefix + data.AuthorizationInfo.AuthorizerAppId, data.AuthorizationInfo.AuthorizerRefreshToken); if (data.AuthorizerInfo.MiniProgramInfo != null) { _redis.StringSet(CacheKey.UserIsWxAppPrefix + data.AuthorizationInfo.AuthorizerAppId, 1); resp.Type = "WxApp"; } else { _redis.KeyDelete(CacheKey.UserIsWxAppPrefix + data.AuthorizationInfo.AuthorizerAppId); resp.Type = "WxWeb"; } resp.HeadImg = data.AuthorizerInfo.HeadImg; resp.NickName = data.AuthorizerInfo.NickName; resp.PrincipalName = data.AuthorizerInfo.PrincipalName; resp.UserName = data.AuthorizerInfo.UserName; resp.Alias = data.AuthorizerInfo.Alias; resp.AppId = data.AuthorizationInfo.AuthorizerAppId; resp.QrcodeUrl = data.AuthorizerInfo.QrcodeUrl; resp.ServiceTypeInfo = data.AuthorizerInfo.ServiceTypeInfo.Id; resp.VerifyTypeInfo = data.AuthorizerInfo.VerifyTypeInfo.Id; foreach (var item in data.AuthorizationInfo.FuncInfos) { resp.Permissions.Add(item.Category.Id); } } else { resp.Error = new Error { ErrMsg = data.ErrMsg, ErrCode = data.ErrCode }; } return(Task.FromResult(resp)); }
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 IActionResult Installed(string auth_code, int expires_in) { LogService.GetInstance().AddLog("Home:Installed", null, "Auth succeed", "", "Info"); var queryAuth = Senparc.Weixin.Open.ComponentAPIs.ComponentApi.QueryAuth(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, auth_code); string authorizerAppid = queryAuth.authorization_info.authorizer_appid; var authorizer = db.AppAuths.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid); if (authorizer == null || authorizer.Code != auth_code) { if (authorizer == null) { authorizer = new AppAuthInfo(); authorizer.AppId = _wxConfig.AppId; authorizer.AuthorizerAppId = queryAuth.authorization_info.authorizer_appid; authorizer.Authorized = true; authorizer.CreateOn = DateTime.Now; var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(ComponentKeys.GetInstance().AccessData.AccessCode, _wxConfig.AppId, queryAuth.authorization_info.authorizer_appid); var authorizerInfo = authorizerInfoResult.authorizer_info; var authorizerInfoEntity = db.AuthorizerInfos.FirstOrDefault(c => c.UserName == authorizerInfo.user_name); if (authorizerInfoEntity == null) { 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 }; } authorizer.Authorizer = authorizerInfoEntity; //TODO: 这里应该存储以下信息,并自动刷新 //todo: queryAuth.authorization_info.authorizer_access_token //TODO: queryAuth.authorization_info.authorizer_refresh_token AuthorizerToken token = db.AuthorizerTokens.FirstOrDefault(c => c.AuthorizerAppId == authorizerAppid); if (token == null) { token = new AuthorizerToken(); db.AuthorizerTokens.Add(token); } token.RefreshOn = DateTime.Now; token.AuthorizerAccessToken = queryAuth.authorization_info.authorizer_access_token; token.AuthorizerRefreshToken = queryAuth.authorization_info.authorizer_refresh_token; token.ExpiredIn = queryAuth.authorization_info.expires_in; db.SaveChanges(); //todo: 网站加入性能监控的组件,方便了解网站的运行状态 db.AppAuths.Add(authorizer); } //need update authorizer.Code = auth_code; authorizer.ExpiredTime = DateTime.Now.AddSeconds(queryAuth.authorization_info.expires_in); authorizer.LastUpdateOn = DateTime.Now; db.SaveChanges(); } HomeInstalledViewModels vm = new HomeInstalledViewModels(); vm.AuthorizerAppId = authorizerAppid; vm.AuthUrl = string.Format(_wxConfig.UserAuthEntryPointUriFmt, authorizerAppid); return(View(vm)); }
/// <summary> /// 授权页回调 /// </summary> /// <param name="id"></param> /// <returns></returns> public ActionResult OpenOAuthCallback(string id) { var reurl = "http://openapp.vzan.com/test/index"; var appid = "wx9a6ab00a752e10e8"; string auth_code = Request["auth_code"]; int areacode = int.Parse(Request["AreaCode"]?.ToString()); int expires_in = Convert.ToInt32(Request["expires_in"]); var currentmodel = opencomponentconfigBLL.SingleModel.getCurrentModel(); string token = currentmodel.component_access_token; //使用授权码获取小程序授权信息 var queryAuthResult = ComponentApi.QueryAuth(token, appid, auth_code); try { var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(token, appid, queryAuthResult.authorization_info.authorizer_appid); StringBuilder str = new StringBuilder(); foreach (FuncscopeCategoryItem item in queryAuthResult.authorization_info.func_info) { str.Append(item.funcscope_category.id.ToString() + ","); } string func_info = str.ToString(); if (func_info.Length > 0) { func_info = func_info.Substring(0, func_info.Length - 1); } #region 公众号详细信息 OpenAuthorizerConfig openconfig = OpenAuthorizerConfigBLL.SingleModel.GetModel("user_name='" + authorizerInfoResult.authorizer_info.user_name + "'"); if (openconfig == null) { openconfig = new OpenAuthorizerConfig(); } openconfig.alias = authorizerInfoResult.authorizer_info.alias; openconfig.appid = queryAuthResult.authorization_info.authorizer_appid; openconfig.func_info = func_info; openconfig.head_img = authorizerInfoResult.authorizer_info.head_img; openconfig.nick_name = authorizerInfoResult.authorizer_info.nick_name; openconfig.qrcode_url = authorizerInfoResult.authorizer_info.qrcode_url; openconfig.service_type_info = (int)authorizerInfoResult.authorizer_info.service_type_info.id; openconfig.user_name = authorizerInfoResult.authorizer_info.user_name; openconfig.verify_type_info = (int)authorizerInfoResult.authorizer_info.verify_type_info.id; openconfig.state = 1; //openconfig.minisnsid = areacode; if (openconfig.id > 0) { OpenAuthorizerConfigBLL.SingleModel.Update(openconfig); } else { OpenAuthorizerConfigBLL.SingleModel.Add(openconfig); } OpenAuthorizerInfo info = OpenAuthorizerInfoBLL.SingleModel.GetModel(string.Format("user_name='{0}'", authorizerInfoResult.authorizer_info.user_name)); if (info == null) { info = new OpenAuthorizerInfo(); } info.addtime = DateTime.Now; info.authorizer_access_token = queryAuthResult.authorization_info.authorizer_access_token; info.authorizer_appid = authorizerInfoResult.authorization_info.authorizer_appid; info.authorizer_refresh_token = queryAuthResult.authorization_info.authorizer_refresh_token; info.refreshtime = DateTime.Now; info.status = 1; //info.minisnsid = areacode; info.user_name = authorizerInfoResult.authorizer_info.user_name; if (info.id > 0) { OpenAuthorizerInfoBLL.SingleModel.Update(info); } else { OpenAuthorizerInfoBLL.SingleModel.Add(info); } #endregion return(Redirect(reurl)); } catch (ErrorJsonResultException ex) { log4net.LogHelper.WriteError(this.GetType(), ex); return(Content(ex.Message)); } }
public ActionResult OAuthCallback(string auth_code, int expires_in, int shopId) { logger.LogInformation($"================================调试开始===================================="); try { #region 查询授权信息 var componentAppId = wechatOpenOptions.AppId; var authorizationCode = auth_code; var accessToken = ZRui.Web.BLL.AuthorizerHelper.GetComponentAccessToken(); var queryAuthResult = ComponentApi.QueryAuth(accessToken, componentAppId, authorizationCode); logger.LogInformation($"授权返回信息queryAuthResult:{queryAuthResult}"); var authorizerAppid = queryAuthResult.authorization_info.authorizer_appid; var authorizationInfo = queryAuthResult.authorization_info; #endregion WechatOpenAuthorizer authorizer = null; var authorizers = db.Query <WechatOpenAuthorizer>(). Where(p => p.AuthorizerAppId == authorizationInfo.authorizer_appid); if (authorizers.Count() > 0) { authorizer = authorizers.FirstOrDefault(p => !p.IsDel); if (authorizer != null) { return(Content("当前店铺绑定的小程序已经存在")); } else { authorizer = authorizers.OrderByDescending(p => p.Id).FirstOrDefault(); authorizer.IsDel = false; } } else { authorizer = new WechatOpenAuthorizer(); db.Add(authorizer); } authorizer.AddIp = GetIp(); authorizer.AddTime = DateTime.Now; authorizer.AddUser = GetUsername(); authorizer.AuthorizerAppId = queryAuthResult.authorization_info.authorizer_appid; authorizer.AuthorizerAccessToken = queryAuthResult.authorization_info.authorizer_access_token; authorizer.AuthorizerRefreshToken = queryAuthResult.authorization_info.authorizer_refresh_token; authorizer.ExpiresIn = queryAuthResult.authorization_info.expires_in; authorizer.ExpiresTime = DateTime.Now.AddSeconds(queryAuthResult.authorization_info.expires_in); GetAuthorizerInfoResult authorizerInfoResult = ComponentApi.GetAuthorizerInfo(accessToken, componentAppId, authorizerAppid, 0x2710); authorizer.AuthorizerNickname = authorizerInfoResult.authorizer_info.nick_name; //这里的Username是原始Id authorizer.AuthorizerUsername = authorizerInfoResult.authorizer_info.user_name; db.SaveChanges(); ShopWechatOpenAuthorizer shopAuth = null; var shopAuths = db.Query <ShopWechatOpenAuthorizer>() .Where(m => m.ShopId == shopId); if (shopAuths.Count() > 0) { shopAuth = shopAuths.FirstOrDefault(p => !p.IsDel); if (shopAuth == null) { shopAuth = shopAuths.OrderByDescending(p => p.Id).FirstOrDefault(); } shopAuth.IsDel = false; } else { shopAuth = new ShopWechatOpenAuthorizer() { ShopId = shopId, }; db.Add(shopAuth); } shopAuth.WechatOpenAuthorizerId = authorizer.Id; db.SaveChanges(); ///初始化 //复制一份授权信息到auth数据库 ZRui.Web.BLL.AuthorizerHelper.InsertOrUpdateAuthorizer(authorizer); //设置请求域以及添加跳转二维码 var initShop = CodeApiExt.QRCodeJumpAddPublish(shopId, authorizer.AuthorizerAccessToken, hostingEnvironment); //创建开放平台--为了获取授权信息时含有unionid AuthorizerHelper.CreateAndBindOpen(authorizer.AuthorizerAppId); ViewData["QueryAuthorizationInfo"] = queryAuthResult.authorization_info; ViewData["GetAuthorizerInfoResult"] = authorizerInfoResult.authorizer_info; return(View()); } catch (ErrorJsonResultException ex) { return(Content(ex.Message)); } }
public ActionResult Installed(string auth_code, int expires_in) { var cts = new ComponentTokenService(); var componentToken = cts.GetToken(); string componentAppId = ConfigurationManager.AppSettings["AppId"]; var queryAuth = Senparc.Weixin.Open.ComponentAPIs.ComponentApi.QueryAuth( componentToken.ComponentAccessToken, componentAppId, auth_code); string authorizerAppid = queryAuth.authorization_info.authorizer_appid; var authorizerInfoResult = ComponentApi.GetAuthorizerInfo(componentToken.ComponentAccessToken, componentAppId, queryAuth.authorization_info.authorizer_appid); var authorizerInfo = authorizerInfoResult.authorizer_info; var authorizerInfoEntity = db.MpInfos.FirstOrDefault(c => c.UserName == authorizerInfo.user_name); if (authorizerInfoEntity == null) { authorizerInfoEntity = new MpInfo() { 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 }; db.MpInfos.Add(authorizerInfoEntity); } MpToken token = db.MpTokens.FirstOrDefault(c => c.MpAppId == authorizerAppid); if (token == null) { token = new MpToken(); token.MpAppId = authorizerAppid; db.MpTokens.Add(token); } token.RefreshOn = DateTime.Now; token.MpAccessToken = queryAuth.authorization_info.authorizer_access_token; token.MpRefreshToken = queryAuth.authorization_info.authorizer_refresh_token; token.ExpiredIn = queryAuth.authorization_info.expires_in; token.BelongToMp = authorizerInfoEntity; db.SaveChanges(); //update preauthcode var updatedCode = ComponentApi.GetPreAuthCode(ConfigurationManager.AppSettings["AppId"], componentToken.ComponentAccessToken); componentToken.PreAuthCodeExpiresIn = updatedCode.expires_in; componentToken.PreAuthCode = updatedCode.pre_auth_code; componentToken.PreAuthCodeCreateOn = DateTime.Now; cts.SavePreAuthCode(componentToken); //HomeInstalledViewModel vm = new HomeInstalledViewModel(); //vm.AuthorizerAppId = authorizerAppid; //vm.AuthUrl = string.Format(ConfigurationManager.AppSettings["UserAuthEntryPointUriFmt"], authorizerAppid); string redirectUrl = string.Format(ConfigurationManager.AppSettings["InstallSuccessUrl"], authorizerAppid); return(Redirect(redirectUrl)); }