コード例 #1
0
        public void ContainerTest()
        {
            MutipleCacheTestHelper.RunMutipleCache(() =>
            {
                //获取Token完整结果(包括当前过期秒数)
                DateTime dt1    = DateTime.Now;
                var tokenResult = AccessTokenContainer.GetAccessTokenResult(base._appId);
                DateTime dt2    = DateTime.Now;

                Assert.IsNotNull(tokenResult);
                Console.WriteLine(tokenResult.access_token);
                Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);

                if (base._useRedis)
                {
                    Thread.Sleep(2500);//等待缓存更新
                }

                //只获取Token字符串
                dt1       = DateTime.Now;
                var token = AccessTokenContainer.GetAccessToken(base._appId);
                dt2       = DateTime.Now;
                Assert.AreEqual(tokenResult.access_token, token);
                Console.WriteLine(tokenResult.access_token);
                Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);

                //getNewToken
                {
                    dt1   = DateTime.Now;
                    token = AccessTokenContainer.TryGetAccessToken(base._appId, base._appSecret, false);
                    dt2   = DateTime.Now;
                    Console.WriteLine(token);
                    Assert.AreEqual(tokenResult.access_token, token);

                    Console.WriteLine("强制重新获取AccessToken");
                    dt1   = DateTime.Now;
                    token = AccessTokenContainer.TryGetAccessToken(base._appId, base._appSecret, true);
                    dt2   = DateTime.Now;
                    Console.WriteLine(token);
                    Assert.AreNotEqual(tokenResult.access_token, token);//如果微信服务器缓存,此处会相同
                    Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
                }

                {
                    tokenResult = AccessTokenContainer.GetAccessTokenResult(base._appId);
                    if (base._useRedis)
                    {
                        Thread.Sleep(2500);//等待缓存更新
                    }
                    Console.WriteLine("HashCode:{0}", tokenResult.GetHashCode());
                    dt1          = DateTime.Now;
                    var allItems = AccessTokenContainer.GetAllItems();
                    dt2          = DateTime.Now;
                    Assert.IsTrue(allItems.Count > 0);

                    //序列化
                    var d1 = StackExchangeRedisExtensions.Serialize(tokenResult);
                    var d2 = StackExchangeRedisExtensions.Serialize(allItems[0].AccessTokenResult);

                    Assert.AreEqual(String.Concat(d1), String.Concat(d2));//证明缓存成功
                    Console.WriteLine("All Items:{0}", allItems.Count);
                    Console.WriteLine("HashCode:{0}", allItems[0].AccessTokenResult.GetHashCode());
                    Console.WriteLine("耗时:{0}毫秒", (dt2 - dt1).TotalMilliseconds);
                }
            }, CacheType.Local, CacheType.Redis);
        }
