获取用户基本信息(包括UnionID机制)
开发者可通过OpenID来获取用户基本信息。请使用https协议。
接口调用请求说明
http请求方式: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
参数说明
参数 | 是否必须 | 说明 |
---|---|---|
access_token | 是 | 调用接口凭证 |
openid | 是 | 普通用户的标识,对当前公众号唯一 |
lang | 否 | 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语 |
所以首先需要拿到access_token才能来调用接口。
获取access_token
接口调用请求说明
https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
参数说明
参数 | 是否必须 | 说明 |
---|---|---|
grant_type | 是 | 获取access_token填写client_credential |
appid | 是 | 第三方用户唯一凭证 |
secret | 是 | 第三方用户唯一凭证密钥,即appsecret |
Map params = new HashMap();
params.put("appid", xxx);
params.put("secret", xxx);
params.put("grant_type", "client_credential");
result = HttpGetUtil.httpRequestToString("https://api.weixin.qq.com/cgi-bin/token", params);
JSONObject jsonObject = JSONObject.fromObject(result);
access_token = jsonObject.get("access_token").toString();
拿到access_token后再去调用获取用户信息的接口
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
Map params = new HashMap(); params.put("access_token",access_token);
params.put("lang","zh_CN");
params.put("openid",xxx);
result = HttpGetUtil.httpRequestToString("https://api.weixin.qq.com/cgi-bin/user/info", params);
jsonObject = JSONObject.fromObject(result);
String subscribe = jsonObject.get("subscribe").toString();
注意:当subscribe为0时,说明用户未关注公众号,拉取不到其他信息。
HttpGetUtil.java
public class HttpGetUtil {
public static String httpRequestToString(String url,
Map params) {
String result = null;
try {
InputStream is = httpRequestToStream(url, params);
BufferedReader in = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = in.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
} catch (Exception e) {
return null;
}
return result;
}
private static InputStream httpRequestToStream(String url,
Map params) {
InputStream is = null;
try {
String parameters = "";
boolean hasParams = false;
for(String key : params.keySet()){
String value = URLEncoder.encode(params.get(key), "UTF-8");
parameters += key +"="+ value +"&";
hasParams = true;
}
if(hasParams){
parameters = parameters.substring(0, parameters.length()-1);
}
url += "?"+ parameters;
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setDoInput(true);
//设置请求方式,默认为GET
conn.setRequestMethod("GET");
is = conn.getInputStream();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}