好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

一、什么是access_token?

    access_token是公众号的全局唯一票据,公众号调用各接口时都需使用access_token。正常情况下access_token有效期为7200秒,重复获取将导致上次获取的access_token失效。由于获取access_token的api调用次数非常有限,建议开发者全局存储与更新access_token,频繁刷新access_token会导致api调用受限,影响自身业务。

二、要解决的问题

1、如何获取access_token。

2、由于access_token的有效期为7200秒,即2小时,并且重复获取将导致上次获取的access_token失效,获取access_token的api调用次数非常有限,所以要解决如何全局存储与更新access_token。

三、思路

1、将access_token存储在数据库中。

2、何时更新access_token呢?当access_token失效的时候更新,那么怎么判断access_token有没有失效呢?使用当前的access_token请求微信接口,获取自定义菜单,如果返回的errcode为42001,则说明access_token已经失效,这时再重新获取access_token。

数据库设计(表名swx_config):

四、代码:

1、http请求代码(httprequestutil类):

?

#region 请求url,不发送数据

/// <summary>

/// 请求url,不发送数据

/// </summary>

public static string requesturl( string url)

{

  return requesturl(url, "post" );

}

#endregion

 

#region 请求url,不发送数据

/// <summary>

/// 请求url,不发送数据

/// </summary>

public static string requesturl( string url, string method)

{

  // 设置参数

  httpwebrequest request = webrequest.create(url) as httpwebrequest;

  cookiecontainer cookiecontainer = new cookiecontainer();

  request.cookiecontainer = cookiecontainer;

  request.allowautoredirect = true ;

  request.method = method;

  request.contenttype = "text/html" ;

  request.headers.add( "charset" , "utf-8" );

 

  //发送请求并获取相应回应数据

  httpwebresponse response = request.getresponse() as httpwebresponse;

  //直到request.getresponse()程序才开始向目标网页发送post请求

  stream responsestream = response.getresponsestream();

  streamreader sr = new streamreader(responsestream, encoding.utf8);

  //返回结果网页(html)代码

  string content = sr.readtoend();

  return content;

}

#endregion

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://api.weixin.qq测试数据/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://api.weixin.qq测试数据/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

以上就是本文的全部内容,希望对大家进行微信公众平台开发有所帮助。

dy("nrwz");

查看更多关于C#微信公众平台开发之access_token的获取存储与更新的详细内容...

  阅读:61次