. NET public account development-3.0 query custom menu,. net-3.0
I. Preface
We have created a custom menu. Now, how can we query our custom menu.
The principles are the same, and they are quite simple, but the interface address document has been replaced.
Start encoding 2.0
In the same way, we first create my query page. Here we use the aspx page selectMenu. aspx
protected void Page_Load(object sender, EventArgs e) { var str = GetPage("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd811f56f3&secret=76eb33f661296"); JObject jo = JObject.Parse(str); access_token = jo["access_token"].ToString(); GetPage("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + access_token + ""); //GetPage("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token"); }
Check whether the code is quite simple. I believe this is not a problem for you. Similarly, it is very easy to delete the custom menu, except that the interface address is changed. The previous article on the code of the GetPage method already exists, so it will not be repeated here.
3.0 token optimization.
We already know how to get our access_token. We know that its validity period is 7200 s. Isn't it very troublesome for us to get it again in every request, it is not conducive to performance optimization. Here we have made some optimizations to this token acquisition method, which is more conducive to our code.
Here we first create an AccessToken class to store some of our information. The Code is as follows:
/// <Summary> /// license token /// </summary> public class accesen en {// <summary> /// Save the obtained license token, the key is the public account, and the value is the token obtained last time by the Public Account /// </summary> private static ConcurrentDictionary <string, Tuple <AccessToken, dateTime> accessTokens = new ConcurrentDictionary <string, Tuple <AccessToken, DateTime> (); /// <summary> /// obtain the access token address /// </summary> private const string urlForGettingAccessToken =" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= {0} & secret = {1} "; // <summary> // obtain the http Method of access token /// </summary> private const string httpMethodForGettingAccessToken = WebRequestMethods. http. get; /// <summary> /// maximum time (in seconds) for saving the access token. After the time expires, you need to re-obtain /// </summary> private const int accessTokenSavingSeconds = 7000; /// <summary> /// access token /// </summary> public string access_token {get; set ;}/// <summary> // valid time, unit: seconds /// </s Ummary> public int expires_in {get; set ;} /// <summary> /// constructor /// </summary> /// <param name = "_ access_token"> access token </param> /// <param name = "_ expires_in"> validity period </param> internal AccessToken (string _ access_token, int _ expires_in) {access_token = _ access_token; expires_in = _ expires_in ;} /// <summary> /// return the AccessToken string /// </summary> /// <returns> </returns> public override string ToStr Ing () {return string. format ("AccessToken: {0} \ r \ n Valid time: {1} seconds", access_token, expires_in );} /// <summary> /// parse AccessToken from the JSON string /// </summary> /// <param name = "json"> JSON string </param> // /<returns> return AccessToken </returns> internal static AccessToken ParseFromJson (string json) {var at = JsonConvert. deserializeAnonymousType (json, new {access_token = "", expires_in = 1}); return new AccessToken (. Access_token,. expires_in );} /// <summary> /// try to parse the AccessToken from the JSON string /// </summary> /// <param name = "json"> JSON string </param>/ // <param name = "msg"> If the resolution is successful, return AccessToken; otherwise, return null. </Param> // <returns> whether the resolution is successful </returns> internal static bool TryParseFromJson (string json, out AccessToken token) {bool success = false; token = null; try {token = ParseFromJson (json); success = true;} catch {} return success ;} /// <summary> /// get the access token /// </summary> /// <param name = "userName"> Public Account </param> /// <returns> return access token </returns> public static AccessToken Get (string userN Ame) {Tuple <AccessToken, DateTime> lastToken = accessTokens. ContainsKey (userName )? AccessTokens [userName]: null; AccessToken token = lastToken = null? Null: lastToken. Item1; DateTime refreshTime = lastToken = null? DateTime. minValue: lastToken. item2; double MS = (DateTime. now-refreshTime ). totalSeconds; if (MS> accessTokenSavingSeconds | token = null) {// try to get 2 ErrorMessage msg from the server; AccessToken newToken = GetFromWeixinServer (userName, out msg ); if (newToken = null) newToken = GetFromWeixinServer (userName, out msg); if (newToken! = Null) {lastToken = new Tuple <AccessToken, DateTime> (newToken, DateTime. now); accessTokens [userName] = lastToken; token = newToken;} return token ;} /// <summary> /// obtain the access token from the server /// </summary> /// <param name = "userName"> Public Account </param> // /<param name = "msg"> error message returned from the server. </Param> // <returns> returns the license token. If the token fails to be obtained, null is returned. </Returns> private static AccessToken GetFromWeixinServer (string userName, out ErrorMessage msg) {AccessToken token = null; msg = new ErrorMessage (ErrorMessage. predictioncode, ""); string url = string. format (urlForGettingAccessToken, WxPayConfig. APPID, WxPayConfig. APPSECRET); string result; if (! HttpHelper. Request (url, out result, httpmethodforgettingaccesen en, string. Empty) {msg. errmsg = "failed to get the response from the server. "; Return token;} if (ErrorMessage. isErrorMessage (result) msg = ErrorMessage. parse (result); else {try {token = AccessToken. parseFromJson (result);} catch (Exception e) {msg = new ErrorMessage (e) ;}} return token ;}}
From the code in this class, we can see that every time we get the access_token, we will judge whether some time has exceeded 7000, and our token expiration time is 7200 s, in this way, you do not need to re-obtain the token for each request.
At this time, our query code can be optimized.
protected void Page_Load(object sender, EventArgs e) {
String username = System. Configuration. ConfigurationManager. receivettings ["weixinid"]. ToString ();
AccessToken token = AccessToken. Get (username );
GetPage("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" + access_token + ""); //GetPage("https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token"); }
I have limited capabilities. I hope you will be able to forgive me.
4.0 public account Development Series
1.0 initial public account
2.0 create a custom menu
3.0 query a custom menu
If you feel good after reading this article, click 【Follow] To support the blogger. Thank you!
If you feel good after reading this article, click
[Recommended]
Author:Feng Xiaoyi
QQ: 616931
Source:Http://www.cnblogs.com/fenglingyi
Statement:The copyright of this article is shared by the author and the blog Park. This statement must be retained without the author's consent and the original article connection must be clearly provided on the article page. Otherwise, the legal liability will be retained.