Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use .net to get ACCESSTOKEN in Wechat public platform development

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the Wechat public platform development how to use .net to obtain ACCESSTOKEN, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to know about it.

After the follower interacts with the official account, the official account can get the follower's OpenID (encrypted WeChat account, and each user's OpenID is unique to each official account. For different official accounts, the openid of the same user is different.

The official account can use this http://www.php.cn/code/11829.html" target= "_ blank" > interface to obtain basic user information based on OpenID, including nickname, profile picture, gender, city, language and time of following.

Developers can get basic user information through OpenID. Please use https protocol.

We can look at the official documentation: get the basic information of the user.

API call request description

Http request method: GET

Api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

Parameter description

Whether the parameter must indicate that access_token is the calling API credential openid is the identity of the ordinary user, and whether the unique lang of the current official account returns the national and regional language version, zh_CN simplified, zh_TW traditional, en English

Return description

Normally, Wechat will return the following JSON packets to the official account:

{"subscribe": 1, "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", "nickname": "Band", "sex": 1, "language": "zh_CN", "city": "zh_CN", "province": "Guangdong", "country": "China", "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0"," subscribe_time ": 1382694957 "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"remark": "", "groupid": 0}

Parameter description

Parameter indicates whether the subscribe user subscribes to the official account ID. A value of 0 means that the user does not follow the official account and cannot pull the rest of the information. The identity of the openid user. The gender of the sex user, which is the nickname of the current unique nickname user on the official account. A value of 1 is male, and a value of 2 is female. If the value is 0, it is the language of the province user in the province where the country user is located in the city where the unknown city user is located. The simplified Chinese is the zh_CNheadimgurl user avatar, and the last value represents the size of the square avatar (optional values are 0, 46, 64, 96, 132). 0 represents a 640mm 640 square avatar). This item is empty when the user does not have an avatar. If the user changes the avatar, the original avatar URL will be invalid. Subscribe_time users follow the time, which is a timestamp. If the user has followed multiple times, the unionid will not appear until the user binds the official account to the Wechat open platform account. For more information, see: access to users' personal information (UnionID mechanism) remarks to fans by remark official account operators. Official account operators can add comments to fans in the user management interface of Wechat public platform. Groupid users' group ID

Wechat will return information such as error code when an error occurs. An example of JSON packet is as follows (this example is an invalid AppID error):

{"errcode": 40013, "errmsg": "invalid appid"}

Based on the above information, we define a user information class to store the user's basic information.

