java 获取微信用户基本信息

17 篇文章 2 订阅
7 篇文章 0 订阅

功能描述:需要获取公众号下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 {
					JSONObject	src = 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":[]}
 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zengsange

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值