search
HomeBackend DevelopmentC#.Net TutorialC# Development of WeChat Portal and Application (5) User Group Information Management

C# Development of WeChat Portal and Application (5) User Group Information Management

Jun 18, 2017 am 10:29 AM
.netGroupapplicationdevelopuserportal

This article mainly introduces the fifth article of C# development of WeChat portal and application in detail, user group information management, which has certain reference value. Interested friends can refer to it

In the past month, I have introduced the development of WeChat portals and applications in C#, and written several essays to share. Due to time constraints, I have not continued to write this series of blogs for a while. It is not that I have stopped researching this aspect. Instead, we will continue to explore this technology in depth and focus on the underlying technology development for better application. This article continues the introduction of the previous article, mainly introducing the development and application of group management. The content of this article and the previous article serve as a complete combination of user information and group information management.

1. User group management content

The introduction of user groups is mainly to facilitate the management of follower lists and the convenience of sending messages to different groups ## operation, a public account supports the creation of up to 500 groups.

User group management includes the following aspects:

1 Create a group

2 Query all groups
3 Query the group the user belongs to
4 Modify the group name
5 Mobile User Groups

WeChat’s definition of creating groups is as follows.

http request method: POST (please use https protocol)


https://api.weixin.qq.com/cgi-bin/groups/create?access_token=ACCESS_TOKENPOST data format: json
POST data example: {"group":{"name":"test"}}

The normally returned results are as follows.


{
  "group": {
    "id": 107, 
    "name": "test"
  }
}

Other interfaces use a similar method, by POSTing some parameters into the URL to obtain the returned Json data.

The entity class information of GroupJson defined in the previous essay is as follows.


  /// <summary>
  /// 分组信息
  /// </summary>
  public class GroupJson : BaseJsonResult
  {
    /// <summary>
    /// 分组id,由微信分配
    /// </summary>
    public int id { get; set; }

    /// <summary>
    /// 分组名字,UTF8编码
    /// </summary>
    public string name { get; set; }
  }

Based on the definitions of the above interfaces, I defined several interfaces and summarized them into the API interface of

User Management.


    /// <summary>
    /// 查询所有分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <returns></returns>
    List<GroupJson> GetGroupList(string accessToken);
            
    /// <summary>
    /// 创建分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="name">分组名称</param>
    /// <returns></returns>
    GroupJson CreateGroup(string accessToken, string name);
            
    /// <summary>
    /// 查询用户所在分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="openid">用户的OpenID</param>
    /// <returns></returns>
    int GetUserGroupId(string accessToken, string openid);
    
    /// <summary>
    /// 修改分组名
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="id">分组id,由微信分配</param>
    /// <param name="name">分组名字(30个字符以内)</param>
    /// <returns></returns>
    CommonResult UpdateGroupName(string accessToken, int id, string name);
            
    /// <summary>
    /// 移动用户分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="openid">用户的OpenID</param>
    /// <param name="to_groupid">分组id</param>
    /// <returns></returns>
    CommonResult MoveUserToGroup(string accessToken, string openid, int to_groupid);

2. Implementation of user group management interface

2.1 Create user group

In order to analyze how to implement To create a POST data operation for user grouping, let’s learn step by step the specific process of creating a user.

First you need to create a dynamically defined entity class information, which contains several attributes that need to be mentioned, as shown below.


string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/create?access_token={0}", accessToken);
var data = new
 {
  group = new
 {
  name = name
  }
 };
string postData = data.ToJson();

Among them, we convert the object into the appropriate Json data operation and put it in the extension method ToJson. This is mainly to facilitate the conversion of dynamically defined entity classes into Json content. The main thing is to call the serial number operation of Json.NET.


/// <summary>
/// 把对象为json字符串
/// </summary>
/// <param name="obj">待序列号对象</param>
/// <returns></returns>
public static string ToJson(this object obj)
 {
  return JsonConvert.SerializeObject(obj, Formatting.Indented);
 }

