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

.NET微信公众号查看关注者接口

程序员文章站 2022-10-15 09:28:14
本文实例为大家分享了java获取不同路径的方法,供大家参考,具体内容如下 实体类: public class userlist { publi...

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

实体类:

 public class userlist
  {
    public string total { get; set; }
    public string count { get; set; }
    public userlistopenid data { get; set; }
    public string next_openid { get; set; }
  }

 public class userlistopenid
  {
    public list<string> openid { get; set;
  }
 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; }
  }

getuser.aspx代码:

<%@ 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">

    <div class="container">
      <div class="row">
        <div class="col-md-6 col-md-push-2">
          <asp:button class="btn btn-primary" id="btnget" runat="server" text="获取所有用户openid" onclick="btnget_click" />
        </div>
        <div 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" />
        </div>
      </div>
    </div>


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

 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;

      }
    }
  }

mainarg.cs获取accesstoken帮助类:

 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 

json序列化,反序列化

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);
    }
  }

结果如图:

.NET微信公众号查看关注者接口

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