コード例 #2
0
        public ActionResult SubmitForm(WxMenu entity, string keyValue)
        {
            try
            {
                MenuManage         mMrg   = new MenuManage();
                WxBaseConfigEntity weixin = app.GetDefaultConfig();
                AccessTokenResult  token  = AccessTokenContainer.GetAccessTokenResult(weixin.AppId);
                if (token.errcode != Senparc.Weixin.ReturnCode.请求成功)
                {
                    return(Error(token.errmsg));
                }

                //重新整理按钮信息
                ButtonGroup          bg      = new ButtonGroup();
                IList <BaseButton>   topList = new List <BaseButton>();
                IList <SingleButton> subList = new List <SingleButton>();
                #region 菜单设置
                for (int i = 0; i < 3; i++)
                {
                    string txtName = (string)ForeachClass.GetValue <WxMenu>(entity, "Top" + (i + 1));
                    string txtKey  = (string)ForeachClass.GetValue <WxMenu>(entity, "Top" + (i + 1) + "Key");
                    string txtUrl  = (string)ForeachClass.GetValue <WxMenu>(entity, "Top" + (i + 1) + "Url");
                    if (string.IsNullOrEmpty(txtName))
                    {
                        // 如果名称为空,则忽略该菜单,以及下面的子菜单
                        continue;
                    }
                    subList = new List <SingleButton>();
                    string txtSubName;
                    string txtSubKey;
                    string txtSubUrl;
                    for (int j = 0; j < 5; j++)
                    {
                        #region 子菜单的设置
                        txtSubName = (string)ForeachClass.GetValue <WxMenu>(entity, "Menu" + (i + 1) + (j + 1));
                        txtSubKey  = (string)ForeachClass.GetValue <WxMenu>(entity, "Menu" + (i + 1) + (j + 1) + "Key");
                        txtSubUrl  = (string)ForeachClass.GetValue <WxMenu>(entity, "Menu" + (i + 1) + (j + 1) + "Url");
                        if (string.IsNullOrEmpty(txtSubName))
                        {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(txtSubUrl))
                        {
                            SingleViewButton sub = new SingleViewButton();
                            sub.name = txtSubName.Trim();
                            sub.url  = Utils.UrlDecode(txtSubUrl.Trim());
                            subList.Add(sub);
                        }
                        else if (!string.IsNullOrEmpty(txtSubKey))
                        {
                            SingleClickButton sub = new SingleClickButton();
                            sub.name = txtSubName.Trim();
                            sub.key  = txtSubKey.Trim();
                            subList.Add(sub);
                        }
                        else
                        {
                            //报错 :子菜单必须有key和name
                            return(Error("二级菜单的名称和key或者url必填!"));

                            ;
                        }
                        #endregion
                    } //子菜单循环结束


                    if (subList != null && subList.Count > 0)
                    {
                        //有子菜单, 该一级菜单是SubButton
                        if (subList.Count < 1)
                        {
                            return(Error("子菜单个数为2~5个!"));
                        }
                        SubButton topButton = new SubButton(Utils.CutString(txtName.Trim(), 16));
                        topButton.sub_button.AddRange(subList);
                        topList.Add(topButton);
                    }
                    else
                    {
                        // 无子菜单
                        if (string.IsNullOrEmpty(txtKey) && string.IsNullOrEmpty(txtUrl))
                        {
                            return(Error("若无子菜单,必须填写key或者url值!"));
                        }

                        if (!string.IsNullOrEmpty(txtUrl))
                        {  //view 页面跳转
                            SingleViewButton topSingleButton = new SingleViewButton();
                            topSingleButton.name = txtName.Trim();
                            topSingleButton.url  = Utils.UrlDecode(txtUrl.Trim());
                            topList.Add(topSingleButton);
                        }
                        else if (!string.IsNullOrEmpty(txtKey))
                        {
                            SingleClickButton topSingleButton = new SingleClickButton();
                            topSingleButton.name = txtName.Trim();
                            topSingleButton.key  = txtKey.Trim();
                            topList.Add(topSingleButton);
                        }
                    }
                }
                #endregion

                bg.button.AddRange(topList);

                var result = mMrg.CreateMenu(token.access_token, bg);
                return(Success("菜单提交成功!"));
            }
            catch (Exception ex)
            {
                return(Error("报错:" + ex.Message));
            }
        }
コード例 #3
0
        /// <summary>
        /// 使用AccessToken进行操作时,如果遇到AccessToken错误的情况,重新获取AccessToken一次,并重试。
        /// 使用此方法之前必须使用AccessTokenContainer.Register(_appId, _appSecret);或JsApiTicketContainer.Register(_appId, _appSecret);方法对账号信息进行过注册,否则会出错。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fun"></param>
        /// <param name="accessTokenOrAppId">AccessToken或AppId。如果为null,则自动取已经注册的第一个appId/appSecret来信息获取AccessToken。</param>
        /// <param name="retryIfFaild">请保留默认值true,不用输入。</param>
        /// <returns></returns>
        public static T TryCommonApi <T>(Func <string, T> fun, string accessTokenOrAppId = null, bool retryIfFaild = true) where T : WxJsonResult
        {
            string appId       = null;
            string accessToken = null;

            if (accessTokenOrAppId == null)
            {
                appId = AccessTokenContainer.GetFirstOrDefaultAppId();
                if (appId == null)
                {
                    throw new UnRegisterAppIdException(null,
                                                       "尚无已经注册的AppId,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!");
                }
            }
            else if (ApiUtility.IsAppId(accessTokenOrAppId))
            {
                if (!AccessTokenContainer.CheckRegistered(accessTokenOrAppId))
                {
                    throw new UnRegisterAppIdException(accessTokenOrAppId, string.Format("此appId({0})尚未注册,请先使用AccessTokenContainer.Register完成注册(全局执行一次即可)!", accessTokenOrAppId));
                }

                appId = accessTokenOrAppId;
            }
            else
            {
                accessToken = accessTokenOrAppId;//accessToken
            }

            T result = null;

            try
            {
                if (accessToken == null)
                {
                    var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(appId, false);
                    accessToken = accessTokenResult.access_token;
                }
                result = fun(accessToken);
            }
            catch (ErrorJsonResultException ex)
            {
                if (retryIfFaild &&
                    appId != null &&
                    ex.JsonResult.errcode == ReturnCode.获取access_token时AppSecret错误或者access_token无效)
                {
                    //尝试重新验证
                    var accessTokenResult = AccessTokenContainer.GetAccessTokenResult(appId, true);
                    //强制获取并刷新最新的AccessToken
                    accessToken = accessTokenResult.access_token;
                    result      = TryCommonApi(fun, appId, false);
                }
                else
                {
                    ex.AccessTokenOrAppId = accessTokenOrAppId;
                    throw;
                }
            }
            catch (WeixinException ex)
            {
                ex.AccessTokenOrAppId = accessTokenOrAppId;
                throw;
            }

            return(result);
        }
コード例 #4
0
        public ActionResult GetMenu()
        {
            try
            {
                MenuManage         mMrg   = new MenuManage();
                WxBaseConfigEntity weixin = app.GetDefaultConfig();
                AccessTokenResult  token  = AccessTokenContainer.GetAccessTokenResult(weixin.AppId);
                if (token.errcode != Senparc.Weixin.ReturnCode.请求成功)
                {
                    return(Error(token.errmsg));
                }
                GetMenuResult result = mMrg.GetMenu(token.access_token);
                if (result == null)
                {
                    return(Error("未获得到菜单,请参考【使用规则】,自行排查问题!"));
                }

                var topButtonList = result.menu.button;
                int topNum        = topButtonList.Count;
                //List<string> menu = new List<string>();
                Dictionary <string, string> menu = new Dictionary <string, string>();
                for (int i = 0; i < topNum; i++)
                {
                    var topButton = topButtonList[i];
                    if (topButton != null)
                    {
                        menu.Add("Top" + (i + 1), topButton.name);
                        if (topButton.GetType() != typeof(SubButton))
                        {     //下面无子菜单
                            if (topButton.GetType() == typeof(SingleViewButton))
                            { //view 页面跳转
                                menu.Add("Top" + (i + 1) + "Key", ((SingleViewButton)topButton).url);
                            }
                            else
                            {
                                menu.Add("Top" + (i + 1) + "Url", ((SingleClickButton)topButton).key);
                            }
                        }
                        else
                        {   //下面有子菜单
                            IList <SingleButton> subButtonList = ((SubButton)topButton).sub_button;
                            if (subButtonList != null && subButtonList.Count > 0)
                            {
                                for (int j = 0; j < subButtonList.Count; j++)
                                {
                                    if (subButtonList[j].GetType() == typeof(SingleViewButton))
                                    {
                                        SingleViewButton sub = (SingleViewButton)subButtonList[j];
                                        menu.Add("Menu" + (i + 1) + (j + 1), sub.name);
                                        menu.Add("Menu" + (i + 1) + (j + 1) + "Url", sub.url);
                                    }
                                    else
                                    {
                                        SingleClickButton sub = (SingleClickButton)subButtonList[j];
                                        menu.Add("Menu" + (i + 1) + (j + 1), sub.name);
                                        menu.Add("Menu" + (i + 1) + (j + 1) + "Key", sub.key);
                                    }
                                }
                            }
                        }
                    }
                }
                return(Success("菜单获取成功", menu));
            }
            catch (Exception ex)
            {
                return(Error(ex.Message));
            }
        }