After preparing the Post data, we will further look at the operation code to obtain the data and convert it into a suitable format.


GroupJson group = null;

CreateGroupResult result = JsonHelper<CreateGroupResult>.ConvertJson(url, postData);
 if (result != null)
{
     group = result.group;
 }

The operation of POST data and converting it into a suitable format entity class is placed in the ConvertJson method. The definition of this method is as follows. The HttpHelper inside is my public The auxiliary class of the class library mainly calls the underlying httpWebRequest object method to submit data and obtain the return result.


/// <summary>
/// 转换Json字符串到具体的对象
/// </summary>
/// <param name="url">返回Json数据的链接地址</param>
/// <param name="postData">POST提交的数据</param>
/// <returns></returns>
    public static T ConvertJson(string url, string postData)
    {
      HttpHelper helper = new HttpHelper();
      string content = helper.GetHtml(url, postData, true);
      VerifyErrorCode(content);

      T result = JsonConvert.DeserializeObject<T>(content);
      return result;
    }

In this way, the complete operation function for creating user groups is as follows.


    /// <summary>
    /// 创建分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="name">分组名称</param>
    /// <returns></returns>
    public GroupJson CreateGroup(string accessToken, string name)
    {
      string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/create?access_token={0}", accessToken);
      var data = new
      {
        group = new
        {
          name = name
        }
      };
      string postData = data.ToJson();

      GroupJson group = null;
      CreateGroupResult result = JsonHelper<CreateGroupResult>.ConvertJson(url, postData);
      if (result != null)
      {
        group = result.group;
      }
      return group;
    }

2.2 Query all groups

Query all groups, you can get all the groups on the server, that is, the ID and name of each group.


    /// <summary>
    /// 查询所有分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <returns></returns>
    public List<GroupJson> GetGroupList(string accessToken)
    {
      string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/get?access_token={0}", accessToken);

      List<GroupJson> list = new List<GroupJson>();
      GroupListJsonResult result = JsonHelper<GroupListJsonResult>.ConvertJson(url);
      if (result != null && result.groups != null)
      {
        list.AddRange(result.groups);
      }

      return list;
    }

2.3 Query the group the user belongs to

Each user belongs to a group. By default, it is in the ungrouped group. We can obtain the user's information through the API Group information, that is, get the ID of the user group you are in.


    /// <summary>
    /// 查询用户所在分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="openid">用户的OpenID</param>
    /// <returns></returns>
    public int GetUserGroupId(string accessToken, string openid)
    {
      string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/getid?access_token={0}", accessToken);
      var data = new
      {
        openid = openid
      };
      string postData = data.ToJson();

      int groupId = -1;
      GroupIdJsonResult result = JsonHelper<GroupIdJsonResult>.ConvertJson(url, postData);
      if (result != null)
      {
        groupId = result.groupid;
      }
      return groupId;
    }

2.4 Modify the group name

You can also adjust the group the user is in in practice. The operation code is as follows.


    /// <summary>
    /// 修改分组名
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="id">分组id,由微信分配</param>
    /// <param name="name">分组名字(30个字符以内)</param>
    /// <returns></returns>
    public CommonResult UpdateGroupName(string accessToken, int id, string name)
    {
      string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/update?access_token={0}", accessToken);
      var data = new
      {
        group = new
        {
          id = id,
          name = name
        }
      };
      string postData = data.ToJson();

      return Helper.GetExecuteResult(url, postData);
    }

The return value CommonResult here is an entity class that contains a bool flag of success or failure, and an

error message of type String( if so).

