1. 程式人生 > >java 獲取微信使用者基本資訊

java 獲取微信使用者基本資訊

功能描述:需要獲取公眾號下openId對應的使用者基本資訊;

實現思路:通過網頁授權獲取到code  用code 換取openid 和access_token  用openid和access_token獲取使用者基本資訊;

第一步:獲取code
呼叫微信獲取code介面  
介面地址:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb82f22f6b7011d4e&redirect_uri=http%3a%2f%2fds.tunnel.echomod.cn%2fDentalinkServiceWeb%2fuser%2fwechatCheck&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect
appid: 在公眾號內可以檢視。
redirect_uri:外網能訪問的專案地址要具體到方法  也就是說接收code的方法。
其他引數預設就好.
第二步:獲取openid和access_token
首先接收code: 
程式碼如下:
@RequestMapping("/wechatCheck")
@ResponseBody
public ModelAndView wechatCheck(@RequestParam(value = "code", required = true) String code,
HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
ModelAndView model = new ModelAndView();
try {
String openId = ""; //微信openId
String accessToken = "";//微信access_token
 openId = (String) request.getSession().getAttribute(SessionConstants.OPENID_SESSION_ID);
 accessToken = (String) request.getSession().getAttribute(SessionConstants.ACCESSTOKEN_SESSION_ID);
if (openId == null || "".equals(openId)) {
// 獲取openId
try {
JSONObjectsrc = WechatTools.queryOpenId(code); //呼叫微信介面
openId = src.getString("openid");//微信openId
accessToken = src.getString("access_token");//微信access_token
System.out.println(src);
} catch (Exception e) {
e.printStackTrace();
logger.error("獲取openId錯誤========================"+e.getMessage()+"========================");
}
}
工具類方法 
url地址是獲取openid和access_token介面地址
地址:https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxb82f22f6b7011d4e&secret=be373618314eec41a2c65567c44764ee&grant_type=authorization_code
appid: 在公眾號內可以檢視。
secret:是你APPID金鑰 在公眾號內檢視
public class WechatTools {
private static Logger logger = Logger.getLogger(WechatTools.class);

public static JSONObject queryOpenId(String code) throws Exception {
//String openId = "";
String url = (String)PropertiesHandler.getConfigValue("wechat.openid.url").toString();
if (url == null || "".equals(url)) {
throw new RecruitException(ErrorsInfo.SYS_ERROR, "系統異常,缺少openId URL配置", "系統異常");
}
String params = "&code=" + code;
url = url + params;
JSONObject json = HttpClientTools.doGet(url);
logger.error("微信返回========================" + json + "==========================");
logger.error("微信返回========================" + json + "==========================");
logger.error("微信返回========================" + json + "==========================");
/*if (json != null) {
openId = json.getString("openid");
if (openId == null) {
throw new RecruitException(ErrorsInfo.ERR00003, "微信錯誤,獲取不到openId", "微信錯誤");
}
}
String src = json.toString();*/
return json;
}
doget方法
/**
 * Http Client 自定義工具類
 * @author kail.huang
 */
public class HttpClientTools {


private static Logger logger = Logger.getLogger(HttpClientTools.class);


/**
 * Http Get 請求方法
 * @param url
 * @return
 * @throws Exception
 */
public static JSONObject doGet(String url) throws Exception {


JSONObject json = null;
HttpGet httpGet = new HttpGet(url);
// 建立httpClientBuilder
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// httpclient
CloseableHttpClient httpClient = clientBuilder.build();


try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
json = JSONObject.fromObject(result);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new RecruitException(ErrorsInfo.ERR00001, "HttpClient 請求異常", "HttpClient 請求異常,請檢查日誌!");
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new RecruitException(ErrorsInfo.ERR00002, "IO 讀取異常", "IO 讀取異常,請檢查日誌!");
}


return json;
}
第三步:獲取微信個人資訊
通過openid和access_token獲取微信個人資訊
url:https://api.weixin.qq.com/sns/userinfo?
程式碼如下:
/**wechat.userInfo.url
 *  獲取微信使用者個人資訊
 * @param openId
 * @param userId 
 * @return
 */
public static SnsUserinfoVO snsUserinfoVO(String openId,String accessToken, long userId) throws Exception{
SnsUserinfoVO snsUserInfo = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//設定日期格式
String url = (String)PropertiesHandler.getConfigValue("wechat.userInfo.url").toString();
if (url == null || "".equals(url)) {
throw new RecruitException(ErrorsInfo.SYS_ERROR, "系統異常,缺少獲取微信userInfo URL配置", "系統異常");
}
String params = "access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
url = url + params;
logger.error("呼叫介面url========================" + url + "==========================");
JSONObject jsonObject = HttpClientTools.doGet(url);
logger.error("呼叫介面獲取微信使用者個人資訊 微信返回引數========================" + jsonObject + "==========================");
 snsUserInfo = new SnsUserinfoVO();
         // 使用者的標識
         snsUserInfo.setOpenId(jsonObject.getString("openid"));
         // 暱稱
         snsUserInfo.setNickName(jsonObject.getString("nickname"));
         // 性別(1是男性,2是女性,0是未知)
         snsUserInfo.setSex(jsonObject.getInt("sex"));
         // 使用者所在國家
         snsUserInfo.setCountry(jsonObject.getString("country"));
         // 使用者所在省份
         snsUserInfo.setProvince(jsonObject.getString("province"));
         // 使用者所在城市
         snsUserInfo.setCity(jsonObject.getString("city"));
         // 使用者頭像
         snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));   
         //提交時間
         snsUserInfo.setInputTime(df.format(new Date()));
         //修改時間 
         snsUserInfo.setModifyTime(df.format(new Date()));
         //提交者
         snsUserInfo.setInputBy(userId);
         //修改者
         snsUserInfo.setModifyBy(userId);
         //狀態
         snsUserInfo.setStatus(1);
return snsUserInfo;
}
到這裡就能成功獲取使用者個人資訊了 如下資訊
{"openid":"oMEfB0d5-CpkKLsWIp3Yvmk-Wp5E","nickname":"卓力","sex":1,"language":"zh_CN","city":"河源","province":"廣東","country":"中國","headimgurl":"http://wx.qlogo.cn/mmopen/Q3auHgzwzM4v340hdqKAkhkTG2SJjjBpE8MR2eNEUSbGzn2r3yAbibQxib6eiaXicYXA08ZkIiajiaWibohY5GiaMqZ4eZNmcgR07TdPXUGhqDMgkgU/0","privilege":[]}