Home WeChat Applet WeChat Development .NET example tutorial for viewing follower interface on WeChat public account

.NET example tutorial for viewing follower interface on WeChat public account

Apr 26, 2017 am 10:19 AM

Entity class:

 public class userlist
  {
    public string total { get; set; }
    public string count { get; set; }
    public userlistopenid data { get; set; }
    public string next_openid { get; set; }
  }
Copy after login
 public class userlistopenid
  {
    public List<string> openid { get; set;
  }
Copy after login
 public class userdetail
  {
    public int subscribe { get; set; }
    public string openid { get; set; }
    public string nickname { get; set; }
    public int sex { get; set; }
    public string language { get; set; }
    public string city { get; set; }
    public string province { get; set; }
    public string country { get; set; }
    public string headimgurl { get; set; }
    public int subscribe_time { get; set; }
    public string unionid { get; set; }
    public string remark { get; set; }
    public int groupid { get; set; }
    public int[] tagid_list { get; set; }
  }
Copy after login

getUser.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="getUser.aspx.cs" Inherits="MyTest.WebUI.Manager.usermsg.getUser" %>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title></title>
  <!-- Bootstrap -->
  <link href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  <!--[if lt IE 9]>
   <script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
   <script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body>
  <form runat="server">

    <p class="container">
      <p class="row">
        <p class="col-md-6 col-md-push-2">
          <asp:Button class="btn btn-primary" ID="btnGet" runat="server" Text="获取所有用户openID" OnClick="btnGet_Click" />
        </p>
        <p class="col-md-6 col-md-pull-2">
          <asp:DropDownList CssClass="form-control" ID="ddlopenids" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlopenids_SelectedIndexChanged"></asp:DropDownList>
          <asp:Label ID="lblMSG" runat="server" Text=""></asp:Label>
          <asp:Image class="img-circle" ID="imgHead" runat="server" Width="180px" Height="180px" />
        </p>
      </p>
    </p>


    <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  </form>
</body>
</html>
Copy after login
 public partial class getUser : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    //获取用户列表
    protected void btnGet_Click(object sender, EventArgs e)
    {
      string next_opid = string.Empty;
      string url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+mainArg.get_Token()+"&next_openid=";
      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
      using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
      {
        StreamReader sr = new StreamReader(response.GetResponseStream());
        string result = sr.ReadToEnd();
        sr.Close();

        MyTest.Common.Entity.userlist userlist = MyTest.Common.Util.JsonEntityExchange<MyTest.Common.Entity.userlist>.Json2Entity(result);
        //Response.Write(userlist.count + "/"+userlist.data+"/"+userlist.next_openid+"/"+userlist.total);
        ddlopenids.DataSource = userlist.data.openid;
        ddlopenids.DataTextField = "";
        ddlopenids.DataValueField = "";
        ddlopenids.DataBind();
        ListItem item = new ListItem();
        item.Text = "--请选择用户的openID--";
        item.Value = "--0--";
        ddlopenids.Items.Insert(0, item);

      }
    }


    //获取用户基本信息(包括UnionID机制)
    protected void ddlopenids_SelectedIndexChanged(object sender, EventArgs e)
    {
      string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ mainArg.get_Token() + "&openid="+ddlopenids.SelectedItem.Text+"&lang=zh_CN ";
      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
      using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
      {
        StreamReader sr = new StreamReader(response.GetResponseStream());
        string result = sr.ReadToEnd();
        sr.Close();
        MyTest.Common.Entity.userdetail user= MyTest.Common.Util.JsonEntityExchange<MyTest.Common.Entity.userdetail>.Json2Entity(result);

        lblMSG.Text = user.subscribe + "/" + user.openid + "/" + user.nickname + "/";
        imgHead.ImageUrl = user.headimgurl;

      }
    }
  }
Copy after login