For the GetExecuteResult function body, it mainly contains functions that submit data, then obtain the results, and process them based on the results.


    /// <summary>
    /// 通用的操作结果
    /// </summary>
    /// <param name="url">网页地址</param>
    /// <param name="postData">提交的数据内容</param>
    /// <returns></returns>
    public static CommonResult GetExecuteResult(string url, string postData = null)
    {
      CommonResult success = new CommonResult();
      try
      {
        ErrorJsonResult result;
        if (postData != null)
        {
          result = JsonHelper<ErrorJsonResult>.ConvertJson(url, postData);
        }
        else
        {
          result = JsonHelper<ErrorJsonResult>.ConvertJson(url);
        }

        if (result != null)
        {
          success.Success = (result.errcode == ReturnCode.请求成功);
          success.ErrorMessage = result.errmsg;
        }
      }
      catch (WeixinException ex)
      {
        success.ErrorMessage = ex.Message;
      }

      return success;
    } 
  }

The meaning of the red part above is that when converting to an entity class, if the error is defined in WeChat, then the error message will be recorded, and I will not handle other exceptions (also Just throw it out).

2.5 Move a user to a new group

The operation of moving a user to a new group is similar to the above section, please look at the code for details.


    /// <summary>
    /// 移动用户分组
    /// </summary>
    /// <param name="accessToken">调用接口凭证</param>
    /// <param name="openid">用户的OpenID</param>
    /// <param name="to_groupid">分组id</param>
    /// <returns></returns>
    public CommonResult MoveUserToGroup(string accessToken, string openid, int to_groupid)
    {
      string url = string.Format("https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token={0}", accessToken);
      var data = new
      {
        openid = openid,
        to_groupid = to_groupid
      };
      string postData = data.ToJson();

      return Helper.GetExecuteResult(url, postData);
    }

3. Calling the user grouping interface

The above section defines and implements various interfaces for user grouping. All The user-related code has been posted without reservation, and its calling operation is shown in the following code (test code).


    private void btnGetGroupList_Click(object sender, EventArgs e)
    {
      IUserApi userBLL = new UserApi();
      List<GroupJson> list = userBLL.GetGroupList(token);
      foreach (GroupJson info in list)
      {
        string tips = string.Format("{0}:{1}", info.name, info.id);
        Console.WriteLine(tips);
      }
    }

    private void btnFindUserGroup_Click(object sender, EventArgs e)
    {
      IUserApi userBLL = new UserApi();
      int groupId = userBLL.GetUserGroupId(token, openId);

      string tips = string.Format("GroupId:{0}", groupId);
      Console.WriteLine(tips);
    }

    private void btnCreateGroup_Click(object sender, EventArgs e)
    {
      IUserApi userBLL = new UserApi();
      GroupJson info = userBLL.CreateGroup(token, "创建测试分组");
      if (info != null)
      {
        string tips = string.Format("GroupId:{0} GroupName:{1}", info.id, info.name);
        Console.WriteLine(tips);

        string newName = "创建测试修改";
        CommonResult result = userBLL.UpdateGroupName(token, info.id, newName);
        Console.WriteLine("修改分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage));
      }
    }

    private void btnUpdateGroup_Click(object sender, EventArgs e)
    {
      int groupId = 111;
      string newName = "创建测试修改";

      IUserApi userBLL = new UserApi();
      CommonResult result = userBLL.UpdateGroupName(token, groupId, newName);
      Console.WriteLine("修改分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage));
    }

    private void btnMoveToGroup_Click(object sender, EventArgs e)
    {
      int togroup_id = 111;//输入分组ID

      if (togroup_id > 0)
      {
        IUserApi userBLL = new UserApi();
        CommonResult result = userBLL.MoveUserToGroup(token, openId, togroup_id);

        Console.WriteLine("移动用户分组名称:" + (result.Success ? "成功" : "失败:" + result.ErrorMessage));
      }
    }

了解了上面的代码和调用规则,我们就能通过API进行用户分组信息的管理了。通过在应用程序中集成相关的接口代码,我们就能够很好的控制我们的关注用户列表和用户分组信息。从而为我们下一步用户的信息推送打好基础。

The above is the detailed content of C# Development of WeChat Portal and Application (5) User Group Information Management. 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
C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft