公众号可通过本接口来获取帐号的关注者列表,关注者列表由一串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
}
然后再创建用户信息的基本类
////// 微信用户基本信息类 /// 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" %>
获取用户列表绑定用户信息的后台代码,已包括,修改备注名,将用户移动到分组,新建分组代码
分组统计,用于显示每个分组的已存在人数,无其他作用
上代码:
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;
}
///
/// 获取所有用户的openid列表
///
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 openidlist = new list();
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();
}
///
/// 绑定分组列表
///
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()));
}
}
///
/// 输入页码提交跳转
///
///
///
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();
}
///
/// 判断是否是数字
///
///
///
public static bool isnum(string text) //
{
for (int i = 0; i < text.length; i )
{
if (!char.isnumber(text, i))
{
return true; //输入的不是数字
}
}
return false; //否则是数字
}
///
/// 绑定用户基本信息事件
///
///
///
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();
}
}
}
}
///
/// 创建分组
///
///
///
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);
}
///
/// 全选、全不选
///
///
///
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;
}
}
///
/// 移动用户到分组
///
///
///
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();是单独创建的一个类,主要用来获取通行证和加载流的方法,代码如下:
////// 微信服务类 /// public class weixinserver { ////// 获取通行证 /// ///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();
}
}
}
///
/// 设置备注名
///
///
///
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微信开发教程汇总》,欢迎大家学习阅读。
以上就是已关注用户管理的全部核心代码,仅供参考,希望对大家的学习有所帮助。
快乐宝贝逗你玩