In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares with you is about how to pay attention to user list and detailed information management in the development of Wechat portal and application by C#. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article. Say no more, come and have a look with the editor.
A very important feature of Wechat is its ability to take advantage of the large user base of its platform, so it is easy to integrate into the CRM (customer relationship management) system. Both service numbers and subscriptions can push relevant product messages to followers and have interactive conversations with active users who respond to messages and events within 48 hours, so user information is a very important part of Wechat API. This essay mainly introduces the development and application of getting follow users, viewing user information, grouping management and so on.
1. Follow the user list and user grouping information
On Wechat's management platform, we can see the follower users of our account, as well as user group information, as shown below.
In the above management interface, you can see the basic information of the followers, but what you get using Wechat API is a list called OpenID. What is this thing first? The description of Wechat API gives the following analysis:
The follower list consists of a string of OpenID (encrypted WeChat account, where each user is unique to the OpenID of each official account. For different official accounts, the openid of the same user is different. Through this API, official account can obtain basic user information based on OpenID, including nickname, profile picture, gender, city, language and time of following.
The meaning of the above parsing is very clear, that is, a user follows our official account, so no matter how many times he follows, it is a certain value for our official account; however, a user has a different OpenID for other official accounts.
Wechat provides a few keyword information, which is used to record the relevant content of the user. According to the relevant definition of the user, we define an entity class that is used to place the obtained user information.
/ / the user information obtained by the advanced interface. / / after the follower interacts with the official account, the official account can get the follower's OpenID / (encrypted WeChat account), and each user has a unique OpenID for each official account. For different official accounts, the openid of the same user is different. / / the official account can obtain basic user information based on OpenID, including nickname, profile picture, gender, city, language and follow time through this API. / public class UserJson: BaseJsonResult {/ whether the user subscribes to the official account logo. A value of 0 means that the user does not follow the official account and cannot get the rest of the information. / public int subscribe {get; set;} / the identity of the user, the current official account unique / public string openid {get; set;} / the nickname of the user / public string nickname {get; set;} / the user's gender, male at 1, female at 2, unknown / public int sex {get; set at 0 / user's language, simplified Chinese is zh_CN / public string language {get; set;} / user's city / public string city {get; set;} / user's province / public string province {get; set;} / user's country / public string country {get; set } / user avatar. The last value represents the square avatar size (optional values of 0,46,64,96,132, 0 represents 640mm 640 square avatar). If the user does not have an avatar, this item is empty / public string headimgurl {get; set;} / user attention time, which is a timestamp. If the user has followed multiple times, take the last follow time / public long subscribe_time {get; set;}}
According to the definition of grouping information, we define a grouped entity class information.
/ public class GroupJson: BaseJsonResult {/ grouping id, assigned by Wechat / public int id {get; set;} / grouped name, UTF8 code / public string name {get; set;}}
2. Obtain the Token of the AIP caller
In the development of Wechat API, most of the time, we need to pass in an AccessToken, which is a string that distinguishes callers from recording session information, so we need to have a good understanding of this access control parameter before learning all API development.
The definition of this object can be seen in the API description of Wechat.
Access_token is the global unique ticket of the official account, which needs to use access_token when calling each interface. Under normal circumstances, the access_token is valid for 7200 seconds. Repeated acquisition will invalidate the last acquired access_token. Since the number of api calls to obtain access_token is very limited, it is recommended that developers store and update access_token globally. Frequent refresh of access_token will result in limited api calls and affect their business.
According to the above definition, we can see that it is a parameter related to identity and session time, and its generation is limited, so we need to cache it and reuse it. Before the session expires, we should reuse this parameter as much as possible to avoid repeated requests, increase server pressure, and call time.
I defined a method to construct and generate the relevant Access Token, and it has the function of caching, but how to cache and use, the call to my API is transparent, we just call it when we use it.
/ / get credential API / third-party user unique credential / third-party user unique credential key, appsecret string GetAccessToken (string appid, string secret)
Caching is mainly based on the addition of the. Net 4 class library MemoryCache, which is a very good cache class.
The implementation code for my operation to get AccessToken is as follows.
/ obtain the Token access token for each operation of Wechat API / Application ID / developer credentials / public string GetAccessToken (string appid, string secret) {/ / normally the access_token is valid for 7200 seconds. If you use the cache setting less than this time, you can string access_token = MemoryCacheHelper.GetCacheItem ("access_token", delegate () {string grant_type = "client_credential"). Var url = string.Format ("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret); HttpHelper helper = new HttpHelper (); string result = helper.GetHtml (url); string regex ="\ "access_token\":\ "(?. *?)\"; string token = CRegex.GetText (result, regex, "token"); return token }, new TimeSpan (0, 0, 7000) / / 7000 seconds expire); return access_token;}
Since we know that AccessToken expires in 7200 seconds by default, we use the cache to record its value as much as possible during this period of time. If we call this method beyond this time, it will automatically retrieve a new value to us.
3. Get the list of followers
Get the list of followers, pull the API call at a time, and pull the OpenID of up to 10000 followers, which can be pulled multiple times to meet the demand. The interface definition of Wechat is as follows.
Http request method: GET (please use https protocol)
Https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
The data returned by this interface is
{"total": 2, "count": 2, "data": {"openid": ["," OPENID1 "," OPENID2 "]}," next_openid ":" NEXT_OPENID "}
Based on the definition of the returned Json data, we also need to define two entity classes to hold the returned results.
/ public class UserListJsonResult: BaseJsonResult {/ the total number of users following the public account / public int total {get; set;} / the number of OPENID pulled by the public account. The maximum is 10000 / public int count {get; set;} / list data, and the list of OPENID / public OpenIdListData data {get Set;} / pull the OPENID / public string next_openid {get; set;}} / list data of the last user of the list, the list of OPENID / / public class OpenIdListData {/ OPENID / public List openid {get; set;}}
In order to get the relevant user information, I define an interface to get the user's information, as shown below.
/ the API API managed by Wechat users / public interface IUserApi {/ get the list of interested users / call the API credential / the first OPENID pulled. If left empty, pull / List GetUserList from scratch by default (string accessToken, string nextOpenId = null) / get the basic information of the user / call the API credential / the identification of the ordinary user, and return the national and regional language version for the current official account only / return the national language version, zh_CN simplified, zh_TW traditional, en English UserJson GetUserDetail (string accessToken, string openId, Language lang = Language.zh_CN)
Then in the implementation class, we implement the above two interfaces respectively to obtain the user list information as shown below.
/ get the list of interested users / call the API credential / the first OPENID pulled. Leave it empty and pull / public List GetUserList from scratch by default (string accessToken, string nextOpenId = null) {List list = new List (); string url = string.Format ("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}", accessToken) If (! string.IsNullOrEmpty (nextOpenId)) {url + = "& next_openid=" + nextOpenId;} UserListJsonResult result = JsonHelper.ConvertJson (url); if (result! = null & & result.data! = null) {list.AddRange (result.data.openid);} return list;}
We can see that the logic of the transformation has been put into JsonHelper. This auxiliary class acquires the contents of the value, verifies the return value, and then converts the operations of several parts of the correct entity class.
Get the content through the auxiliary class HttpHelper, which is in my common class library, in which the logic is mainly through the HttpRequest data acquisition operation, not to repeat.
HttpHelper helper = new HttpHelper (); string content = helper.GetHtml (url)
Because of the returned content, we need to determine whether it correctly returns the desired results, and if not, throw a custom related exception to facilitate handling, as shown below.
/ check the returned record. If no error is returned, or if the result indicates success, the result returned by the exception / private static bool VerifyErrorCode (string content) {if (content.Contains ("errcode")) {ErrorJsonResult errorResult = JsonConvert.DeserializeObject (content) is not thrown. Exceptions are logged only for unsuccessful operations, because some operations return normal results ({"errcode": 0, "errmsg": "ok"}) if (errorResult! = null & & errorResult.errcode! = ReturnCode. Request succeeded) {string error = string.Format ("Wechat request error! error code: {0}, description: {1}", (int) errorResult.errcode, errorResult.errmsg); LogTextHelper.Error (errorResult); throw new WeixinException (error); / / throw error}} return true;}
And then converted to the corresponding format, that is, through the Json.NET class library for conversion.
T result = JsonConvert.DeserializeObject (content); return result
In this way, we can complete the processing and conversion in the ConvertJson function entity, and the complete function code is as follows.
/ Json string manipulation helper class / public class JsonHelper where T: class, new () {/ check the returned record. If no error is returned, or if the result indicates success, the returned result / private static bool VerifyErrorCode (string content) {if (content.Contains ("errcode")) {ErrorJsonResult errorResult = JsonConvert.DeserializeObject (content) is not thrown. Exceptions are logged only for unsuccessful operations, because some operations return normal results ({"errcode": 0, "errmsg": "ok"}) if (errorResult! = null & & errorResult.errcode! = ReturnCode. Request successful) {string error = string.Format ("error occurred in Wechat request! Error code: {0}, description: {1} ", (int) errorResult.errcode, errorResult.errmsg); LogTextHelper.Error (errorResult); throw new WeixinException (error); / / throw error}} return true;} / convert the Json string to the specific object / return the link address of Json data / public static T ConvertJson (string url) {HttpHelper helper = new HttpHelper () String content = helper.GetHtml (url); VerifyErrorCode (content); T result = JsonConvert.DeserializeObject (content); return result;}}
The interface layer code that calls this API is as follows (test code)
IUserApi userBLL = new UserApi (); List userList = userBLL.GetUserList (token)
4. Get user details
The operation of getting the list above is relatively simple and does not require any data from POST, so the required data can be obtained through the Get protocol.
This section continues with the operation of getting user details, which can also be done through the GET protocol.
The call definition for this API is as follows:
Http request method: GET
Https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
By passing in an OpenId, we can get the relevant information about the user very well.
We have defined its interface in the previous section, explaining the incoming and return values, and according to the definition, its implementation function is as follows.
/ get the basic information of the user / call the API credential / the ID of the ordinary user, and return the national and regional language version for the current official account, zh_CN simplified, zh_TW traditional En English public UserJson GetUserDetail (string accessToken, string openId, Language lang = Language.zh_CN) {string url = string.Format ("https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang={2}", accessToken, openId, lang.ToString ()) UserJson result = JsonHelper.ConvertJson (url); return result;}
Finally, combining the two API that gets the user list and the user details, let's take a look at the calling code (test code).
Private void btnGetUsers_Click (object sender, EventArgs e) {IUserApi userBLL = new UserApi (); List userList = userBLL.GetUserList (token); foreach (string openId in userList) {UserJson userInfo = userBLL.GetUserDetail (token, openId); if (userInfo! = null) {string tips = string.Format ("{0}: {1}", userInfo.nickname, userInfo.openid); Console.WriteLine (tips) The above is how to pay attention to the management of user lists and details in the development of Wechat portals and applications by C#. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.