C # development WeChat Portal and application (iv) user list and detailed information management

Source: Internet
Author: User
Tags openid
This article is mainly for you to introduce the C # development portal and application of the fourth, the attention to user lists and detailed information management, with a certain reference value, interested in small partners can refer to

In the last month of the C # development portal and application of the introduction, wrote a few essays to share, because of time, interval for a period of time did not continue to write this series of blogs, not to this aspect of the study, but continue to explore this aspect of technology, in order to better apply, Concentrate on the technical development of the bottom.

An important feature is the ability to take advantage of the vast user base of its platform, so it is easy to integrate in the CRM (Customer Relationship Management) system, service numbers and subscriptions are able to push related product messages to followers, as well as interactive conversations with active users who respond to messages and events within 48 hours. So user information is a very important part of the API, this essay mainly introduces the development and application of getting attention to users, viewing user information, grouping management and so on.

1, focus on user list and user group information

On the management platform, we can see the user of our account followers, as well as the user group information, as shown below.

The above management interface, you can see the basic information of the followers user, but using the API to get a list called OpenID, we first understand what this thing is? The description of the API gives the following parsing:

The list of followers consists of a string of OpenID (encrypted number, each user is unique to each OpenID of the public number. For different public numbers, the same user's OpenID is different) composition. The public can use this interface to access basic user information based on OpenID, including nickname, Avatar, Gender, city, language and time of concern.

The above analytic meaning is very clear, is a user pays attention to our public number, then whether he is the first attention, is a certain value to US public number, but, one user to other public number, but has the other different OpenID.

A few keyword information is provided to record the user's relevant content, according to the user's relevant definition, we define an entity class, used to put back the user information.


 <summary>///Advanced interface to obtain user information. After the message interaction between the followers and the public, the public number is available to the followers ' OpenID///(encrypted number, each user is unique to the OpenID for each public number). For different public numbers, the same user's OpenID is different). The public can use this interface to access basic user information based on OpenID, including nickname, Avatar, Gender, city, language and time of concern. </summary> public class Userjson:basejsonresult {///<summary>//The user subscribes to the publicity ID, the value is 0 o'clock, on behalf of this user is not concerned about the public number, pull not To the rest of the information.  </summary> public int Subscribe {get; set;}///<summary>//user's identity, unique to current general String OpenID {get; set;}//<summary>//user's nickname///</summary> public string Nickname {get; set;}///  lt;summary>///user's gender, value 1 o'clock is male, value 2 o'clock is female, value 0 o'clock is unknown//</summary> public int sex {get; set;}//<summary>// User's language, Simplified Chinese is zh_cn//</summary> public string language {get; set;}///<summary>//The user's city///</summar Y> public string City {get; set;}//<summary>///</summary> public string Province {get; s Et }///<summary>//user country///</summary> public String Country {get; set;}//<summary>//user picture, the last value represents the size of the square head (0, 46, 64, 96, 132 values are optional, 0 represents the 640*640 square head), the user does not have the Avatar when the item is empty/// Lt;/summary> public string Headimgurl {get; set;}///<summary>//user focus time, timestamp. If the user has been concerned more than once, take the last attention time///</summary> public long subscribe_time {get; set;}}

Based on the grouping information definition, we define a grouped entity class information.


<summary>///Group information///</summary> public class Groupjson:basejsonresult {///<summary>///group ID, by  Assign//</summary> public int ID {get; set;}///<summary>///Group name, UTF8 encoding///</summary> public string name {get; set;}}

2. Obtain the token of the AIP caller

In the development of API, many times, we need to pass in a accesstoken, this is to distinguish between the caller and the recording session information of the string, so before we learn all the API development, we need to understand this access control parameters well.

The definition of this object, which we can learn from the API description.

Access_token is the public number's globally unique ticket, and the public number needs to use Access_token when invoking each interface. Normally the Access_token is valid for 7,200 seconds, and a duplicate fetch will result in the last acquired Access_token failure. since the number of API calls to get Access_token is very limited, it is recommended that developers global storage and update Access_token, frequent refresh Access_token will cause API calls to be restricted and affect their business.

As defined above, we can see that it is a parameter related to identity and session time, and it has a limit on the number of times it is generated, so we need to cache it and reuse it, we should reuse this parameter as much as possible before the session expires, avoid repeated requests, increase server pressure, And the time of the call.

I have defined a method for building the associated access Token, and it has the ability to cache, but specifically how to cache and use it, the call to my API is transparent, and we just call it when we use it.


Get voucher interface///</summary>//<param name= "AppID" > Third party User unique voucher </param>//<param name= "Secret" > Third-party user unique credential key, both appsecret</param> string Getaccesstoken (String AppID, String secret);

The cache is primarily based on the. NET4 added class library memorycache, this is a very good cache class.

The operation implementation code for my get Accesstoken is shown below.


///<summary>///Get token access token per operation API///</summary>//<param name= "AppID" > Application id</param>//<param name= "secret" > Developer credentials </param>//<returns></returns> public String Getaccesstoken (String AppID, String secret) {//normally access_token valid for 7,200 seconds, here the cache setting is shorter than this time can be string Access_token   = Memorycachehelper.getcacheitem<string> ("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\ ": \" (? <token>.*?)   \"";   String token = Cregex.gettext (result, regex, "token");  return token;  }, new TimeSpan (0, 0, 7000)//7000 seconds expired);   return access_token; }

As we know, accesstoken default is 7,200 seconds expired, so in this time period, we use the cache to record its value, if it exceeds this time, we call this method, it will automatically regain a new value to us.

3. Get a list of your followers

Get a list of watchlist, one pull API call, up to 10,000 followers of OpenID, can be pulled through multiple pull to meet the needs. The interface definition is as follows.

HTTP request mode: GET (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 JSON data returned, we also need to define two entity classes to hold the returned results.


<summary>////Get JSON results for user list///</summary> public class Userlistjsonresult:basejsonresult {//<su Mmary>///The total number of users who are concerned with the public account////</summary> general int full {get; set;}///<summary>///Pull the number of OpenID, the maximum value is 100 XX//</summary> public int count {get; set;}///<summary>//list data, List of OpenID//</summary> public  Openidlistdata data {get; set;}///<summary>///The next user's OpenID//</summary> public string Next_openid {get; set;}} <summary>///list data, List of OpenID///</summary> public class Openidlistdata {//<summary>///OpenID column Table///</summary> public list<string> OpenID {get; set;}}

In order to obtain the relevant user information, I have defined an interface that is used to obtain the user's information, and the interface definition is as follows.


<summary>///user-managed API interface///</summary> public interface Iuserapi {///<summary>//Get a list of watchlist/// lt;/summary>//<param name= "Accesstoken" > Call interface Voucher </param>//<param name= "Nextopenid" > First pull the OpenID, do not fill the default from start to pull </param>///<returns></returns> list<string> getuserlist (string Accesstoken, string nextopenid = null); <summary>/////</summary>//<param name= "Accesstoken" > Invoke interface Credentials </param>//< param name= "OpenId" > General user identification, unique to the current public number </param>//<param name= "lang" > Return country language version, ZH_CN simplified, zh_tw traditional, en English </param> Userjson getuserdetail (String Accesstoken, String openId, Language lang = LANGUAGE.ZH_CN);

Then in the implementation class, we implement the above two interfaces separately, get the user list information as shown below.


<summary>///Get a list of users///</summary>/<param name= "Accesstoken" > Invoke interface Credentials </param>//< param name= "Nextopenid" > First pull of OpenID, do not fill the default from start to pull </param>//<returns></returns> public List <string> getuserlist (String accesstoken, string nextopenid = null) {  list<string> List = new List<stri Ng> ();  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<userlistjsonresult>. Convertjson (URL);  if (result! = NULL && Result.data! = null)  {  list. AddRange (Result.data.openid);  }  return list; }

We see that the logic of the transformation has been put into the jsonhelper, the helper class inside the value of the content, verify the return value, and then convert the correct entity class several parts of the operation.

Get the content, through the auxiliary class Httphelper, this in my common class library, inside 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 returns the desired result correctly, and if not, throws a custom related exception that is convenient to handle, as shown below.


<summary>////check returned records, if no error is returned, or the result prompt succeeds, do not throw exception///</summary>//<param name= "Content" > returned results </param>//<returns></returns> private static bool Verifyerrorcode (string content) {  if ( Content. Contains ("Errcode"))  {  Errorjsonresult errorresult = jsonconvert.deserializeobject<errorjsonresult> (content);  The exception was logged for a non-successful operation because some operations returned a normal result ({"Errcode": 0, "errmsg": "OK"})  if (errorresult! = null && Errorresult.errcode ! = ReturnCode. Request succeeded)  {   string error = String. Format ("The request has an error! Error code: {0}, Description: {1} ", (int) errorresult.errcode, errorresult.errmsg);   Logtexthelper.error (Errorresult);   throw new Weixinexception (error);//Throw Error  }  }  return true;

It is then converted to the appropriate format, through the Json.NET class library.


T result = jsonconvert.deserializeobject<t> (content); return result;

This allows us to process and convert the complete function code in the Convertjson function entity, as shown below.


 <summary>////JSON string Manipulation helper class////</summary> public class jsonhelper<t> where T:class, new () {/// lt;summary>///check returned records, if no error is returned, or the result prompt succeeds, do not throw exception//</summary>//<param name= "Content" > Returned results </ param>//<returns></returns> private static bool Verifyerrorcode (string content) {if (content.  Contains ("Errcode")) {Errorjsonresult Errorresult = jsonconvert.deserializeobject<errorjsonresult> (content); The exception was logged for a non-successful operation because some operations returned a normal result ({"Errcode": 0, "errmsg": "OK"}) if (Errorresult! = NULL && errorresult.errcode! = Ret Urncode. Request succeeded} {string error = string. Format ("The request has an error!   Error code: {0}, Description: {1} ", (int) errorresult.errcode, errorresult.errmsg);   Logtexthelper.error (Errorresult); throw new Weixinexception (error);//Throw Error}} return true; }///<summary>//Convert JSON string to specific object////</summary>//<param name= "url" > return the link address of JSON data </param>/ <returns></returns> public static T Convertjson (stringURL) {Httphelper helper = new Httphelper (); String content = Helper.  gethtml (URL);  Verifyerrorcode (content);  T result = jsonconvert.deserializeobject<t> (content); return result; }}

The interface layer code that calls this API is shown below (test code)


Iuserapi USERBLL = new Userapi (); List<string> userlist = userbll.getuserlist (token)

4. Get User Details

The Get list operation above is relatively simple and does not post any data, so you get the required data through the GET protocol.

This section continues with the operation of getting user details, which can be done through the GET protocol.

The invocation definition for this API is as follows:

HTTP request mode: GET
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 a good information about the user.

In the previous section, we have defined its interface, which describes the incoming and returned values, and by definition, its implementation functions are as follows.

<summary>/////</summary>//<param name= "Accesstoken" > Invoke interface Credentials </param>//< param name= "OpenId" > General user identification, unique to the current public number </param>//<param name= "lang" > Return country language version, ZH_CN simplified, zh_tw traditional, en English </param> Public Userjson Getuserdetail (string Accesstoken, String openId, Language lang = language.zh_cn) {  str ing 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<userjson>. Convertjson (URL);  return result; }

Finally, we combine the two APIs to get a list of users and get user details, and we'll look at the code that was called (test code).


 private void Btngetusers_click (object sender, EventArgs e) {Iuserapi USERBLL = new Userapi ()  ;  List<string> 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); }  } }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.