본 글에서는 asp.net WeChat 개발 시 사용자 관리 관련 내용을 주로 소개합니다. 도움이 필요한 친구는 이
인터페이스공개 계정을 참고할 수 있습니다. > 계정의 팔로어 목록을 가져옵니다. 팔로어 목록은 OpenID 문자열로 구성됩니다(암호화된 WeChat ID, 각 사용자의 OpenID는 각 공식 계정마다 고유함). 단일 풀 호출로 최대 10,000명의 팔로어 OpenID를 가져올 수 있으며, 필요에 따라 여러 번 가져올 수 있습니다. 인터페이스 호출 요청 설명http 요청 방법: GET(https 프로토콜을 사용하세요) 반환 설명 올바른 경우JSON 패킷 반환:
잘못된 경우 JSON 패킷 반환(예: 잘못된 AppID 오류): {" errcode" :40013,"errmsg":"invalid appid"}첨부: 팔로워 수가 10,000명을 초과하는 경우
작성하면 됩니다. _openid 값. 필요에 따라 목록을 여러 번 가져올 수 있습니다.
구체적으로 인터페이스 호출 시 이전 호출에서 반환된 next_openid 값이 다음 호출에서 next_openid 값으로 사용됩니다. 예는 다음과 같습니다. 공개 계정 A의 팔로어는 23,000명입니다. 풀 팔로우 인터페이스를 통해 모든 팔로어를 얻으려면 해당 요청 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" }
반환 결과:
{ "total":23000, "count":10000, "data":{ "openid":[ "OPENID10001", "OPENID10002", ..., "OPENID20000" ] }, "next_openid":"OPENID20000" }
결과 반환( 팔로어 목록이 반환됨) , return next_openid가 비어 있음):
{ "total":23000, "count":3000, "data":{" "openid":[ "OPENID20001", "OPENID20002", ..., "OPENID23000" ] }, "next_openid":"OPENID23000" }
목록 은 500번, 사용자의 기본 정보는 500,000번 얻을 수 있으므로 다음에는 사용자 목록을 얻을 때 <를 사용하겠습니다. 🎜>캐시 . 500번은 많지만 사용하기에는 정말 빠릅니다. 렌더링은 다음과 같습니다.
사용자 목록을 보세요. 공식 웹사이트에서는 사용자 목록을 가져오면 다음과 같은 결과가 나온다고 나와 있습니다. 이 기능을 위해 저는
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">
<p class="place">
<span>位置:</span>
<ul class="placeul">
<li><a href="WelCome.aspx" target="rightFrame">首页</a></li>
<li>微信管理</li>
<li>德桥员工服务中心--关注者列表管理</li>
</ul>
</p>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<p id="shownewgroup">
<p class="closeLogin"><a class="closeloginpage"><span style="float:left; color:#08a5e0; font-size:18px; text-indent:5px;">新建分组</span>关闭</a> </p>
<p style="font-size:12px; height:40px; color:red; line-height:40px;"> 30字符以内</p>
<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"><p 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;"> 确定创建</p></asp:LinkButton>
</p>
<p id="shownewgroupzhezhaoceng"></p>
<p 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></p>
<p 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"><p 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;"> + 新建分组</p></a>
<a href="WxGroupManageList.aspx"><p 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;">分组管理</p></a>
<a href="WeiXinUserList.aspx"><p 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;">刷 新</p></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"><p style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold;float:left; text-align:center;color:#fff;"> 查询</p></asp:LinkButton>--%>
</p>
<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") %>'><p style=" border:1px solid #d9d9d9; border-radius:5px; width:111px; height:35px; line-height:35px; font-weight:bold;float:left; text-align:center;"> 修改备注名称</p></a>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<p 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>
</p>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
그룹 통계는 각 그룹의 기존 인원 수를 표시하는 데 사용됩니다. function
코드: 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;
}
}
/// <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 WeChat 개발의 다음 사용자 관리 단계에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!