Package com.souvc.weixin.pojo;/*** class name: WeixinUserInfo * description: basic information of Wechat users * developer: souvc * creation time: 2015-11-27 * release version: V1.0 * / public class WeixinUserInfo {/ / user's identity private String openId; / / follow status (1 is followed, 0 is not followed). You can't get the rest of the information if you don't follow private int subscribe. / / the user follows the time, which is a timestamp. If the user has followed many times, take the last follow time private String subscribeTime; / / nickname private String nickname; / / the gender of the user (1 is male, 2 is female, 0 is unknown) private int sex; / / the user's country private String country; / / user's province private String province; / / user's city private String city; / / user's language, simplified Chinese is zh_CN private String language / / user profile private String headImgUrl; public String getOpenId () {return openId;} public void setOpenId (String openId) {this.openId = openId;} public int getSubscribe () {return subscribe;} public void setSubscribe (int subscribe) {this.subscribe = subscribe;} public String getSubscribeTime () {return subscribeTime;} public void setSubscribeTime (String subscribeTime) {this.subscribeTime = subscribeTime;} public String getNickname () {return nickname } public void setNickname (String nickname) {this.nickname = nickname;} public int getSex () {return sex;} public void setSex (int sex) {this.sex = sex;} public String getCountry () {return country;} public void setCountry (String country) {this.country = country;} public String getProvince () {return province;} public void setProvince (String province) {this.province = province } public String getCity () {return city;} public void setCity (String city) {this.city = city;} public String getLanguage () {return language;} public void setLanguage (String language) {this.language = language;} public String getHeadImgUrl () {return headImgUrl;} public void setHeadImgUrl (String headImgUrl) {this.headImgUrl = headImgUrl;}}

Let's first take a look at the interface for obtaining user information:

Https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

According to the analysis, a token is needed to get the basic information of the user.

Package com.souvc.weixin.pojo;/*** class name: Token * description: credential * developer: souvc * creation time: 2015-11-27 * release version: V1.0 * / public class Token {/ / API access credential private String accessToken; / / credential validity period, in seconds: private int expiresIn; public String getAccessToken () {return accessToken;} public void setAccessToken (String accessToken) {this.accessToken = accessToken } public int getExpiresIn () {return expiresIn;} public void setExpiresIn (int expiresIn) {this.expiresIn = expiresIn;}}

Https request, required trust manager

Package com.souvc.weixin.util;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager / * Class name: MyX509TrustManager * description: trust Manager * developer: souvc * creation time: 2015-11-27 * release: V1.0 * / public class MyX509TrustManager implements X509TrustManager {/ / check client certificate public void checkClientTrusted (X509Certificate [] chain, String authType) throws CertificateException {} / / check server-side certificate public void checkServerTrusted (X509Certificate [] certificate String authType) throws CertificateException {} / / returns an array of trusted X509 certificates public X509Certificate [] getAcceptedIssuers () {return null }}

Encapsulates a public class:

Package com.souvc.weixin.util;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.ConnectException;import java.net.URL;import javax.net.ssl.HttpsURLConnection;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSocketFactory;import javax.net.ssl.TrustManager;import net.sf.json.JSONException;import net.sf.json.JSONObject;import org.slf4j.Logger;import org.slf4j.LoggerFactory Import com.souvc.weixin.pojo.Token;/*** class name: CommonUtil * description: general tool class * developer: souvc * creation time: 2015-11-27 * release: V1.0 * / public class CommonUtil {private static Logger log = LoggerFactory.getLogger (CommonUtil.class) / / credential acquisition (GET) public final static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; / * send https request * * @ param requestUrl request address * @ data submitted by param requestMethod request method (GET, POST) * @ param outputStr * @ return JSONObject (get the property value of json object by JSONObject.get (key)) * / public static JSONObject httpsRequest (String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null Try {/ / create the SSLContext object and initialize TrustManager [] tm = {new MyX509TrustManager ()} with the trust manager we specified; SSLContext sslContext = SSLContext.getInstance ("SSL", "SunJSSE"); sslContext.init (null, tm, new java.security.SecureRandom ()); / / get the SSLSocketFactory object SSLSocketFactory ssf = sslContext.getSocketFactory (); URL url = new URL (requestUrl) from the above SSLContext object HttpsURLConnection conn = (HttpsURLConnection) url.openConnection (); conn.setSSLSocketFactory (ssf); conn.setDoOutput (true); conn.setDoInput (true); conn.setUseCaches (false); / / set request method (GET/POST) conn.setRequestMethod (requestMethod); / / write data if (null! = outputStr) {OutputStream outputStream = conn.getOutputStream () to the output stream when outputStr is not null / / Note the encoding format outputStream.write (outputStr.getBytes ("UTF-8")); outputStream.close ();} / / read the returned content from the input stream InputStream inputStream = conn.getInputStream (); InputStreamReader inputStreamReader = new InputStreamReader (inputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader (inputStreamReader); String str = null; StringBuffer buffer = new StringBuffer () While ((str = bufferedReader.readLine ())! = null) {buffer.append (str);} / / release resource bufferedReader.close (); inputStreamReader.close (); inputStream.close (); inputStream = null; conn.disconnect (); jsonObject = JSONObject.fromObject (buffer.toString ()) } catch (ConnectException ce) {log.error ("connection timeout: {}", ce);} catch (Exception e) {log.error ("https request exception: {}", e);} return jsonObject } / * obtain API access credential * * @ param appid credential * @ param appsecret key * @ return * / public static Token getToken (String appid, String appsecret) {Token token = null; String requestUrl = token_url.replace ("APPID", appid) .replace ("APPSECRET", appsecret); / / initiate GET request to obtain credential JSONObject jsonObject = httpsRequest (requestUrl, "GET", null) If (null! = jsonObject) {try {token = new Token (); token.setAccessToken (jsonObject.getString ("access_token")); token.setExpiresIn (jsonObject.getInt ("expires_in"));} catch (JSONException e) {token = null / / get token failed log.error ("get token failed errcode: {} errmsg: {}", jsonObject.getInt ("errcode"), jsonObject.getString ("errmsg"));}} return token;} / * URL coding (utf-8) * * @ param source * @ return * / public static String urlEncodeUTF8 (String source) {String result = source Try {result = java.net.URLEncoder.encode (source, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace ();} return result;} / * * determine the file extension by content type * * @ param contentType content type * @ return * / public static String getFileExt (String contentType) {String fileExt = "" If ("image/jpeg" .equals (contentType)) fileExt = ".jpg"; else if ("audio/mpeg" .equals (contentType)) fileExt = ".mp3"; else if ("audio/amr" .equals (contentType)) fileExt = ".amr"; else if ("video/mp4" .equals (contentType)) fileExt = ".mp4"; else if ("video/mpeg4" .equals (contentType) fileExt = ".mp4" Return fileExt;}}

How to get the basic information of the user:

/ * * obtain user information * * @ param accessToken API access credential * @ param openId user ID * @ return WeixinUserInfo * / public static WeixinUserInfo getUserInfo (String accessToken, String openId) {WeixinUserInfo weixinUserInfo = null; / / splicing request address String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID";" RequestUrl = requestUrl.replace ("ACCESS_TOKEN", accessToken) .replace ("OPENID", openId); / / get user information JSONObject jsonObject = CommonUtil.httpsRequest (requestUrl, "GET", null); if (null! = jsonObject) {try {weixinUserInfo = new WeixinUserInfo (); / / user's identity weixinUserInfo.setOpenId (jsonObject.getString ("openid")) / / follow status (1: follow, 0: no follow), weixinUserInfo.setSubscribe (jsonObject.getInt ("subscribe")) when not followed; / / weixinUserInfo.setSubscribeTime (jsonObject.getString ("subscribe_time")); / / nickname weixinUserInfo.setNickname (jsonObject.getString ("nickname")) / / user's gender (1 is male, 2 is female, 0 is unknown) weixinUserInfo.setSex (jsonObject.getInt ("sex")); / / user's country weixinUserInfo.setCountry (jsonObject.getString ("country")); / / user's province weixinUserInfo.setProvince (jsonObject.getString ("province")) / / user's city weixinUserInfo.setCity (jsonObject.getString ("city")); / / user's language, simplified Chinese is zh_CN weixinUserInfo.setLanguage (jsonObject.getString ("language")); / / user avatar weixinUserInfo.setHeadImgUrl (jsonObject.getString ("headimgurl")) } catch (Exception e) {if (0 = = weixinUserInfo.getSubscribe ()) {log.error ("user {} unfollowed", weixinUserInfo.getOpenId ());} else {int errorCode = jsonObject.getInt ("errcode"); String errorMsg = jsonObject.getString ("errmsg"); log.error ("failed to get user information errcode: {} errmsg: {}", errorCode, errorMsg) } return weixinUserInfo;}

Test method: note to replace the following with your own appid and secret key.

Public static void main (String args []) {/ / get the API access credential String accessToken = CommonUtil.getToken ("xxxx", "xxxx"). GetAccessToken (); / * * obtain user information * / WeixinUserInfo user = getUserInfo (accessToken, "ooK-yuJvd9gEegH6nRIen-gnLrVw"); System.out.println ("OpenID:" + user.getOpenId ()); System.out.println ("follow status:" + user.getSubscribe ()) System.out.println ("follow time:" + user.getSubscribeTime ()); System.out.println ("nickname:" + user.getNickname ()); System.out.println ("gender:" + user.getSex ()); System.out.println ("country:" + user.getCountry ()); System.out.println ("Province:" + user.getProvince ()); System.out.println ("City:" + user.getCity ()) System.out.println ("language:" + user.getLanguage ()); System.out.println ("avatar:" + user.getHeadImgUrl ());} Thank you for reading this article carefully. I hope the article "how to use .net to get ACCESSTOKEN in the development of Wechat public platform" shared by the editor will be helpful to you. At the same time, I also hope you can support me, pay attention to the industry information channel, and more related knowledge is waiting for you to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report