Home  >  Article  >  WeChat Applet  >  Detailed explanation of following user management steps in asp.net WeChat development

Detailed explanation of following user management steps in asp.net WeChat development

高洛峰
高洛峰Original
2017-03-20 13:48:321895browse

This article mainly introduces the related content of the followed user management in asp.net WeChat development. Friends in need can refer to the

public account through this Interface to obtain the account's follower list. The follower list consists of a string of OpenIDs (encrypted WeChat IDs, each user's OpenID for each official account is unique). A single pull call can pull up to 10,000 OpenIDs of followers, and you can pull multiple times to meet your needs.

Interface call request description

http request method: GET (please use https protocol)

Detailed explanation of following user management steps in asp.net WeChat development

Return description

Return JSON data packet when correct:

Detailed explanation of following user management steps in asp.net WeChat development

Return JSON data packet when incorrect (example is invalid AppID error):

{" errcode":40013,"errmsg":"invalid appid"}
Attachment: When the number of followers exceeds 10,000

When the number of followers of the official account exceeds 10,000, you can fill in next## The value of #_openid can be used to pull the list multiple times to meet the needs.

Specifically, when calling the interface, the next_openid value returned from the previous call is used as the next_openid value in the next call.

The example is as follows:

Public account A has 23,000 following people. If you want to get all the following people through the pull attention interface, then the respective request URLs are as follows:

https:// api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN

Return result:

{
 "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


Return result:

##

{
 "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
Return results (the follower list has been returned , return next_openid is empty):



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


is called every day in the interface permission table of the WeChat official website background (taking service account as an example) to obtain users The list

can be obtained 500 times, and the user's basic information can be obtained 500,000 times. So next, when I obtain the user list, I will use

caching. Even though 500 times is a lot, But it is really fast to use. The rendering is as follows:

Let’s take a look at the user list first. The official website says that getting the user list returns: A group of openIDs. For this feature, I did this, Detailed explanation of following user management steps in asp.net WeChat developmentCreate a class for storing openId

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

And then create a basic class of user information

 /// 
 /// 微信用户基本信息类
 /// 
 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

 }

User list front-end code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WeiXinUserList.aspx.cs" Inherits="DQWebSite.Administrator.WeiXinUserList" %>






 
 
 

 
 

位置:

  • 首页
  • 微信管理
  • 德桥员工服务中心--关注者列表管理

新建分组关闭

30字符以内

确定创建

已关注人数

全选

+ 新建分组

分组管理

刷 新

<%--

查询

--%>

OpenID 头像 昵称(备注名) 关注时间 所属分组 操作
<%--OnCheckedChanged="CheckIn_CheckedChanged"--%> 分组名称 '>

修改备注名称

确定 >>| > < |<< 当前第 页/ 共搜索到 条记录.

Get the back-end code for binding user information to the user list, which is included. Modify the remark name, move the user to a group, and create a new group code

Group statistics, used to display the number of existing people in each group, no other functionDetailed explanation of following user management steps in asp.net WeChat development

Code:

 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(); is a separately created class, mainly used to obtain passes and load streams. The code is as follows:

 /// 
 /// 微信服务类
 /// 
 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;
  }
 }
 }
Modify the code of the remarks page:

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

 }


The above is the detailed content of Detailed explanation of following user management steps in asp.net WeChat development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn