当前位置: 移动技术网 > IT编程>开发语言>.net > .NET微信公众号开发之查询自定义菜单

.NET微信公众号开发之查询自定义菜单

2017年12月12日  | 移动技术网IT编程  | 我要评论

长江七号迅雷下载,行尸走肉第五季第四集,星座资源站

一.前言

   前面我们已经创建好了我们的自定义菜单。那么我们现在要如何查询我们自定义的菜单。

原理都是一样的,而且都是相当简单,只是接口地址文档换掉了。

二、开始编码

   同样我们首先创建好我的查询页面,在这里我们使用aspx页面 selectmenu.aspx

复制代码 代码如下:

        protected void page_load(object sender, eventargs e)
        {
            var str = getpage("");
            jobject jo = jobject.parse(str);
            access_token = jo["access_token"].tostring();
            getpage("=" + access_token + "");
            //getpage("");
        }

看代码是不是相当的简单。相信这对于聪明的你根本不是什么问题。同样删除我们的自定义菜单也很简单,只不过是接口地址换了而已,getpage方法的代码前面的文章已经有了,在这里就不重复的说明了。

三、令牌优化.

  前面我们已经知道了,怎么获取我们的access_token,我们知道它的有效时间是7200s,在这里难道我们每次请求都需要去重新获取一次,岂不是很麻烦,而且也不利于性能的优化,在这里我们对这个获取令牌的方法做一些优化,更有利于我们的代码.

在这里我们首先创建一个accesstoken类来存储我们的一些信息。代码如下

  /// <summary>
  /// 微信许可令牌
  /// </summary>
  public class accesstoken
  {
    /// <summary>
    /// 保存已获取到的许可令牌,键为公众号,值为公众号最后一次获取到的令牌
    /// </summary>
    private static concurrentdictionary<string, tuple<accesstoken, datetime>> accesstokens = new concurrentdictionary<string, tuple<accesstoken, datetime>>();

    /// <summary>
    /// 获取access token的地址
    /// </summary>
    private const string urlforgettingaccesstoken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
    /// <summary>
    /// 获取access token的http方法
    /// </summary>
    private const string httpmethodforgettingaccesstoken = webrequestmethods.http.get;
    /// <summary>
    /// 保存access token的最长时间(单位:秒),超过时间之后,需要重新获取
    /// </summary>
    private const int accesstokensavingseconds = 7000;

    /// <summary>
    /// access token
    /// </summary>
    public string access_token { get; set; }
    /// <summary>
    /// 有效时间,单位:秒
    /// </summary>
    public int expires_in { get; set; }

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="_access_token">access token</param>
    /// <param name="_expires_in">有效时间</param>
    internal accesstoken(string _access_token, int _expires_in)
    {
      access_token = _access_token;
      expires_in = _expires_in;
    }

    /// <summary>
    /// 返回accesstoken字符串
    /// </summary>
    /// <returns></returns>
    public override string tostring()
    {
      return string.format("accesstoken:{0}\r\n有效时间:{1}秒", access_token, expires_in);
    }

    /// <summary>
    /// 从json字符串解析accesstoken
    /// </summary>
    /// <param name="json">json字符串</param>
    /// <returns>返回accesstoken</returns>
    internal static accesstoken parsefromjson(string json)
    {
      var at = jsonconvert.deserializeanonymoustype(json, new { access_token = "", expires_in = 1 });
      return new accesstoken(at.access_token, at.expires_in);
    }

    /// <summary>
    /// 尝试从json字符串解析accesstoken
    /// </summary>
    /// <param name="json">json字符串</param>
    /// <param name="msg">如果解析成功,返回accesstoken;否则,返回null。</param>
    /// <returns>返回是否解析成功</returns>
    internal static bool tryparsefromjson(string json, out accesstoken token)
    {
      bool success = false;
      token = null;
      try
      {
        token = parsefromjson(json);
        success = true;
      }
      catch { }
      return success;
    }

    /// <summary>
    /// 得到access token
    /// </summary>
    /// <param name="username">公众号</param>
    /// <returns>返回access token</returns>
    public static accesstoken get(string username)
    {
      tuple<accesstoken, datetime> lasttoken = accesstokens.containskey(username) ? accesstokens[username] : null;
      accesstoken token = lasttoken == null ? null : lasttoken.item1;
      datetime refreshtime = lasttoken == null ? datetime.minvalue : lasttoken.item2;
      double ms = (datetime.now - refreshtime).totalseconds;
      if (ms > accesstokensavingseconds || token == null)
      {
        //尝试从微信服务器获取2次
        errormessage msg;
        accesstoken newtoken = getfromweixinserver(username, out msg);
        if (newtoken == null)
          newtoken = getfromweixinserver(username, out msg);
        if (newtoken != null)
        {
          lasttoken = new tuple<accesstoken, datetime>(newtoken, datetime.now);
          accesstokens[username] = lasttoken;
          token = newtoken;
        }
      }
      return token;
    }

    /// <summary>
    /// 从微信服务器获取access token
    /// </summary>
    /// <param name="username">公众号</param>
    /// <param name="msg">从服务器返回的错误信息。</param>
    /// <returns>返回许可令牌;如果获取失败,返回null。</returns>
    private static accesstoken getfromweixinserver(string username, out errormessage msg)
    {
      accesstoken token = null;
      msg = new errormessage(errormessage.exceptioncode, "");
      string url = string.format(urlforgettingaccesstoken, wxpayconfig.appid, wxpayconfig.appsecret);
      string result;
      if(!httphelper.request(url, out result, httpmethodforgettingaccesstoken, string.empty))
      {
        msg.errmsg = "从微信服务器获取响应失败。";
        return token;
      }
      if (errormessage.iserrormessage(result))
        msg = errormessage.parse(result);
      else
      {
        try
        {
          token = accesstoken.parsefromjson(result);
        }
        catch (exception e)
        {
          msg = new errormessage(e);
        }
      }
      return token;
    }
  }

 从这个类中的代码我们看到,每次获取access_token的时候都会判断一些时间是不是超过了7000,我们的token过期时间是7200s,这样就不需要每次请求的时候都是重新获取token。

这个时候我们的查询代码可以优化下.

复制代码 代码如下:

        protected void page_load(object sender, eventargs e)
        {
              string username = system.configuration.configurationmanager.appsettings["weixinid"].tostring();
              accesstoken token = accesstoken.get(username);

            getpage("=" + access_token + "");
            //getpage("");
        }

以上所述就是本文的全部内容了,希望大家能够喜欢。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网