asp.net微信开发(已关注用户管理)
公众号可通过本接口来获取帐号的关注者列表,关注者列表由一串openid(加密后的微信号,每个用户对每个公众号的openid是唯一的)组成。一次拉取调用最多拉取10000个关注者的openid,可以通过多次拉取的方式来满足需求。
接口调用请求说明
http请求方式: get(请使用https协议)
返回说明
正确时返回json数据包:
错误时返回json数据包(示例为无效appid错误):
{"errcode":40013,"errmsg":"invalid appid"}
附:关注者数量超过10000时
当公众号关注者数量超过10000时,可通过填写next_openid的值,从而多次拉取列表的方式来满足需求。
具体而言,就是在调用接口时,将上一次调用得到的返回中的next_openid值,作为下一次调用中的next_openid值。
示例如下:
公众账号a拥有23000个关注的人,想通过拉取关注接口获取所有关注的人,那么分别请求url如下:
https://api.weixin.qq.com/cgi-bin/user/get?access_token=access_token
返回结果:
{ "total":23000, "count":10000, "data":{" openid":[ "openid1", "openid2", ..., "openid10000" ] }, "next_openid":"openid10000" }
https://api.weixin.qq.com/cgi-bin/user/get?access_token=access_token&next_openid=next_openid1
返回结果:
{ "total":23000, "count":10000, "data":{ "openid":[ "openid10001", "openid10002", ..., "openid20000" ] }, "next_openid":"openid20000" }
https://api.weixin.qq.com/cgi-bin/user/get?access_token=access_token&next_openid=next_openid2
返回结果(关注者列表已返回完时,返回next_openid为空):
{ "total":23000, "count":3000, "data":{" "openid":[ "openid20001", "openid20002", ..., "openid23000" ] }, "next_openid":"openid23000" }
微信官方网站后台的接口权限表里(以服务号为例)每天调用的获取用户列表能获取500次,获取用户基本信息可以获取500000次,所以说接下来,我在获取用户列表的时候,会用到缓存,别看500次不少了,
可是真正的用起来快得不得了,先上效果图如下:
先来看看用户列表,官网说获取用户的列表返回的是一组组openid,针对这个特性,我是这么做的,
创建一个用于存储openid的类
public class wxopenidinfo { public string wxopenid { get; set; }//用户存放微信用户的openid }
然后再创建用户信息的基本类
/// <summary> /// 微信用户基本信息类 /// </summary> public class wxuserinfo { public int subscribe { get; set; }//关注状态 public string openid { get; set; }//openid public string nickname { get; set; }//昵称 public string sex { get; set; }//性别 public string city { get; set; }//城市 public string province { get; set; }//省份 public string headimgurl { get; set; }//头像图片地址 public string subscribe_time { get; set; }//关注时间 public string remark { get; set; }//备注 public string groupid { get; set; }//分组id }
用户列表前台代码
<%@ page language="c#" autoeventwireup="true" codebehind="weixinuserlist.aspx.cs" inherits="dqwebsite.administrator.weixinuserlist" %> <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title></title> <link href="css/style.css" rel="stylesheet" type="text/css" /> <style type="text/css"> #title {width:100%; height:40px;margin-top:10px; text-indent:5px; line-height:40px;} .checkstyle { float:left;} #ddladdgroups { text-align:center; width:161px; border:1px solid #d9d9d9; border-radius:5px; height:35px; line-height:35px; font-weight:bold; text-align:center; float:left; margin:auto 5px auto 5px;} .ddladdgroups{ text-align:center; width:161px; border:1px solid #d9d9d9; border-radius:5px; height:35px; line-height:35px; font-weight:bold; text-align:center; float:left; margin:auto 5px auto 5px;} #ddlgroups { text-align:center; width:111px; border:1px solid #d9d9d9; border-radius:5px; height:35px; line-height:35px; font-weight:bold; text-align:center; float:left; margin:auto 5px auto 5px;} .newgroups { margin:auto 5px auto 5px;} .inputstyle { height:35px; line-height:35px; text-indent:5px; width:280px;background-image:url('images/inputbg.gif'); background-repeat:repeat-x;border-top:solid 1px #a7b5bc; border-left:solid 1px #a7b5bc; border-right:solid 1px #ced9df; border-bottom:solid 1px #ced9df; float:left; margin:auto 5px auto 5px; } .wxusertab { border:1px solid #d9d9d9; width:100%; text-align:left; text-indent:5px; } th { height:35px;background-image:url('images/th.gif'); background-repeat:repeat-x; } td { border-bottom:1px solid #d9d9d9; } .trcolor { background-color:#ecd9df; } tr:hover { cursor:pointer; } #fenpage { width:1124px; height:25px; line-height:25px; text-align:center; margin:20px auto 20px auto; } .linka { color:#0094ff; cursor:pointer; } .fenyebtn {width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px; float:right; } .fenyebtn2 { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right; } .topageindex { width:60px;height:25px; background-image:url('images/inputbg.gif'); margin-left:10px; background-repeat:repeat-x;border-top:solid 1px #a7b5bc; border-left:solid 1px #a7b5bc; border-right:solid 1px #ced9df; border-bottom:solid 1px #ced9df; text-align:center; float:right; } .gotopagebtn { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right; background-color:#ced9df; } .deletebtn {float:left;width:100px; color:#000; height:25px; background-color:#ced9df; border:1px solid #ced9df; border-radius:5px; text-align:center; } a { color:#08a5e0; } .droplist { background-image:url('images/inputbg.gif'); background-repeat:repeat-x; width:120px; height:25px; border:1px solid #ced9df; } .checkstyle { float:left; } .imgheadstyle { width:50px; height:50px; margin-top:10px; } .lbsubscribecount { font-size:26px; } #shownewgroup { width:300px; height:200px; background-color:white;z-index:9999; border:2px solid #ddd; top:40%; left:40%; background-color:#fff; position:fixed;margin:-100px auto auto -100px; display:none; } #shownewgroupzhezhaoceng { height:200%; width:200%; left:0px; top:0px;position:fixed; z-index:9998; background:rgb(50,50,50);background:rgba(0,0,0,0.5); display:none; } .closelogin { height:30px; border-bottom:2px solid #31bb34; text-align:right; line-height:30px; font-size:14px; font-weight:bold; } a:hover { cursor:pointer; } #updateremark { width:300px; height:200px; background-color:white;z-index:9999; border:2px solid #ddd; top:40%; left:40%; background-color:#fff; position:fixed;margin:-100px auto auto -100px; display:none; } #updateremark_zhezhaoceng { height:100%; width:100%; left:0px; top:0px;position:fixed; z-index:9998; background:rgb(50,50,50);background:rgba(0,0,0,0.5); display:none; } </style> <script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(".newgroups").click(function () { $("#shownewgroupzhezhaoceng").show(); $("#shownewgroup").show(); }), $('.closeloginpage').click(function () { $("#shownewgroupzhezhaoceng").hide(); $("#shownewgroup").hide(); }) }) </script> </head> <body> <form id="form1" runat="server"> <div class="place"> <span>位置:</span> <ul class="placeul"> <li><a href="welcome.aspx" target="rightframe">首页</a></li> <li>微信管理</li> <li>德桥员工服务中心--关注者列表管理</li> </ul> </div> <asp:scriptmanager id="scriptmanager1" runat="server"></asp:scriptmanager> <asp:updatepanel id="updatepanel1" runat="server"> <contenttemplate> <div id="shownewgroup"> <div class="closelogin"><a class="closeloginpage"><span style="float:left; color:#08a5e0; font-size:18px; text-indent:5px;">新建分组</span>关闭</a> </div> <div style="font-size:12px; height:40px; color:red; line-height:40px;"> 30字符以内</div> <input type="text" id="txtgroupsname" name="txtgroupsname" class="inputstyle" maxlength="30" runat="server" value="分组名称" onfocus="if(value==defaultvalue){value='';this.style.color='#000'}" onblur="if(!value){value=defaultvalue;this.style.color='#999'}" style="color:#999"/> <asp:linkbutton id="linkbtncreategroup" runat="server" onclick="linkbtncreategroup_click"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold;float:left; margin-top:20px; margin-left:5px; text-align:center;color:#fff;"> 确定创建</div></asp:linkbutton> </div> <div id="shownewgroupzhezhaoceng"></div> <div style=" border-bottom:2px solid #31bb34; height:30px; margin-top:10px; text-indent:10px; font-size:22px; line-height:30px; width:100%;"><span style="float:left; font-size:16px;">已关注人数</span><span style="color:red;"><asp:label id="lbsubscribecount" cssclass="lbsubscribecount" runat="server" text="label"></asp:label> </span></div> <div id="title"> <asp:checkbox id="checkall" runat="server" cssclass="checkstyle" oncheckedchanged="checkall_checkedchanged" /><span style="float:left;">全选 </span> <asp:dropdownlist id="ddladdgroups" cssclass="ddladdgroups" runat="server" onselectedindexchanged="ddladdgroups_selectedindexchanged"> </asp:dropdownlist> <asp:dropdownlist id="ddlgroups" runat="server"> </asp:dropdownlist> <a class="newgroups"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; margin:auto 20px auto 10px; font-weight:bold;float:left; text-align:center;color:#fff;"> + 新建分组</div></a> <a href="wxgroupmanagelist.aspx"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; margin:auto 20px auto 10px; font-weight:bold;float:left; text-align:center;color:#fff;">分组管理</div></a> <a href="weixinuserlist.aspx"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; margin:auto 20px auto 10px; font-weight:bold;float:left; text-align:center;color:#fff;">刷 新</div></a> <%-- <input type="text" id="txtname" name="txtname" class="inputstyle" runat="server" value="用户昵称" onfocus="if(value==defaultvalue){value='';this.style.color='#000'}" onblur="if(!value){value=defaultvalue;this.style.color='#999'}" style="color:#999"/> <asp:linkbutton id="linkbutton1" runat="server"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold;float:left; text-align:center;color:#fff;"> 查询</div></asp:linkbutton>--%> </div> <table class="wxusertab"> <asp:repeater id="repeaterwxuserlist" runat="server" onitemdatabound="repeaterwxuserlist_itemdatabound"> <headertemplate> <tr> <th></th> <th>openid</th> <th>头像</th> <th>昵称(备注名)</th> <th>关注时间</th> <th>所属分组</th> <th>操作</th> </tr> </headertemplate> <itemtemplate> <tr style="width:100%; line-height:50px;"> <td style="width:30px;"> <asp:checkbox id="checkin" runat="server" cssclass="checkstyle" /> <%--oncheckedchanged="checkin_checkedchanged"--%></td> <td style="width:150px;"><asp:label id="lbwxopenid" runat="server" text=""></asp:label> </td> <td style="width:80px;"><asp:image id="imgheadurl" runat="server" cssclass="imgheadstyle" /> </td> <td style="width:150px;"><asp:label id="lbnickname" runat="server" cssclass="checkstyle" text=""></asp:label> <asp:label id="lbremark" runat="server" text=""></asp:label> </td> <td style="width:130px;"> <asp:label id="lbsubscrine_time" runat="server" text=""></asp:label> </td> <td style="width:100px;"> <asp:label id="lbgroupid" runat="server" cssclass="checkstyle" visible="false" text=""></asp:label> <asp:dropdownlist id="ddladdgroupss" enabled="false" cssclass="ddladdgroups" runat="server"> <asp:listitem value="0">分组名称</asp:listitem> </asp:dropdownlist> </td> <td style="width:110px;"> <a href='updateremarkname.aspx?id=<%# eval("wxopenid") %>'><div style=" border:1px solid #d9d9d9; border-radius:5px; width:111px; height:35px; line-height:35px; font-weight:bold;float:left; text-align:center;"> 修改备注名称</div></a> </td> </tr> </itemtemplate> </asp:repeater> </table> <div id="fenpage"> <asp:linkbutton id="linkbtntopage" cssclass="gotopagebtn" runat="server" onclick="linkbtntopage_click">确定</asp:linkbutton> <asp:textbox id="txtpageindex" cssclass="topageindex" runat="server"></asp:textbox> <asp:hyperlink id="lnklast" runat="server"><span class="fenyebtn2">>>|</span></asp:hyperlink> <asp:hyperlink id="lnknext" runat="server"><span class="fenyebtn2">></span></asp:hyperlink> <asp:hyperlink id="lnktop" runat="server"><span class="fenyebtn2"><</span></asp:hyperlink> <asp:hyperlink id="lnkfist" runat="server"><span class="fenyebtn">|<<</span></asp:hyperlink> <span style="float:left;">当前第</span> <span style="float:left; color:red;"><asp:label id="lbpageindex" runat="server" text=""></asp:label></span> <span style="float:left;margin-left:5px;">页/</span> <span style="float:left;margin-left:5px;">共</span> <span style="float:left;color:red;"><asp:label id="lbcountpage" runat="server" text=""></asp:label></span> <span style="float:left;margin-left:5px;">页</span> <span style="float:left;margin-left:10px;"><asp:label id="lbpagesize" runat="server" text=""></asp:label></span> <span style="float:left;margin-left:10px;">共搜索到 </span> <span style="float:left;margin-left:5px; color:red;"><asp:label id="lbcountdata" runat="server" text=""></asp:label></span> <span style="float:left;margin-left:5px;">条记录.</span> </div> </contenttemplate> </asp:updatepanel> </form> </body> </html>
获取用户列表绑定用户信息的后台代码,已包括,修改备注名,将用户移动到分组,新建分组代码
分组统计,用于显示每个分组的已存在人数,无其他作用
上代码:
pageddatasource pds = new pageddatasource(); protected void page_load(object sender, eventargs e) { if(!page.ispostback) { bindgrouplist(); bindgetalluseropenidlist(); this.databind(); this.checkall.autopostback = true; this.ddladdgroups.autopostback = true; } //this.ddladdgroups.enabled = false; } /// <summary> /// 获取所有用户的openid列表 /// </summary> private void bindgetalluseropenidlist() { weixinserver wxs = new weixinserver(); ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string jsonres = ""; string content = cache["alluseropenlist_content"] as string; if (content == null) { jsonres = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + access_tokento; httpwebrequest myrequest = (httpwebrequest)webrequest.create(jsonres); myrequest.method = "get"; httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); content = reader.readtoend(); reader.close(); //设置缓存的数据7000秒后过期 cache.insert("alluseropenlist_content", content, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(content); int totalnum = int.parse(jsonobj["count"].tostring()); list<wxopenidinfo> openidlist = new list<wxopenidinfo>(); for (int i = 0; i < totalnum;i++ ) { wxopenidinfo wxopeninfo = new wxopenidinfo(); wxopeninfo.wxopenid = jsonobj["data"]["openid"][i].tostring(); openidlist.add(wxopeninfo); } pds.datasource = openidlist; pds.allowpaging = true; pds.pagesize = 20;//每页显示为20条 int currentpage; if (!string.isnullorwhitespace(this.txtpageindex.text.tostring().trim())) { currentpage = convert.toint32(this.txtpageindex.text.tostring().trim()); } else if (request.querystring["page"] != null) { currentpage = convert.toint32(request.querystring["page"]); } else { currentpage = 1; } pds.currentpageindex = currentpage - 1;//当前页的索引就等于当前页码-1; if (!pds.isfirstpage) { //request.currentexecutionfilepath 为当前请求的虚拟路径 this.lnktop.navigateurl = request.currentexecutionfilepath + "?page=" + convert.tostring(currentpage - 1); this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.enabled = this.lnklast.enabled = true; } else { this.lnkfist.enabled = this.lnktop.enabled = false; this.lnknext.enabled = this.lnklast.enabled = true; this.lnkfist.attributes.add("style", "color:#ced9df;"); this.lnktop.attributes.add("style", "color:#ced9df;"); this.lnknext.attributes.remove("style"); this.lnklast.attributes.remove("style"); } if (!pds.islastpage) { //request.currentexecutionfilepath 为当前请求的虚拟路径 this.lnknext.navigateurl = request.currentexecutionfilepath + "?page=" + convert.tostring(currentpage + 1); this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.enabled = this.lnklast.enabled = true; } else { this.lnknext.enabled = this.lnklast.enabled = false; this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.attributes.add("style", "color:#ced9df;"); this.lnklast.attributes.add("style", "color:#ced9df;"); this.lnkfist.attributes.remove("style"); this.lnktop.attributes.remove("style"); } this.lnkfist.navigateurl = request.currentexecutionfilepath + "?page=" + convert.tostring(1);//跳转至首页 this.lnklast.navigateurl = request.currentexecutionfilepath + "?page=" + convert.tostring(pds.pagecount);//跳转至末页 this.repeaterwxuserlist.datasource = pds; this.repeaterwxuserlist.databind(); this.lbcountdata.text = openidlist.count.tostring(); this.lbpageindex.text = (pds.currentpageindex + 1).tostring(); this.lbpagesize.text = "每页" + pds.pagesize.tostring() + "条记录"; this.lbcountpage.text = pds.pagecount.tostring(); this.txtpageindex.text = (pds.currentpageindex + 1).tostring(); if (int.parse(openidlist.count.tostring()) <= int.parse(pds.pagesize.tostring())) { this.lnkfist.visible = this.lnktop.visible = this.lnknext.visible = this.lnklast.visible = this.txtpageindex.visible = this.linkbtntopage.visible = false; } else { this.lnkfist.visible = this.lnktop.visible = this.lnknext.visible = this.lnklast.visible = this.txtpageindex.visible = this.linkbtntopage.visible = true; } this.lbsubscribecount.text = openidlist.count.tostring(); } /// <summary> /// 绑定分组列表 /// </summary> private void bindgrouplist() { weixinserver wxs = new weixinserver(); ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string jsonres = ""; string content = cache["allgroups_content"] as string; if (content == null) { jsonres = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + access_tokento; httpwebrequest myrequest = (httpwebrequest)webrequest.create(jsonres); myrequest.method = "get"; httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); content = reader.readtoend(); reader.close(); //设置缓存的数据7000秒后过期 cache.insert("allgroups_content", content, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(content); int groupsnum = jsonobj["groups"].count(); this.ddlgroups.items.clear();//清除 this.ddladdgroups.items.clear(); this.ddlgroups.items.insert(0, new listitem("分组统计", "0"));//添加默认第一个提示 this.ddladdgroups.items.insert(0, new listitem("移动用户到分组", "0")); for (int i = 0; i < groupsnum; i++) { this.ddlgroups.items.add(new listitem(jsonobj["groups"][i]["name"].tostring() + "(" + jsonobj["groups"][i]["count"].tostring() + ")", jsonobj["groups"][i]["id"].tostring())); this.ddladdgroups.items.add(new listitem(jsonobj["groups"][i]["name"].tostring(), jsonobj["groups"][i]["id"].tostring())); } } /// <summary> /// 输入页码提交跳转 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtntopage_click(object sender, eventargs e) { if (string.isnullorwhitespace(this.txtpageindex.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('页码不能为空!')", true); this.txtpageindex.focus(); return; } if (isnum(this.txtpageindex.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('页码数只能输入数字!')", true); this.txtpageindex.focus(); this.txtpageindex.text = this.lbpageindex.text.tostring(); return; } if (int.parse(this.txtpageindex.text.tostring().trim()) > int.parse(this.lbcountpage.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('所输页数不能大于总页数!')", true); this.txtpageindex.focus(); this.txtpageindex.text = this.lbpageindex.text.tostring(); return; } bindgetalluseropenidlist(); } /// <summary> /// 判断是否是数字 /// </summary> /// <param name="text"></param> /// <returns></returns> public static bool isnum(string text) // { for (int i = 0; i < text.length; i++) { if (!char.isnumber(text, i)) { return true; //输入的不是数字 } } return false; //否则是数字 } /// <summary> /// 绑定用户基本信息事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void repeaterwxuserlist_itemdatabound(object sender, repeateritemeventargs e) { //checkbox checkin = e.item.findcontrol("checkin") as checkbox; //checkin.autopostback = true; if(e.item.itemtype==listitemtype.item||e.item.itemtype==listitemtype.alternatingitem) { wxopenidinfo wxopen = e.item.dataitem as wxopenidinfo; label lbwxopenid = e.item.findcontrol("lbwxopenid") as label; lbwxopenid.text = wxopen.wxopenid.tostring(); //根据openid获取用户基本信息。缓存处理 weixinserver wxs = new weixinserver(); ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string jsonres ="https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_tokento + "&openid=" + lbwxopenid.text.tostring(); httpwebrequest myrequest = (httpwebrequest)webrequest.create(jsonres); myrequest.method = "get"; httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); string content = reader.readtoend(); reader.close(); //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(content); image imgheadurl = e.item.findcontrol("imgheadurl") as image; label lbnickname = e.item.findcontrol("lbnickname") as label; label lbremark = e.item.findcontrol("lbremark") as label; label lbsubscrine_time = e.item.findcontrol("lbsubscrine_time") as label; label lbgroupid = e.item.findcontrol("lbgroupid") as label; dropdownlist ddladdgroupss = e.item.findcontrol("ddladdgroupss") as dropdownlist; lbnickname.text = jsonobj["nickname"].tostring(); if (!string.isnullorwhitespace(jsonobj["remark"].tostring())) { lbremark.text = "(" + jsonobj["remark"].tostring() + ")"; } imgheadurl.imageurl = jsonobj["headimgurl"].tostring(); lbgroupid.text = jsonobj["groupid"].tostring(); //获取关注时间 int totaltiem = int.parse(jsonobj["subscribe_time"].tostring()); //将整型格式时间转换为时间格式 datetime t = new datetime(1970, 1, 1).addseconds(totaltiem); //转换后的时间会比原有时间小8个小时,因此需要加上8个小时 lbsubscrine_time.text = t.addhours(8).tostring(); string jjjjjjjjjddd = cache["allgroups_content"] as string; if (jjjjjjjjjddd == null) { jsonres = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + access_tokento; httpwebrequest myrequestss = (httpwebrequest)webrequest.create(jsonres); myrequest.method = "get"; httpwebresponse myresponsess = (httpwebresponse)myrequest.getresponse(); streamreader readerss = new streamreader(myresponse.getresponsestream(), encoding.utf8); jjjjjjjjjddd = reader.readtoend(); reader.close(); //设置缓存的数据7000秒后过期 cache.insert("allgroups_content", jjjjjjjjjddd, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } //使用前需要引用newtonsoft.json.dll文件 jobject jsonobjss = jobject.parse(jjjjjjjjjddd); int groupsnumss = jsonobjss["groups"].count(); for (int i = 0; i < groupsnumss;i++ ) { if (jsonobjss["groups"][i]["id"].tostring().equals(lbgroupid.text.tostring())) { ddladdgroupss.selecteditem.text = jsonobjss["groups"][i]["name"].tostring(); } } } } /// <summary> /// 创建分组 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtncreategroup_click(object sender, eventargs e) { if (this.txtgroupsname.value.tostring().equals("分组名称")) { //// scriptmanager.registerclientscriptblock(this.page,this.gettype(),"","alert('不能为空!')",true); this.txtgroupsname.focus(); return; } weixinserver wxs = new weixinserver(); string res = ""; ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string posturl = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=" + access_tokento; //string postdata = "{\"group\":{\"name\":\""+this.txtgroupsname.value.tostring().trim()+"\"}}"; string postdata = "{\"group\":{\"name\":\""+this.txtgroupsname.value.tostring().trim()+"\"}}"; res = wxs.getpage(posturl, postdata); scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('创建成功!如未显示,请退出重新登录即可!');location='weixinuserlist.aspx';", true); } /// <summary> /// 全选、全不选 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void checkall_checkedchanged(object sender, eventargs e) { checkbox checkall = (checkbox)sender; foreach (repeateritem item in this.repeaterwxuserlist.items) { checkbox checkin = (checkbox)item.findcontrol("checkin"); checkin.checked = checkall.checked; } } /// <summary> /// 移动用户到分组 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void ddladdgroups_selectedindexchanged(object sender, eventargs e) { ///取得分组id string groupid = this.ddladdgroups.selectedvalue.tostring(); //this.label1.text = groupid.tostring(); boolean bools = false; foreach (repeateritem item in this.repeaterwxuserlist.items) { checkbox checkin = (checkbox)item.findcontrol("checkin"); if (checkin.checked) { bools = true; label lbwxopenid = item.findcontrol("lbwxopenid") as label; weixinserver wxs = new weixinserver(); string res = ""; ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string posturl = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + access_tokento; //post数据例子:{"openid":"odf3iyx0ro3_7jd4hfrdfrjdcm58","to_groupid":108} //string postdata = "{\"openid\":\"" + openid.tostring().trim() + "\",\"remark\":\"" + this.txtremarkname.value.tostring() + "\"}"; string postdata = "{\"openid\":\"" + lbwxopenid.text.tostring() + "\",\"to_groupid\":\"" + groupid.tostring() + "\"}"; res = wxs.getpage(posturl, postdata); //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(res); ///获取返回结果的正确|true|false, string isright = jsonobj["errcode"].tostring();//0 string istrueorfalse = jsonobj["errmsg"].tostring();//ok if (isright.equals("0") && istrueorfalse.equals("ok")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('移动用户成功!');location='weixinuserlist.aspx';", true); } else { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('移动用户失败!');", true); return; } } } if (!bools) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('未选中项!');location='weixinuserlist.aspx';", true); return; } }
weixinserver wxs = new weixinserver();是单独创建的一个类,主要用来获取通行证和加载流的方法,代码如下:
/// <summary> /// 微信服务类 /// </summary> public class weixinserver { /// <summary> /// 获取通行证 /// </summary> /// <returns></returns> public string getaccesstoken() { string url_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=此处应该填写公众的appid&secret=此处应该填写公众号的secret"; httpwebrequest myrequest = (httpwebrequest)webrequest.create(url_token); myrequest.method = "get"; httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); string content = reader.readtoend(); reader.close(); return content; } public string getpage(string p, string postdata) { stream outstream = null; stream instream = null; streamreader sr = null; httpwebresponse response = null; httpwebrequest request = null; encoding encoding = encoding.utf8; byte[] data = encoding.getbytes(postdata); // 准备请求... try { // 设置参数 request = webrequest.create(p) as httpwebrequest; cookiecontainer cookiecontainer = new cookiecontainer(); request.cookiecontainer = cookiecontainer; request.allowautoredirect = true; request.method = "post"; request.contenttype = "application/x-www-form-urlencoded"; request.contentlength = data.length; outstream = request.getrequeststream(); outstream.write(data, 0, data.length); outstream.close(); //发送请求并获取相应回应数据 response = request.getresponse() as httpwebresponse; //直到request.getresponse()程序才开始向目标网页发送post请求 instream = response.getresponsestream(); sr = new streamreader(instream, encoding); //返回结果网页(html)代码 string content = sr.readtoend(); string err = string.empty; return content; } catch (exception ex) { string err = ex.message; return string.empty; } } }
修改备注页面的代码:
protected void page_load(object sender, eventargs e) { if(request.querystring["id"]!=null) { string openid = request.querystring["id"].tostring(); this.txtopenid.value = openid.tostring(); //根据openid获取用户基本信息。缓存处理 weixinserver wxs = new weixinserver(); ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string jsonres = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_tokento + "&openid=" + openid; httpwebrequest myrequest = (httpwebrequest)webrequest.create(jsonres); myrequest.method = "get"; httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); string content = reader.readtoend(); reader.close(); //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(content); //假如备注名不为空,给备注名文本框赋值,显示原有的备注名 if (!string.isnullorwhitespace(jsonobj["remark"].tostring())) { this.txtremarkname.value = jsonobj["remark"].tostring(); } } } /// <summary> /// 设置备注名 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtnset_click(object sender, eventargs e) { string openid = request.querystring["id"].tostring(); weixinserver wxs = new weixinserver(); string res = ""; ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if (access_token == null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string posturl = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=" + access_tokento; string postdata = "{\"openid\":\"" + openid.tostring().trim() + "\",\"remark\":\"" + this.txtremarkname.value.tostring() + "\"}"; res = wxs.getpage(posturl, postdata); //使用前需药引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(res); ///获取返回结果的正确|true|false, string isright = jsonobj["errcode"].tostring();//0 string istrueorfalse = jsonobj["errmsg"].tostring();//ok if (isright.equals("0") && istrueorfalse.equals("ok")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('修改备注成功!');location='weixinuserlist.aspx';", true); } else { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('修改备注失败!');", true); } }
本文已被整理到了《asp.net微信开发教程汇总》,欢迎大家学习阅读。
以上就是已关注用户管理的全部核心代码,仅供参考,希望对大家的学习有所帮助。