This article describes how to obtain basic user information from the Java version of the public platform, for more information about how to obtain basic user information, see this article.
After the consumer and the public account generate a message interaction, the public account can obtain the OpenID of the consumer (encrypted number. each user has a unique OpenID for each public account. For different public accounts, the openid of the same user is different ).
The public account can use this http://www.php.cn/code/11829.html "target =" _ blank "> interface to obtain basic user information based on OpenID, including nicknames, portraits, gender, city, language, and focus time.
You can use OpenID to obtain basic user information. Use https protocol.
Let's take a look at the official document: get basic user information.
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
Parameters |
Required? |
Description |
Access_token |
Yes |
Interface call credential |
Openid |
Yes |
The identifier of a common user, which is unique to the current public account. |
Lang |
No |
Return to the Chinese language version, zh_CN simplified, zh_TW traditional, en English |
Return description
Normally, the following JSON data packet is returned to the public 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
Parameters |
Description |
Subscribe |
Whether the user subscribes to the public account ID. if the value is 0, the user does not pay attention to the public account and cannot obtain other information. |
Openid |
User ID, which is unique to the current public account |
Nickname |
User nickname |
Sex |
Gender of the user. if the value is 1, the user is male. if the value is 2, the user is female. if the value is 0, the user is unknown. |
City |
User's City |
Country |
Country of the user |
Province |
Province |
Language |
The user's language. the simplified Chinese name is zh_CN. |
Headimgurl |
User profile picture. the last value indicates the size of the square profile picture (optional values include 0, 46, 64, 96, and 132, and 0 indicates the size of the 640x640 square profile picture ), this item is blank when the user does not have an avatar. If you change the profile picture, the original profile picture URL becomes invalid. |
Subscribe_time |
The user's attention time, which is the timestamp. If the user has followed the last time |
Unionid |
This field appears only when you bind a public account to an open platform account. For details, see obtain user personal information (UnionID mechanism) |
Remark |
Comments from public account operators to fans. public account operators can add comments to fans in the user management field of the public platform. |
Groupid |
ID of the user's group |
When an error occurs, an error code or other information is returned. An example of a JSON data 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 basic user information.
Package com. souvc. weixin. pojo;/*** class name: WeixinUserInfo
* Description: basic user information.
* Developer: souvc
* Creation time:
* Release version: V1.0
*/Public class WeixinUserInfo {// User ID private String openId; // Follow status (1 is followed, 0 is not followed ), the remaining information cannot be obtained when you are not paying attention to it. private int subscribe; // The time when the user follows the message, which is the timestamp. If the user has been concerned for many times, take the last follow time private String subscribeTime; // nickname private String nickname; // the user's gender (1 is male, 2 is female, 0 is unknown) private int sex; // private String country of the country where the user is located; // private String province of the province where the user is located; // private String city of the city where the user is located; // user's language. the simplified Chinese name 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 take a look at the interface for getting 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 basic information of the user.
Package com. souvc. weixin. pojo;/*** class name: Token
* Description: credential.
* Developer: souvc
* Creation time:
* Release version: V1.0
*/Public class Token {// interface access credential private String accessToken; // credential validity period, unit: Second private int expiresIn; public String getAccessToken () {return accesresien ;} 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:
* Release version: V1.0
*/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 {} // returns the trusted X509 certificate array public X509Certificate [] getAcceptedIssuers () {return null ;}}
It 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: common tools.
* Developer: souvc
* Creation time:
* Release version: V1.0
*/Public class CommonUtil {private static Logger log = LoggerFactory. getLogger (CommonUtil. class); // GET the credential (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 data submitted * @ return JSONObject (through JSONObject. get (key) method to get the json object attribute value) */public static JSONObject httpsRequest (String requestUrl, String requestMethod, String outputStr) {JSONObject jsonObject = null; try {// Create an SSLContext object and use the trusted manager we specified to initialize TrustManager [] tm = {new MyX509TrustManager ()}; SSLContext SslContext = SSLContext. getInstance ("SSL", "SunJSSE"); sslContext. init (null, tm, new java. security. secureRandom (); // Obtain the SSLSocketFactory object SSLSocketFactory ssf = SSLContext from the sslContext object. getSocketFactory (); URL url URL = new url (requestUrl); HttpsURLConnection conn = (HttpsURLConnection) URL. openConnection (); conn. setSSLSocketFactory (ssf); conn. setDoOutput (true); conn. setDoInput (true); conn. setUse Caches (false); // Set the request method (GET/POST) conn. setRequestMethod (requestMethod); // when outputStr is NOT null, write data to the output stream if (null! = OutputStr) {OutputStream outputStream = conn. getOutputStream (); // 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 bu Ffer = new StringBuffer (); while (str = bufferedReader. readLine ())! = Null) {buffer. append (str);} // releases the 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 the interface 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 a GET request to obtain the 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 failure 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 the file extension ** @ param contentType content type ** @ return */public static String getFileExt (String contentType) based on the content type) {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 credential * @ param openId user id * @ return WeixinUserInfo */public static WeixinUserInfo getUserInfo (String accessToken, String openId) {WeixinUserInfo weixinUserInfo = null; // concatenate the 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 (); // weixinUserInfo. setOpenId (jsonObject. getString ("openid"); // follow State (1 is followed, 0 is not followed), other information cannot be obtained if not followed. setSubscribe (jsonObject. getInt ("subscribe"); // weixinUserInfo. setSubscribeTime (jsonObject. getString ("subscribe_time"); // nickname weixinUserInfo. setNickname (jsonObject. getString ("nickname"); // the user's gender (1 is male, 2 is female, 0 is unknown) weixinUserInfo. setSex (jsonObject. getInt ("sex"); // weixinUserInfo. setCountry (jsonObject. getString ("country"); // weixinUserInfo. setProvince (jsonObject. getString ("province"); // weixinUserInfo. setCity (jsonObject. getString ("city"); // the user's language. the simplified Chinese name is zh_CN weixinUserInfo. setLanguage (jsonObject. getString ("language"); // weixinUserInfo. setHeadImgUrl (jsonObject. getString ("headimgurl");} catch (Exception e) {if (0 = weixinUserInfo. getSubscribe () {log. error ("user {} has canceled follow", 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: replace the following with your own appid and key.
Public static void main (String args []) {// Obtain the interface access credential 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 effect is as follows:
OpenID: ooK-yuJvd9gEegH6nRIen-gnLrVw
Follow status: 1
Followed by: 1449021142
Nickname: less wind
Gender: 1
Country: China
Province: Guangdong
City: Guangzhou
Language: zh_CN
Profile Photo: http://wx.qlogo.cn/mmopen/lOZIEvyfCa7aZQ7CkiamdpQicUDnGDEC0nzb7ZALjdl3TzFVFEHWM1AFqEXnicNIDeh0IQYTt0NrIP06ibg4W5WflASfFfX9qqib0/0
The above is the detailed description of ACCESSTOKEN. Net for public platform development and the details of the instance. For more information, see other related articles on php Chinese network!