After the follower interacts with the official account, the official account can obtain the following's OpenID (the encrypted WeChat account, each user's OpenID for each official account is unique. For different official accounts, the same user's openid is different).
The official account can obtain basic user information based on OpenID through this interface, including nickname, avatar, gender, city, language and time of follow-up.
Developers can obtain basic user information through OpenID. Please use the https protocol.
We can take a look at the official documentation: obtaining basic information about users.
Interface call request description
http request method: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
Parameter description
| parameter | Is it necessary | illustrate |
|---|---|---|
| access_token | yes | Call interface credentials |
| openid | yes | The identity of an ordinary user is unique to the current official account |
| lang | no | Return to the country and regional language version, zh_CN Simplified Chinese, zh_TW Traditional Chinese, en English |
Return to the description
Under normal circumstances, WeChat will return the following JSON packet to the official account:
{ "subscribe": 1, "openid": "o6_bmjrPTlm6_2sgVt7hMZOPfL2M", "nickname": "Band", "sex": 1, "language": "zh_CN", "city": "Guangzhou", "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 | illustrate |
|---|---|
| subscribe | Whether the user subscribes to the official account ID? If the value is 0, it means that the user has not followed the official account and cannot pull the remaining information. |
| openid | User ID, unique to the current official account |
| nickname | User's nickname |
| sex | The gender of the user, when the value is 1, it is male, when the value is 2, it is female, and when the value is 0, it is unknown |
| city | The user's city |
| country | User country |
| province | The province where the user is located |
| language | The user's language, simplified Chinese is zh_CN |
| headimgurl | The user's avatar, the last value represents the size of the square avatar (there are 0, 46, 64, 96, and 132 values are optional, and 0 represents 640*640 square avatar). This item is empty when the user has no avatar. If the user changes the avatar, the original avatar URL will be invalid. |
| subscribe_time | The user focuses on time, as a timestamp. If the user has followed it many times, then the last time to follow |
| unionid | This field will only appear after the user binds the official account to the WeChat open platform account. See: Obtaining user personal information (UnionID mechanism) |
| Remark | Official account operators’ notes to fans. Official account operators can add notes to fans in the WeChat public platform user management interface. |
| groupid | The group ID of the user |
When error occurs, WeChat will return error codes and other information. The 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 </br>* Description: Basic information of WeChat users</br>* Developer: souvc </br>* Creation time: 2015-11-27 </br>* Release version: V1.0 </br> */public class WeixinUserInfo { // User ID private String openId; // Follow status (1 is following, 0 is not following), no remaining information can be obtained when not following private int subscribe; // User follow time, a timestamp. If the user has followed many times, take the last time to follow private String subscribeTime; // Nickname private String nickname; // User's gender (1 is male, 2 is female, 0 is unknown) private int sex; // User's country private String country; // User's province private String province; // User's city private String city; // User's language, simplified Chinese: zh_CN private String language; // User's avatar 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 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 required to obtain the user's basic information.
package com.souvc.weixin.pojo;/*** Class name: Token </br>* Description: Credentials</br>* Developer: souvc </br>* Creation time: 2015-11-27 </br>* Release version: V1.0 </br> */public class Token { // Interface access credentials private String accessToken; // Credential validity period, unit: 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, trust manager required
package com.souvc.weixin.util;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import javax.net.ssl.X509TrustManager;/*** Class name: MyX509TrustManager </br>* Description: Trust Manager</br>* Developer: souvc </br>* Creation time: 2015-11-27 </br>* Release version: V1.0 </br> */public class MyX509TrustManager implements X509TrustManager { // Check the client certificate public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // Check the server certificate public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } // Return the trusted X509Certificate[] getAcceptedIssuers() { return null; }} Encapsulated 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 </br>* Description: General Tools Class</br>* Developer: souvc </br>* Creation time: 2015-11-27 </br>* Release version: V1.0 </br> */public class CommonUtil { private static Logger log = LoggerFactory.getLogger(CommonUtil.class); // Credential Obtainment (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* @param requestMethod Request Method (GET, POST) * @param outputStr The data submitted * @return JSONObject(get the attribute value of the json object through JSONObject.get(key)) */ public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) { JSONObject jsonObject = null; try { // Create SSLContext object and initialize TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // Get the SSLSocketFactory object from the above SSLContext object SSLSocketFactory ssf = sslContext.getSocketFactory(); URL url = new URL(requestUrl); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); // Set the request method (GET/POST) conn.setRequestMethod(requestMethod); // Write data to the output stream if (null != outputStream) { OutputStream outputStream = conn.getOutputStream(); // Pay attention to the encoding format outputStream.write(outputStr.getBytes("UTF-8")); outputStream.close(); } //Return 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 the resource bufferedReader.close(); inputStreamReader.close(); inputStream.close(); inputStream = null; conn.disconnect(); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error("Connect timeout: {}", ce); } catch (Exception e) { log.error("https request exception: {}", e); } return jsonObject; } /** * Get interface access credentials* * @param appid credentials* @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 a GET request to get credentials 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; // Failed to get token log.error("failed to get token errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg")); } } return token; } /** * URL encoding (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 file extension based on 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 obtain basic user information:
/** * Get user information* * @param accessToken interface access credentials* @param openId User ID* @return WeixinUserInfo */ public static WeixinUserInfo getUserInfo(String accessToken, String openId) { WeixinUserInfo weixinUserInfo = null; // Splice 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 ID weixinUserInfo.setOpenId(jsonObject.getString("openid")); // Follow status (1 is following, 0 is not following), no remaining information can be obtained when not following weixinUserInfo.setSubscribe(jsonObject.getInt("subscribe")); // User attention time weixinUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time")); // Nickname weixinUserInfo.setNickname(jsonObject.getString("nickname")); // User gender (1 is male, 2 is female, 0 is unknown) weixinUserInfo.setSex(jsonObject.getInt("sex")); // The user's country weixinUserInfo.setCountry(jsonObject.getString("country")); // The user's province weixinUserInfo.setProvince(jsonObject.getString("province")); // The user's city weixinUserInfo.setCity(jsonObject.getString("city")); // The 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{}Unsong", weixinUserInfo.getOpenId()); } else { int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); log.error("Failed to obtain user information errcode:{} errmsg:{}", errorCode, errorMsg); } } } return weixinUserInfo; }Test method: Pay attention to replace the following with your appid and secret key.
public static void main(String args[]) { // Get interface access credentials String accessToken = CommonUtil.getToken("xxxx", "xxxx").getAccessToken(); /** * Get 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()); }The effects are as follows:
OpenID: ooK-yuJvd9gEegH6nRIen-gnLrVw
Status of attention: 1
Follow time: 1449021142
Nickname: Feng Shao Gender: 1
Country: China Province: Guangdong City: Guangzhou Language: zh_CN
Avatar: http://wx.qlogo.cn/mmopen/lOZIEvyfCa7aZQ7CkiamdpQicUDnGDEC0nzb7ZALjdl3TzFVFEHWM1AFqEXnicNIDeh0IQYTt0NrIP06ibg4W5WflASfFfX9qqib0/0
The above content introduces the basic information of users in the development of WeChat public platform for the actual Java version of WeChat. I hope that this article sharing will be helpful to your future work and study. At the same time, thank you for your continued support for the Wulin Network website.