C#微信公众平台开发之access_token的获取存储与更新

2019-12-30 11:48:55王振洲

2、辅助方法(Tools类):


namespace SWX.Utils
{
  /// <summary>
  /// 工具类
  /// </summary>
  public class Tools
  {
    #region 获取Json字符串某节点的值
    /// <summary>
    /// 获取Json字符串某节点的值
    /// </summary>
    public static string GetJsonValue(string jsonStr, string key)
    {
      string result = string.Empty;
      if (!string.IsNullOrEmpty(jsonStr))
      {
        key = """ + key.Trim('"') + """;
        int index = jsonStr.IndexOf(key) + key.Length + 1;
        if (index > key.Length + 1)
        {
          //先截逗号,若是最后一个,截“}”号,取最小值
          int end = jsonStr.IndexOf(',', index);
          if (end == -1)
          {
            end = jsonStr.IndexOf('}', index);
          }

          result = jsonStr.Substring(index, end - index);
          result = result.Trim(new char[] { '"', ' ', ''' }); //过滤引号或空格
        }
      }
      return result;
    }
    #endregion

  }
}

3、判断access_token是否过期(WXApi类):


#region 验证Token是否过期
/// <summary>
/// 验证Token是否过期
/// </summary>
public static bool TokenExpired(string access_token)
{
  string jsonStr = HttpRequestUtil.RequestUrl(string.Format("https://www.easck.com/cgi-bin/menu/get?access_token={0}", access_token));
  if (Tools.GetJsonValue(jsonStr, "errcode") == "42001")
  {
    return true;
  }
  return false;
}
#endregion

4、请求微信接口,获取access_token(WXApi类):


#region 获取Token
/// <summary>
/// 获取Token
/// </summary>
public static string GetToken(string appid, string secret)
{
  string strJson = HttpRequestUtil.RequestUrl(string.Format("https://www.easck.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret));
  return Tools.GetJsonValue(strJson, "access_token");
}
#endregion

5、全局存储与更新access_token(AdminUtil类):


#region 获取access_token
/// <summary>
/// 获取access_token
/// </summary>
public static string GetAccessToken(PageBase page)
{
  string access_token = string.Empty;

  UserInfo user = GetLoginUser(page);
  if (user != null)
  {
    if (string.IsNullOrWhiteSpace(user.access_token)) //尚未保存过access_token
    {
      access_token = WXApi.GetToken(user.AppID, user.AppSecret);
    }
    else
    {
      if (WXApi.TokenExpired(user.access_token)) //access_token过期
      {
        access_token = WXApi.GetToken(user.AppID, user.AppSecret);
      }
      else
      {
        return user.access_token;
      }
    }

    MSSQLHelper.ExecuteSql(string.Format("update SWX_Config set access_token='{0}' where UserName='{1}'", access_token, user.UserName));
  }

  return access_token;
}
#endregion