mainArg.cs Get accessToken help class:

 public class mainArg
  {
    //测试号
    public static string appid = "wx3eb5bf1290db2ca0";
    public static string secret = "e6013be0a7338c7d3e02877db116e231";

    public string jsapi_ticket;
    public string noncestr;
    public long timestamp;
    public string signature;

    private static string path = HttpContext.Current.Server.MapPath(@"~/TemplePath");
    private static string tokenPath = HttpContext.Current.Server.MapPath(@"~/TemplePath/token.txt");
    private static string ticketPath = HttpContext.Current.Server.MapPath(@"~/TemplePath/ticket.txt");

    public mainArg() {
      noncestr = getNonceStr();
      timestamp = getTime();
    }
    /// <summary>
    /// 获取access_token
    /// </summary>
    /// <returns></returns>
    public static string get_Token()
    {
      string token = null;
      //判断是否存在或过期
      if (File.Exists(tokenPath)) {
        FileStream fs = new FileStream(tokenPath, FileMode.Open);
        var serializer = new DataContractJsonSerializer(typeof(AccToken));
        AccToken readJSToken = (AccToken)serializer.ReadObject(fs);
        fs.Close();
        FileInfo fi = new FileInfo(tokenPath);
        if (CheckTimeOut(fi.LastWriteTime) < (readJSToken.expires_in-200)) {

          return token = readJSToken.access_token;
        }

      }

      string url = @"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";
      string urlarg = @"appid=" + appid + @"&secret=" + secret;
      //      HttpUtility.UrlEncode(appid,Encoding.GetEncoding("utf-8"));
      url += urlarg;
      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
      using (WebResponse response = req.GetResponse())
      {
        Stream s = response.GetResponseStream();
        StreamReader sr = new StreamReader(s);
        token = sr.ReadToEnd();

        if (!Directory.Exists(path))
        {
          Directory.CreateDirectory(path);
        }
        if (File.Exists(tokenPath))
        {
          File.Delete(tokenPath);
        }
        FileStream fs = File.Create(tokenPath);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write(token);
        sw.Flush();
        sw.Close();
        fs.Close();
        FileStream fs1 = new FileStream(tokenPath, FileMode.Open);
        var serializer = new DataContractJsonSerializer(typeof(AccToken));
        AccToken readJSToken = (AccToken)serializer.ReadObject(fs1);
        fs1.Close();
        token = readJSToken.access_token;
        return token;
      }

    }
    /// <summary>
    /// 获取ticket
    /// </summary>
    /// <returns></returns>
    public string getTicket() {
      string ticket = null;
      // 判断是否存在或过期
      if (File.Exists(ticketPath))
      {
        FileStream fs = new FileStream(ticketPath, FileMode.Open);
        var serializer = new DataContractJsonSerializer(typeof(JsTicket));
        JsTicket readJSTicket = (JsTicket)serializer.ReadObject(fs);
        fs.Close();
        FileInfo fi = new FileInfo(ticketPath);
        if (CheckTimeOut(fi.LastWriteTime) < (readJSTicket.expires_in - 200))
        {

          return ticket = readJSTicket.ticket;
        }

      }

      string url = @"https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&";
      string urlarg = @"access_token="+get_Token();
      //      HttpUtility.UrlEncode(appid,Encoding.GetEncoding("utf -8"));
      url += urlarg;
      HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
      using (WebResponse response = req.GetResponse())
      {
        Stream s = response.GetResponseStream();
        StreamReader sr = new StreamReader(s);
        ticket = sr.ReadToEnd();

        if (!Directory.Exists(path))
        {
          Directory.CreateDirectory(path);
        }
        if (File.Exists(ticketPath))
        {
          File.Delete(ticketPath);
        }
        FileStream fs = File.Create(ticketPath);
        StreamWriter sw = new StreamWriter(fs);
        sw.Write(ticket);
        sw.Flush();
        sw.Close();
        fs.Close();
        FileStream fs1 = new FileStream(ticketPath, FileMode.Open);
        var serializer = new DataContractJsonSerializer(typeof(JsTicket));
        JsTicket readJSTicket = (JsTicket)serializer.ReadObject(fs1);
        fs1.Close();
        ticket = readJSTicket.ticket;
        return ticket;
      }

    }
    //
    public static long getTime() {
      return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
    }
    public static string getTimeString(DateTime dt)
    {
      TimeSpan ts = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, 0);
      return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    //获取16位随机字符串
    public static string getNonceStr()
    {
      int length = 16;
      string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
      string str = "";
      Random rad = new Random();
      for (int i = 0; i < length; i++)
      {
        str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
      }
      return str;
    }


    //得到签名
    public string getSign() {

      jsapi_ticket = getTicket();
      string s1 = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url=http://winsee.imwork.net/Manager/Main/testjs.aspx", jsapi_ticket, noncestr, timestamp.ToString());     
      signature = GetSHA1(s1);
      return signature;
    }
    public static string GetSHA1(string strSource)
    {
      string strResult = string.Empty;


      System.Security.Cryptography.SHA1 sha = System.Security.Cryptography.SHA1.Create();
      byte[] bytResult = sha.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strSource));
      for (int i = 0; i < bytResult.Length; i++)
      {
        strResult = strResult + bytResult[i].ToString("x2");
      }
      return strResult;
    }
    //SHA1哈希加密算法 
    public static string GetSHA1_1(string str_sha1_in)
    {
      SHA1 sha1 = new SHA1CryptoServiceProvider();
      byte[] bytes_sha1_in = Encoding.Default.GetBytes(str_sha1_in);
      byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);
      string str_sha1_out = BitConverter.ToString(bytes_sha1_out);
      str_sha1_out = str_sha1_out.Replace("-", "").ToLower();
      return str_sha1_out;
    }

    // 判断是否超过7200s
    public static long CheckTimeOut(DateTime changeTime)
    {
      return Convert.ToInt64((DateTime.Now - changeTime).TotalSeconds);

    }



  }


 # region 创建Json序列化 及反序列化类目 
  //创建JSon类 保存文件 ticket.txt
  public class AccToken
  {

    public string access_token { get; set; }
    public long expires_in { get; set; }
  }

  //创建从微信返回结果的一个类 用于获取ticket 
  public class JsTicket
  {

    public long errcode { get; set; }
    public string errmsg { get; set; }
    public string ticket { get; set; }
    public long expires_in { get; set; }
  }
  #endregion
