Ejemplo n.º 1
0
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            if (requestMessage.Content == "TESTCOMPONENT_MSG_TYPE_TEXT")
            {
                var responseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();
                responseMessage.Content = requestMessage.Content + "_callback";//固定为TESTCOMPONENT_MSG_TYPE_TEXT_callback
                return(responseMessage);
            }

            if (requestMessage.Content.StartsWith("QUERY_AUTH_CODE:"))
            {
                string openTicket      = OpenTicketHelper.GetOpenTicket(componentAppId);
                var    query_auth_code = requestMessage.Content.Replace("QUERY_AUTH_CODE:", "");
                try
                {
                    var component_access_token = ComponentApi.GetComponentAccessToken(componentAppId, componentSecret, openTicket).component_access_token;
                    var oauthResult            = ComponentApi.QueryAuth(component_access_token, componentAppId, query_auth_code);

                    //调用客服接口
                    var content    = query_auth_code + "_from_api";
                    var sendResult = CustomApi.SendText(oauthResult.authorization_info.authorizer_access_token,
                                                        requestMessage.FromUserName, content);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 获取QueryAuthResult(此方法每次都会发出请求,不缓存)
        /// </summary>
        /// <param name="componentAppId"></param>
        /// <param name="authorizationCode"></param>
        /// <param name="updateToAuthorizerContanier">是否将Authorization更新到AuthorizerContanier</param>
        /// <param name="getNewToken"></param>
        /// <returns></returns>
        /// <exception cref="WeixinOpenException"></exception>
        public static QueryAuthResult GetQueryAuthResult(string componentAppId, string authorizationCode, bool updateToAuthorizerContanier = true, bool getNewToken = false)
        {
            if (!CheckRegistered(componentAppId))
            {
                throw new WeixinOpenException(UN_REGISTER_ALERT);
            }

            var componentBag = TryGetItem(componentAppId);
            using (Cache.BeginCacheLock(LockResourceName + ".GetQueryAuthResult", componentAppId))//同步锁
            {
                var accessToken = TryGetComponentAccessToken(componentAppId, componentBag.ComponentAppSecret, null, getNewToken);
                var queryAuthResult = ComponentApi.QueryAuth(accessToken, componentAppId, authorizationCode);

                if (updateToAuthorizerContanier)
                {
                    //更新到AuthorizerContainer
                    AuthorizerContainer.TryUpdateAuthorizationInfo(componentAppId, queryAuthResult.authorization_info.authorizer_appid, queryAuthResult.authorization_info);
                }

                return queryAuthResult;
            }
        }
Ejemplo n.º 3
0
        /// <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));
            }
        }
Ejemplo n.º 4
0
        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));
            }
        }