欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net微信开发 如何获取AccessToken

程序员文章站 2023-11-25 08:55:34
本文实例为大家分享了获取accesstoken的方法,供大家参考,具体内容如下 accesstoken获取方法 public static access_tok...

本文实例为大家分享了获取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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。