Home Backend Development C#.Net Tutorial C# 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
.net Group application develop user portal

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"
  }
}
Copy after login

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; }
  }
Copy after login

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);
Copy after login

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();
Copy after login

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);
 }
Copy after login

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;
 }
Copy after login

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;
    }
Copy after login

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;
    }
Copy after login

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;
    }
Copy after login

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;
    }
Copy after login

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);
    }
Copy after login

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;
    } 
  }
Copy after login

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);
    }
Copy after login

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));
      }
    }
Copy after login

了解了上面的代码和调用规则,我们就能通过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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Xiaohongshu account to find users? Can I find my mobile phone number? How to use Xiaohongshu account to find users? Can I find my mobile phone number? Mar 22, 2024 am 08:40 AM

With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the &quot;Discover&quot; button in the lower right corner, and then select the &quot;Notes&quot; option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the &quot;Follow&quot; button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select &quot;Personal Information&quot;

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

How to Undo Delete from Home Screen in iPhone How to Undo Delete from Home Screen in iPhone Apr 17, 2024 pm 07:37 PM

Deleted something important from your home screen and trying to get it back? You can put app icons back on the screen in a variety of ways. We have discussed all the methods you can follow and put the app icon back on the home screen. How to Undo Remove from Home Screen in iPhone As we mentioned before, there are several ways to restore this change on iPhone. Method 1 – Replace App Icon in App Library You can place an app icon on your home screen directly from the App Library. Step 1 – Swipe sideways to find all apps in the app library. Step 2 – Find the app icon you deleted earlier. Step 3 – Simply drag the app icon from the main library to the correct location on the home screen. This is the application diagram

The role and practical application of arrow symbols in PHP The role and practical application of arrow symbols in PHP Mar 22, 2024 am 11:30 AM

The role and practical application of arrow symbols in PHP In PHP, the arrow symbol (-&gt;) is usually used to access the properties and methods of objects. Objects are one of the basic concepts of object-oriented programming (OOP) in PHP. In actual development, arrow symbols play an important role in operating objects. This article will introduce the role and practical application of arrow symbols, and provide specific code examples to help readers better understand. 1. The role of the arrow symbol to access the properties of an object. The arrow symbol can be used to access the properties of an object. When we instantiate a pair

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Analysis of user password storage mechanism in Linux system Analysis of user password storage mechanism in Linux system Mar 20, 2024 pm 04:27 PM

Analysis of user password storage mechanism in Linux system In Linux system, the storage of user password is one of the very important security mechanisms. This article will analyze the storage mechanism of user passwords in Linux systems, including the encrypted storage of passwords, the password verification process, and how to securely manage user passwords. At the same time, specific code examples will be used to demonstrate the actual operation process of password storage. 1. Encrypted storage of passwords In Linux systems, user passwords are not stored in the system in plain text, but are encrypted and stored. L

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

See all articles