新建Asp.net MVC 4.0项目
WeChatSubscript是项目UI层
WeChatTools是封装操作访问公众号接口的一些方法类库
获取AccssToken
我们要的得到AccessToken,这是所有接口访问的基础,我们看看官方给出的接口调用文档
很简单明了,grant_type=client_credential,这是固定的不会变
appid与secret就是前面一章我叫大家记起来的那个认证口令数据。
下边我们来实现这个功能,新建WeCharbase.cs
public class WeCharbase
{
private static readonly string appId;
private static readonly string appSecret;
static WeCharbase()
{
appId = "**********";
appSecret = "832090bfddabbac19cc8da5053aea47b";
}
public static string AccessToken
{
get { return GetAccessToken(); }
}
/// 获取access_token
///
///
///
private static string GetAccessToken()
{
if (HttpContext.Current == null)
{
return GetToken();
}
var accessTokenCache = HttpContext.Current.Cache["access_token"];
if (accessTokenCache != null)
{
return accessTokenCache.ToString();
}
else
{
return GetToken();
}
}
/// 获取ccess_token
///
private static string GetToken()
{
try
{
var client = new WebClient();
client.Encoding = Encoding.UTF8;
var responseData = client.DownloadString(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appId, appSecret));
var javascriptSerializer = new JavascriptSerializer();
var accessDictionary = javascriptSerializer.Deserialize>(responseData);
var accessToken = accessDictionary["access_token"];
if (accessToken == null)
{
return string.Empty;
}
HttpContext.Current.Cache.Insert("access_token", accessToken, null, DateTime.Now.AddSeconds(7100), TimeSpan.Zero, CacheItemPriority.Normal, null);
HttpContext.Current.Cache.Remove("ticket");
GetTicket();
return accessToken.ToString();
}
catch (Exception ex)
{
return ex.Message;
}
}
}
细心的童鞋功能注意到这里用了HttpContext.Current.Cache,为什么呢?
因为access_token在官方服务器会缓存2个小时,请求一次,这个access_token在2个小时内都有效
所以请求一次得到access_token后,在以后的2个小时内都可以用这个access_token去访问其他接口
所以没有必要每次请求不同的接口都请求access_token一次
UI层实现
我们新建控制器SubscriptController.cs
新增2个Action,ViewAccessToken
///获取AccessToken ///public ActionResult ViewAccessToken() { return View(); } /// 获取AccessToken ///public ActionResult GetAccessToken() { return Content(WeCharbase.AccessToken); }
新增视图
| 获取access token |
运行项目,看看效果
成功了,是不是很简单呀
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



