最新赞助活动温馨提示:自愿赞助服务器费用,学生和没有工作的整站资源免费下载!
头像

用.net开发微信如何获取AccessToken介绍-微信开发

来源:http://erdangjiade.com/topic/139322.html 微信开发爱好者 2017-11-01 00:11浏览(39)

本文实例为大家分享了获取AccessToken的方法,供大家参考,具体内容如下

AccessToken获取方法

public static Access_token GetAccessToken()
{
  string formatString = String.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret);
 
  Access_token res = new Access_token();
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(formatString);
  request.Method = "GET";
  request.ContentType = "text/html;charset=UTF-8";
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  Stream myResponseStream = response.GetResponseStream();
  StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
  string retString = myStreamReader.ReadToEnd();
  myStreamReader.Close();
  myResponseStream.Close();
  if (retString.IndexOf("7200") > 0)
  {
    Access_token token = new Access_token();
    token = JsonHelper.ParseFromJson<Access_token>(retString);
    res.access_token = token.access_token;
    res.expires_in = token.expires_in;
  }
  return res;
}

Access_token类结构

public class Access_token
{
  public Access_token()
  {
    // 
    //TODO:用于验证Access_token是否过期实体
    // 
  }
  string _access_token;
  string _expires_in;
 
  /// <summary> 
  /// 获取到的凭证  
  /// </summary> 
  public string access_token
  {
    get { return _access_token; }
    set { _access_token = value; }
  }
 
  /// <summary> 
  /// 凭证有效时间,单位:秒 
  /// </summary> 
  public string expires_in
  {
    get { return _expires_in; }
    set { _expires_in = value; }
  }
}

JsonHelper.ParseFromJson方法

/// <summary> 
/// 将JSON对象转换为Model
/// </summary> 
/// <typeparam name="T"></typeparam> 
/// <param name="szJson"></param> 
/// <returns></returns> 
public static T ParseFromJson<T>(string szJson)
{
  T obj = Activator.CreateInstance<T>();
  using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
  {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    return (T)serializer.ReadObject(ms);
  }
}

以上就是用.net开发微信如何获取AccessToken介绍的详细内容,更多请关注二当家的素材网其它相关文章!

标签: 微信
评论0
头像

友情提示:垃圾评论一律封号 加我微信:826096331拉你进VIP群学习群

1 2