. net wechat development how to obtain accesstoken

Time:2022-1-27

This example shares the method of obtaining accesstoken for your reference. The specific contents are as follows

Accesstoken obtaining method


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 class structure

public class Access_token
{
  public Access_token()
  {
    // 
    //Todo: used to verify access_ Whether the token is an expired entity
    // 
  }
  string _access_token;
  string _expires_in;

  /// <summary> 
  ///Obtained voucher  
  /// </summary> 
  public string access_token
  {
    get { return _access_token; }
    set { _access_token = value; }
  }

  /// <summary> 
  ///Effective time of voucher, unit: Second 
  /// </summary> 
  public string expires_in
  {
    get { return _expires_in; }
    set { _expires_in = value; }
  }
}

JsonHelper. Parsefromjason method

/// <summary> 
///Convert JSON object to 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);
  }
}

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.