上一篇已讲解到新建用户分组,移动用户到分组的功能,这一章主要讲解修改分组名称和删除分组
开发者可以使用接口,对公众平台的分组进行查询、创建、修改、删除等操作,也可以使用接口在需要时移动用户到某个分组。
目录 |
创建分组
一个公众账号,最多支持创建100个分组。
接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"group":{"name":"test"}}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
name | 分组名字(30个字符以内) |
返回说明 正常时的返回JSON数据包示例:
{ "group": { "id": 107, "name": "test" } }
参数说明
参数 | 说明 |
---|---|
id | 分组id,由微信分配 |
name | 分组名字,UTF8编码 |
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
查询所有分组
接口调用请求说明
http请求方式: GET(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/get?access_token=ACCESS_TOKEN
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
返回说明 正常时的返回JSON数据包示例:
{ "groups": [ { "id": 0, "name": "未分组", "count": 72596 }, { "id": 1, "name": "黑名单", "count": 36 }, { "id": 2, "name": "星标组", "count": 8 }, { "id": 104, "name": "华东媒", "count": 4 }, { "id": 106, "name": "★不测试组★", "count": 1 } ] }
参数说明
参数 | 说明 |
---|---|
groups | 公众平台分组信息列表 |
id | 分组id,由微信分配 |
name | 分组名字,UTF8编码 |
count | 分组内用户数量 |
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
查询用户所在分组
通过用户的OpenID查询其所在的GroupID。 接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"openid":"od8XIjsmk6QdVTETa9jLtGWA6KBc"}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
openid | 用户的OpenID |
返回说明 正常时的返回JSON数据包示例:
{ "groupid": 102 }
参数说明
参数 | 说明 |
---|---|
groupid | 用户所属的groupid |
错误时的JSON数据包示例(该示例为OpenID无效错误):
{"errcode":40003,"errmsg":"invalid openid"}
修改分组名
接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/update?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"group":{"id":108,"name":"test2_modify2"}}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
id | 分组id,由微信分配 |
name | 分组名字(30个字符以内) |
返回说明 正常时的返回JSON数据包示例:
{"errcode": 0, "errmsg": "ok"}
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
移动用户分组
接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"openid":"oDF3iYx0ro3_7jD4HFRDfrjdCM58","to_groupid":108}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
openid | 用户唯一标识符 |
to_groupid | 分组id |
返回说明 正常时的返回JSON数据包示例:
{"errcode": 0, "errmsg": "ok"}
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
批量移动用户分组
接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"openid_list":["oDF3iYx0ro3_7jD4HFRDfrjdCM58","oDF3iY9FGSSRHom3B-0w5j4jlEyY"],"to_groupid":108}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
openid_list | 用户唯一标识符openid的列表(size不能超过50) |
to_groupid | 分组id |
返回说明 正常时的返回JSON数据包示例:
{"errcode": 0, "errmsg": "ok"}
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
删除分组
注意本接口是删除一个用户分组,删除分组后,所有该分组内的用户自动进入默认分组。 接口调用请求说明
http请求方式: POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=ACCESS_TOKEN POST数据格式:json POST数据例子:{"group":{"id":108}}
参数说明
参数 | 说明 |
---|---|
access_token | 调用接口凭证 |
group | 分组 |
id | 分组的id |
返回说明 正常时的返回JSON数据包示例:
{"errcode": 0, "errmsg": "ok"}
错误时的JSON数据包示例(该示例为AppID无效错误):
{"errcode":40013,"errmsg":"invalid appid"}
直接上代码,废话不多说,获取分组列表需要用到的实体类
/// <summary> /// 微信分组类 /// </summary> public class WxGroupsInfo { public string Group_ID { get; set; }//分组编号 public string Group_Name { get; set; }//分组名称 public string Group_Count { get; set; }//分组人数 }
前台代码:
<!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"> .inputstyle { height:35px; line-height:35px; text-indent:5px; width:350px;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;margin:15px auto 15px auto; } a:hover { cursor:pointer; } .g_title { width:100%; border-bottom:2px solid #ced9df;font-size:20px; font-weight:bold; text-align:left; text-indent:5px; height:40px; line-height:40px; } th { height:35px;background-image:url(‘images/th.gif‘); background-repeat:repeat-x; } tr { height:30px; } #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; } .inputstyle22 { 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; } </style> <script src="../js/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript">
//修改分组名称调用的函数 function EditRoster(PayNo,name) { //alert(PayNo+":"+name); var url = ‘****.aspx?id=‘ + PayNo+"&name="+name;//转向网页的地址; var name = ‘add‘; //网页名称,可为空; var iWidth = 600; //弹出窗口的宽度; var iHeight = 300; //弹出窗口的高度; //获得窗口的垂直位置 var iTop = (window.screen.availHeight - 30 - iHeight) / 2; //获得窗口的水平位置 var iLeft = (window.screen.availWidth - 10 - iWidth) / 2; window.open(url, name, ‘height=‘ + iHeight + ‘,innerHeight=‘ + iHeight + ‘,width=‘ + iWidth + ‘,innerWidth=‘ + iWidth + ‘,top=‘ + iTop + ‘,left=‘ + iLeft + ‘,status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no‘); } $(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> <div class="g_title">分组管理</div> <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="inputstyle22" 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> <table style="width:1124px; margin:10px auto 10px auto; border:1px solid #ecd9df;text-align:center;"> <asp:Repeater ID="RepeaterGroupList" runat="server" OnItemCommand="RepeaterGroupList_ItemCommand" OnItemDataBound="RepeaterGroupList_ItemDataBound"> <HeaderTemplate> <tr> <th>序号</th> <th>ID编号</th> <th>分组名称</th> <th>分组人数</th> <th>操作</th> </tr> </HeaderTemplate> <ItemTemplate> <tr style=‘background-color: <%#(Container.ItemIndex%2==0)?"#fff":"#ced9ff"%>‘> <td><asp:Label ID="lbXuHao" runat="server" Text=""></asp:Label></td> <td><%# Eval("Group_ID") %></td> <td><%# Eval("Group_Name") %></td> <td><%# Eval("Group_Count") %></td> <td> <a onclick="EditRoster(‘<%# Eval("Group_ID") %>‘,‘<%# Eval("Group_Name") %>‘);">修改分组名称</a> <asp:LinkButton ID="LinkBtnDeleteGroup" runat="server" CommandName="DeleteGroups" CommandArgument=‘<%# Eval("Group_ID") %>‘ >删除分组</asp:LinkButton> </td> </tr> </ItemTemplate> </asp:Repeater> </table> <a class="newGroups"><div style="background-image:url(‘images/buttonbg.png‘); width:111px; height:35px; line-height:35px; margin:10px auto 10px 28px; font-weight:bold;float:left; text-align:center;color:#fff;"> ┼ 新建分组</div></a> </form> </body> </html>
后台代码如下:
protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { BindGroupList(); this.DataBind(); } } 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(); List<WxGroupsInfo> wxgrouplist = new List<WxGroupsInfo>(); for (int i = 0; i < groupsnum; i++) { WxGroupsInfo wginfo = new WxGroupsInfo(); wginfo.Group_ID = jsonObj["groups"][i]["id"].ToString(); wginfo.Group_Name = jsonObj["groups"][i]["name"].ToString(); wginfo.Group_Count = jsonObj["groups"][i]["count"].ToString(); wxgrouplist.Add(wginfo); } this.RepeaterGroupList.DataSource = wxgrouplist; this.RepeaterGroupList.DataBind(); } /// <summary> /// 绑定事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void RepeaterGroupList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if(e.Item.ItemType==ListItemType.Item||e.Item.ItemType==ListItemType.AlternatingItem) { Label lbXuHao = e.Item.FindControl("lbXuHao") as Label; int num = 1; lbXuHao.Text = num.ToString(); for (int i = 0; i < this.RepeaterGroupList.Items.Count;i++ ) { num += 1; lbXuHao.Text = num.ToString(); } LinkButton LinkBtnDeleteGroup = e.Item.FindControl("LinkBtnDeleteGroup") as LinkButton; LinkBtnDeleteGroup.Attributes.Add("OnClick", "return confirm(‘您确定要删除该分组?删除后该分组内的人员即将恢复到默认分组!‘)"); } } /// <summary> /// 执行事件 /// </summary> /// <param name="source"></param> /// <param name="e"></param> protected void RepeaterGroupList_ItemCommand(object source, RepeaterCommandEventArgs e) { //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘删除接口已关闭!‘);location=‘WxGroupManageList.aspx‘;", true); if (e.CommandName == "DeleteGroups") { 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/delete?access_token=" + Access_tokento; //POST数据例子: POST数据例子:{"group":{"id":108}} string groupid = e.CommandArgument.ToString(); string postData = "{\"group\":{\"id\":\"" + groupid.ToString() + "\"}}"; res = wxs.GetPage(posturl, postData); ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘删除成功!由于缓存问题,您可能需要重新登录才能看到效果!‘);location=‘WxGroupManageList.aspx‘;", true); } } /// <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() + "\"}}"; res = wxs.GetPage(posturl, postData); ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘创建成功!如未显示,请退出重新登录即可!‘);location=‘WxGroupManageList.aspx‘;", true); }
修改分组名称的页面
前台代码:
<!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> <style type="text/css"> .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; } </style> </head> <body> <form id="form1" runat="server"> <table border="1" style=" width:500px; border-collapse:collapse; margin:20px auto 20px auto; line-height:40px;"> <tr> <td style="text-align:right;">分组编号:</td> <td> <asp:TextBox ID="txtGroupId" CssClass="inputstyle" Enabled="false" runat="server"></asp:TextBox></td> </tr> <tr> <td style="text-align:right;">分组名称:</td> <td> <asp:TextBox ID="txtGroupName" CssClass="inputstyle" runat="server"></asp:TextBox> </td> </tr> <tr> <td></td> <td> <asp:LinkButton ID="LinkBtnSet" runat="server" OnClick="LinkBtnSet_Click" ><div style="background-image:url(‘images/buttonbg.png‘); width:111px; height:35px; line-height:35px; float:left; font-weight:bold;text-align:center;color:#fff;"> 设 置</div></asp:LinkButton></td> </tr> </table> </form> </body> </html>
后台代码:
protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostBack) { if (Request.QueryString["id"] != null) { string group_id = Request.QueryString["id"].ToString(); string group_name = Request.QueryString["name"].ToString(); this.txtGroupId.Text = group_id.ToString(); this.txtGroupName.Text = group_name.ToString(); this.txtGroupName.Focus(); } } } /// <summary> /// 设置 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void LinkBtnSet_Click(object sender, EventArgs e) { if(String.IsNullOrWhiteSpace(this.txtGroupName.Text.ToString().Trim())) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘不能为空!‘);", true); this.txtGroupName.Focus(); return; } if (this.txtGroupName.Text.ToString().Trim().Length>30) { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘组名称应在30个字符之内!‘);", true); this.txtGroupName.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/update?access_token=" + Access_tokento; //POST数据例子:POST数据例子:{"group":{"id":108,"name":"test2_modify2"}} //string postData = "{\"group\":{\"name\":\"" + this.txtgroupsName.Value.ToString().Trim() + "\"}}"; string postData = "{\"group\":{\"id\":\"" + txtGroupId.Text.ToString() +"\",\"name\":\""+this.txtGroupName.Text.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(‘修改成功!如未正常显示,属缓存问题,请重新登录即可!‘);window.opener.location.reload();this.close();", true); } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(‘修改失败!‘);this.close();", true); } }
WeiXinServer wxs = new WeiXinServer();公共方法用于获取通行证和加载流,如需要到上一篇查看