Copy after login

JSon serialization, deserialization


public class JsonEntityExchange<T> where T:new()
  {
    /// <summary>
    /// json转实体LIST
    /// </summary>
    /// <param name="JsonStr"></param>
    /// <returns></returns>
    public static List<T> Json2Entitys(string JsonStr)
    {
      JavaScriptSerializer Serializer = new JavaScriptSerializer();
      List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
      return objs;
    }
    /// <summary>
    /// json转实体
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T Json2Entity(string json)
    {
      T obj = Activator.CreateInstance<T>();
      using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
      {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        return (T)serializer.ReadObject(ms);
      }
    }
    /// <summary>
    /// 实体转json
    /// </summary>
    /// <param name="lists">实体list</param>
    /// <returns></returns>
    public static string Entity2Json(List<T> lists) {

      return new JavaScriptSerializer().Serialize(lists);
    }
  }
Copy after login

The result is as shown:

The above is the detailed content of .NET example tutorial for viewing follower interface on WeChat public account. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

Performance differences between Java framework and .NET framework Performance differences between Java framework and .NET framework Jun 03, 2024 am 09:19 AM

In terms of high-concurrency request processing, .NETASP.NETCoreWebAPI performs better than JavaSpringMVC. The reasons include: AOT early compilation, which reduces startup time; more refined memory management, where developers are responsible for allocating and releasing object memory.

C# .NET Interview Questions & Answers: Level Up Your Expertise C# .NET Interview Questions & Answers: Level Up Your Expertise Apr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C# .NET: Exploring Core Concepts and Programming Fundamentals C# .NET: Exploring Core Concepts and Programming Fundamentals Apr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

From Web to Desktop: The Versatility of C# .NET From Web to Desktop: The Versatility of C# .NET Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Advanced C# .NET Tutorial: Ace Your Next Senior Developer Interview Apr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles