SoFunction
Updated on 2025-03-07

C# development WeChat portal and application (5) User group information management

Last month, I introduced the WeChat portal and application of C# development and wrote several essays to share. Due to time constraints, I have not continued to write this series of blogs for a while. I did not stop researching this aspect, but continued to explore the technologies in this aspect in depth. In order to better apply it, I will focus on the underlying technology development. 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 are 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 to facilitate the operation of sending messages to different groups. 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 user's group
4 Modify the group name
5 Mobile user grouping

WeChat’s definition of creating a group is as follows.

http request method: POST (please use https protocol)
/cgi-bin/groups/create?access_token=ACCESS_TOKEN
POST data format: json
POST data example: {"group":{"name":"test"}}

The normal return result is as follows.

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

Other interfaces are also in a similar way, using some POST parameters to enter the URL to obtain the returned Json data.

The previous essay defines the entity class information of GroupJson as shown below.

  /// <summary>
  /// Group information  /// </summary>
  public class GroupJson : BaseJsonResult
  {
    /// <summary>
    /// Group id, assigned by WeChat    /// </summary>
    public int id { get; set; }

    /// <summary>
    /// Group name, UTF8 encoding    /// </summary>
    public string name { get; set; }
  }

Based on the definitions of the above interfaces, I have defined several interfaces and summarized them into the user-managed API interface.

    /// <summary>
    /// Query all groups    /// </summary>
    /// <param name="accessToken">Calling interface credentials</param>    /// &lt;returns&gt;&lt;/returns&gt;
    List&lt;GroupJson&gt; GetGroupList(string accessToken);
            
    /// &lt;summary&gt;
    /// Create grouping    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="name">Group name</param>    /// &lt;returns&gt;&lt;/returns&gt;
    GroupJson CreateGroup(string accessToken, string name);
            
    /// &lt;summary&gt;
    /// Query the user's group    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="openid">User's OpenID</param>    /// &lt;returns&gt;&lt;/returns&gt;
    int GetUserGroupId(string accessToken, string openid);
    
    /// &lt;summary&gt;
    /// Modify the group name    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="id">Group id, assigned by WeChat</param>    /// <param name="name">Group name (within 30 characters)</param>    /// &lt;returns&gt;&lt;/returns&gt;
    CommonResult UpdateGroupName(string accessToken, int id, string name);
            
    /// &lt;summary&gt;
    /// Mobile user grouping    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="openid">User's OpenID</param>    /// <param name="to_groupid">Groupid id</param>    /// &lt;returns&gt;&lt;/returns&gt;
    CommonResult MoveUserToGroup(string accessToken, string openid, int to_groupid);

2. Implementation of user group management interface

2.1 Create user grouping

In order to analyze how to implement POST data operations for creating user groups, we will understand the specific process of creating users step by step.

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 = ("/cgi-bin/groups/create?access_token={0}", accessToken);
var data = new
 {
  group = new
 {
  name = name
  }
 };
string postData = ();

Among them, we convert the object into appropriate Json data operations and put it in the extension method ToJson. This is mainly to facilitate the dynamically defined entity class to convert Json content, mainly to call serial number operations.

/// &lt;summary&gt;
/// Make the object as a json string/// &lt;/summary&gt;
/// <param name="obj">Object to be serial number</param>/// &lt;returns&gt;&lt;/returns&gt;
public static string ToJson(this object obj)
 {
  return (obj, );
 } 

After preparing the Post data, we will take a closer look at the operation code that obtains the data and converts it to a suitable format.

GroupJson group = null;

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

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

/// &lt;summary&gt;
/// Convert Json string to specific object/// &lt;/summary&gt;
/// <param name="url">Returns the link address of Json data</param>/// <param name="postData">POST submitted data</param>/// &lt;returns&gt;&lt;/returns&gt;
    public static T ConvertJson(string url, string postData)
    {
      HttpHelper helper = new HttpHelper();
      string content = (url, postData, true);
      VerifyErrorCode(content);

      T result = &lt;T&gt;(content);
      return result;
    }

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

    /// &lt;summary&gt;
    /// Create grouping    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="name">Group name</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public GroupJson CreateGroup(string accessToken, string name)
    {
      string url = ("/cgi-bin/groups/create?access_token={0}", accessToken);
      var data = new
      {
        group = new
        {
          name = name
        }
      };
      string postData = ();

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

2.2 Query all groups

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

    /// &lt;summary&gt;
    /// Query all groups    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public List&lt;GroupJson&gt; GetGroupList(string accessToken)
    {
      string url = ("/cgi-bin/groups/get?access_token={0}", accessToken);

      List&lt;GroupJson&gt; list = new List&lt;GroupJson&gt;();
      GroupListJsonResult result = JsonHelper&lt;GroupListJsonResult&gt;.ConvertJson(url);
      if (result != null &amp;&amp;  != null)
      {
        ();
      }

      return list;
    }

2.3 Query the user's group

Each user belongs to a group, and by default it is in Ungrouped. We can obtain the user's group information through the API, that is, obtain the ID of the user group.

    /// &lt;summary&gt;
    /// Query the user's group    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="openid">User's OpenID</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public int GetUserGroupId(string accessToken, string openid)
    {
      string url = ("/cgi-bin/groups/getid?access_token={0}", accessToken);
      var data = new
      {
        openid = openid
      };
      string postData = ();

      int groupId = -1;
      GroupIdJsonResult result = JsonHelper&lt;GroupIdJsonResult&gt;.ConvertJson(url, postData);
      if (result != null)
      {
        groupId = ;
      }
      return groupId;
    }

2.4 Modify the group name

In practice, the grouping where the user is located can also be adjusted, and the operation code is as follows.

    /// &lt;summary&gt;
    /// Modify the group name    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="id">Group id, assigned by WeChat</param>    /// <param name="name">Group name (within 30 characters)</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public CommonResult UpdateGroupName(string accessToken, int id, string name)
    {
      string url = ("/cgi-bin/groups/update?access_token={0}", accessToken);
      var data = new
      {
        group = new
        {
          id = id,
          name = name
        }
      };
      string postData = ();

      return (url, postData);
    }

The return value CommonResult here is an entity class that contains the success or failure of bool and the error message of String type (if any).

For this GetExecuteResult function body, it is mainly a function that submits data, then obtains the result, and processes it according to the result.

    /// &lt;summary&gt;
    /// General operation results    /// &lt;/summary&gt;
    /// <param name="url">Web page address</param>    /// <param name="postData">Submitted data content</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static CommonResult GetExecuteResult(string url, string postData = null)
    {
      CommonResult success = new CommonResult();
      try
      {
        ErrorJsonResult result;
        if (postData != null)
        {
          result = JsonHelper&lt;ErrorJsonResult&gt;.ConvertJson(url, postData);
        }
        else
        {
          result = JsonHelper&lt;ErrorJsonResult&gt;.ConvertJson(url);
        }

        if (result != null)
        {
           = ( == ReturnCode.Request succeeded);
           = ;
        }
      }
      catch (WeixinException ex)
      {
         = ;
      }

      return success;
    } 
  }

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

2.5 Move users to new grouping

The operation of moving users to a new group is similar to the one in the above section, please see the code for details.

    /// &lt;summary&gt;
    /// Mobile user grouping    /// &lt;/summary&gt;
    /// <param name="accessToken">Calling interface credentials</param>    /// <param name="openid">User's OpenID</param>    /// <param name="to_groupid">Groupid id</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public CommonResult MoveUserToGroup(string accessToken, string openid, int to_groupid)
    {
      string url = ("/cgi-bin/groups/members/update?access_token={0}", accessToken);
      var data = new
      {
        openid = openid,
        to_groupid = to_groupid
      };
      string postData = ();

      return (url, postData);
    }

3. Calling of user group interface

In the above section, various interfaces for user grouping are defined and implemented. All user-related codes have been posted without reservation. Its call operation is shown in the following code (test code).

    private void btnGetGroupList_Click(object sender, EventArgs e)
    {
      IUserApi userBLL = new UserApi();
      List&lt;GroupJson&gt; list = (token);
      foreach (GroupJson info in list)
      {
        string tips = ("{0}:{1}", , );
        (tips);
      }
    }

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

      string tips = ("GroupId:{0}", groupId);
      (tips);
    }

    private void btnCreateGroup_Click(object sender, EventArgs e)
    {
      IUserApi userBLL = new UserApi();
      GroupJson info = (token, "Create a test group");
      if (info != null)
      {
        string tips = ("GroupId:{0} GroupName:{1}", , );
        (tips);

        string newName = "Create test modification";
        CommonResult result = (token, , newName);
        ("Modify the group name:" + ( ? "success" : "fail:" + ));
      }
    }

    private void btnUpdateGroup_Click(object sender, EventArgs e)
    {
      int groupId = 111;
      string newName = "Create test modification";

      IUserApi userBLL = new UserApi();
      CommonResult result = (token, groupId, newName);
      ("Modify the group name:" + ( ? "success" : "fail:" + ));
    }

    private void btnMoveToGroup_Click(object sender, EventArgs e)
    {
      int togroup_id = 111;//Input the group ID
      if (togroup_id &gt; 0)
      {
        IUserApi userBLL = new UserApi();
        CommonResult result = (token, openId, togroup_id);

        ("Mobile User Group Name:" + ( ? "success" : "fail:" + ));
      }
    }

After understanding the above code and call rules, we can manage user grouping information through the API. By integrating relevant interface code into the application, we can control our attention user list and user grouping information well. This will lay a solid foundation for our next step of user information push.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.