主頁(yè) > 知識(shí)庫(kù) > asp.net微信開(kāi)發(fā)(已關(guān)注用戶管理)

asp.net微信開(kāi)發(fā)(已關(guān)注用戶管理)

熱門標(biāo)簽:硅谷的囚徒呼叫中心 地方門戶網(wǎng)站 百度競(jìng)價(jià)排名 網(wǎng)站排名優(yōu)化 科大訊飛語(yǔ)音識(shí)別系統(tǒng) 集中運(yùn)營(yíng)管理辦法 服務(wù)器配置 阿里云

公眾號(hào)可通過(guò)本接口來(lái)獲取帳號(hào)的關(guān)注者列表,關(guān)注者列表由一串OpenID(加密后的微信號(hào),每個(gè)用戶對(duì)每個(gè)公眾號(hào)的OpenID是唯一的)組成。一次拉取調(diào)用最多拉取10000個(gè)關(guān)注者的OpenID,可以通過(guò)多次拉取的方式來(lái)滿足需求。

接口調(diào)用請(qǐng)求說(shuō)明

http請(qǐng)求方式: GET(請(qǐng)使用https協(xié)議)

返回說(shuō)明

正確時(shí)返回JSON數(shù)據(jù)包:

錯(cuò)誤時(shí)返回JSON數(shù)據(jù)包(示例為無(wú)效AppID錯(cuò)誤):

{"errcode":40013,"errmsg":"invalid appid"}
附:關(guān)注者數(shù)量超過(guò)10000時(shí)

當(dāng)公眾號(hào)關(guān)注者數(shù)量超過(guò)10000時(shí),可通過(guò)填寫next_openid的值,從而多次拉取列表的方式來(lái)滿足需求。

具體而言,就是在調(diào)用接口時(shí),將上一次調(diào)用得到的返回中的next_openid值,作為下一次調(diào)用中的next_openid值。

示例如下:

公眾賬號(hào)A擁有23000個(gè)關(guān)注的人,想通過(guò)拉取關(guān)注接口獲取所有關(guān)注的人,那么分別請(qǐng)求url如下:
https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN
返回結(jié)果:

{
 "total":23000,
 "count":10000,
 "data":{"
 openid":[
 "OPENID1",
 "OPENID2",
 ...,
 "OPENID10000"
 ]
 },
 "next_openid":"OPENID10000"
}

https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKENnext_openid=NEXT_OPENID1
返回結(jié)果:

{
 "total":23000,
 "count":10000,
 "data":{
 "openid":[
 "OPENID10001",
 "OPENID10002",
 ...,
 "OPENID20000"
 ]
 },
 "next_openid":"OPENID20000"
}

https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKENnext_openid=NEXT_OPENID2
返回結(jié)果(關(guān)注者列表已返回完時(shí),返回next_openid為空):

{
 "total":23000,
 "count":3000,
 "data":{"
 "openid":[
  "OPENID20001",
  "OPENID20002",
  ...,
  "OPENID23000"
 ]
 },
 "next_openid":"OPENID23000"
}

微信官方網(wǎng)站后臺(tái)的接口權(quán)限表里(以服務(wù)號(hào)為例)每天調(diào)用的獲取用戶列表能獲取500次,獲取用戶基本信息可以獲取500000次,所以說(shuō)接下來(lái),我在獲取用戶列表的時(shí)候,會(huì)用到緩存,別看500次不少了,
可是真正的用起來(lái)快得不得了,先上效果圖如下:

先來(lái)看看用戶列表,官網(wǎng)說(shuō)獲取用戶的列表返回的是一組組openID,針對(duì)這個(gè)特性,我是這么做的,
創(chuàng)建一個(gè)用于存儲(chǔ)openId的類

public class WxOpenIdInfo
 {
 public string WxopenId { get; set; }//用戶存放微信用戶的openId
 }

然后再創(chuàng)建用戶信息的基本類

 /// summary>
 /// 微信用戶基本信息類
 /// /summary>
 public class WxUserInfo
 {
 public int subscribe { get; set; }//關(guān)注狀態(tài)

 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; }//關(guān)注時(shí)間

 public string remark { get; set; }//備注

 public string groupid { get; set; }//分組ID

 }

 用戶列表前臺(tái)代碼

%@ 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">首頁(yè)/a>/li>
   li>微信管理/li>
   li>德橋員工服務(wù)中心--關(guān)注者列表管理/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>關(guān)閉/a>nbsp;nbsp;/div>
  div style="font-size:12px; height:40px; color:red; line-height:40px;">nbsp;nbsp;30字符以內(nèi)/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;">nbsp;確定創(chuàng)建/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;">已關(guān)注人數(shù)/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;">全選nbsp;/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;">nbsp;+nbsp;新建分組/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;">刷nbsp;nbsp;新/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;">nbsp;查詢/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>關(guān)注時(shí)間/th>
   th>所屬分組/th>
   th>操作/th>
  /tr>
  /HeaderTemplate>
  ItemTemplate>
   tr style="width:100%; line-height:50px;">
    td style="width:30px;">nbsp;nbsp;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;">nbsp;修改備注名稱/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>nbsp;
  asp:HyperLink ID="lnkLast" runat="server">span class="fenyebtn2">>>|/span>/asp:HyperLink>nbsp;
  asp:HyperLink ID="lnkNext" runat="server">span class="fenyebtn2">>/span>/asp:HyperLink>nbsp;
   asp:HyperLink ID="lnkTop" runat="server">span class="fenyebtn2">/span>/asp:HyperLink>nbsp;
  asp:HyperLink ID="lnkFist" runat="server">span class="fenyebtn">|/span>/asp:HyperLink>nbsp;
  span style="float:left;">當(dāng)前第/span>
  span style="float:left; color:red;">asp:Label ID="lbPageIndex" runat="server" Text="">/asp:Label>/span>
  span style="float:left;margin-left:5px;">頁(yè)//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;">頁(yè)/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;">共搜索到nbsp;/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>

獲取用戶列表綁定用戶信息的后臺(tái)代碼,已包括,修改備注名,將用戶移動(dòng)到分組,新建分組代碼

分組統(tǒng)計(jì),用于顯示每個(gè)分組的已存在人數(shù),無(wú)其他作用

上代碼:

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

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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();

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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());


  ListWxOpenIdInfo> openidlist = new ListWxOpenIdInfo>();


  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;//每頁(yè)顯示為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;//當(dāng)前頁(yè)的索引就等于當(dāng)前頁(yè)碼-1;
  if (!pds.IsFirstPage)
  {
  //Request.CurrentExecutionFilePath 為當(dāng)前請(qǐng)求的虛擬路徑
  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 為當(dāng)前請(qǐng)求的虛擬路徑
  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);//跳轉(zhuǎn)至首頁(yè)
  this.lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(pds.PageCount);//跳轉(zhuǎn)至末頁(yè)

  this.RepeaterWxUserList.DataSource = pds;
  this.RepeaterWxUserList.DataBind();

  this.lbCountData.Text = openidlist.Count.ToString();
  this.lbPageIndex.Text = (pds.CurrentPageIndex + 1).ToString();
  this.lbPageSize.Text = "每頁(yè)" + 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();

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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();

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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("分組統(tǒng)計(jì)", "0"));//添加默認(rèn)第一個(gè)提示
  this.DDlAddgroups.Items.Insert(0, new ListItem("移動(dòng)用戶到分組", "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>
 /// 輸入頁(yè)碼提交跳轉(zhuǎn)
 /// /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('頁(yè)碼不能為空!')", true);
  this.txtPageIndex.Focus();
  return;
  }
  if (IsNum(this.txtPageIndex.Text.ToString().Trim()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('頁(yè)碼數(shù)只能輸入數(shù)字!')", 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('所輸頁(yè)數(shù)不能大于總頁(yè)數(shù)!')", true);
  this.txtPageIndex.Focus();
  this.txtPageIndex.Text = this.lbPageIndex.Text.ToString();
  return;
  }

  BindGetAllUserOpenIdList();
 }
 /// summary>
 /// 判斷是否是數(shù)字
 /// /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; //輸入的不是數(shù)字 
  }
  }
  return false; //否則是數(shù)字
 }
 /// 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();

  //根據(jù)OpenID獲取用戶基本信息。緩存處理
  WeiXinServer wxs = new WeiXinServer();

  ///從緩存讀取accesstoken
  string Access_token = Cache["Access_token"] as string;

  if (Access_token == null)
  {
   //如果為空,重新獲取
   Access_token = wxs.GetAccessToken();

   //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
   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();

  //獲取關(guān)注時(shí)間
  int totaltiem = int.Parse(jsonObj["subscribe_time"].ToString());
  //將整型格式時(shí)間轉(zhuǎn)換為時(shí)間格式
  DateTime t = new DateTime(1970, 1, 1).AddSeconds(totaltiem);
  //轉(zhuǎn)換后的時(shí)間會(huì)比原有時(shí)間小8個(gè)小時(shí),因此需要加上8個(gè)小時(shí)
  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();

   //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
   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>
 /// 創(chuàng)建分組
 /// /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();

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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('創(chuàng)建成功!如未顯示,請(qǐng)退出重新登錄即可!');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>
 /// 移動(dòng)用戶到分組
 /// /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();

   //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
   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數(shù)據(jù)例子:{"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);

   ///獲取返回結(jié)果的正確|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('移動(dòng)用戶成功!');location='WeiXinUserList.aspx';", true);
   }
   else
   {
   ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('移動(dòng)用戶失??!');", true);
   return;
   }
  }

  }
  if (!bools)
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('未選中項(xiàng)!');location='WeiXinUserList.aspx';", true);
  return;
  }
 }

 WeiXinServer wxs = new WeiXinServer();是單獨(dú)創(chuàng)建的一個(gè)類,主要用來(lái)獲取通行證和加載流的方法,代碼如下:

 /// summary>
 /// 微信服務(wù)類
 /// /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_credentialappid=此處應(yīng)該填寫公眾的appidsecret=此處應(yīng)該填寫公眾號(hào)的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);
  // 準(zhǔn)備請(qǐng)求...
  try
  {
  // 設(shè)置參數(shù)
  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();
  //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
  response = request.GetResponse() as HttpWebResponse;
  //直到request.GetResponse()程序才開(kāi)始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
  instream = response.GetResponseStream();
  sr = new StreamReader(instream, encoding);
  //返回結(jié)果網(wǎng)頁(yè)(html)代碼
  string content = sr.ReadToEnd();
  string err = string.Empty;
  return content;
  }
  catch (Exception ex)
  {
  string err = ex.Message;
  return string.Empty;
  }
 }
 }

修改備注頁(yè)面的代碼:

 protected void Page_Load(object sender, EventArgs e)
 {
  if(Request.QueryString["id"]!=null)
  {
  String openid = Request.QueryString["id"].ToString();
  this.txtOpenId.Value = openid.ToString();

  //根據(jù)OpenID獲取用戶基本信息。緩存處理
  WeiXinServer wxs = new WeiXinServer();

  ///從緩存讀取accesstoken
  string Access_token = Cache["Access_token"] as string;

  if (Access_token == null)
  {
   //如果為空,重新獲取
   Access_token = wxs.GetAccessToken();

   //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
   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>
 /// 設(shè)置備注名
 /// /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();

  //設(shè)置緩存的數(shù)據(jù)7000秒后過(guò)期
  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);

  ///獲取返回結(jié)果的正確|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微信開(kāi)發(fā)教程匯總》,歡迎大家學(xué)習(xí)閱讀。

以上就是已關(guān)注用戶管理的全部核心代碼,僅供參考,希望對(duì)大家的學(xué)習(xí)有所幫助。

您可能感興趣的文章:
  • .NET微信公眾號(hào) 用戶分組管理
  • asp.net微信開(kāi)發(fā)(用戶分組管理)
  • 微信開(kāi)發(fā)(一) asp.net接入
  • asp.net微信開(kāi)發(fā)(永久素材管理)
  • asp.net微信開(kāi)發(fā)(高級(jí)群發(fā)圖文)
  • asp.net微信開(kāi)發(fā)(高級(jí)群發(fā)文本)
  • asp.net微信開(kāi)發(fā)(消息應(yīng)答)
  • asp.net微信開(kāi)發(fā)(開(kāi)發(fā)者接入)
  • asp.net開(kāi)發(fā)微信公眾平臺(tái)之獲取用戶消息并處理
  • ASP.NET微信公眾號(hào)之用戶分組管理web頁(yè)面

標(biāo)簽:甘孜 西雙版納 開(kāi)封 烏蘭察布 威海 廣西 隨州 梧州

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《asp.net微信開(kāi)發(fā)(已關(guān)注用戶管理)》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266