微信获取用户信息的方式有两种,静默授权(无需用户同意)和非静默授权(需要用户“ 手动点击 ”拉取授权,可以用户无需关注公众号即可获取用户信息)
整体的代码请查看最后,前边为原理介绍
首先将appid发送到指定连接,设置redirecturi回调地址
//静默授权,只获取openid snsapi_base; 非静默授权, 获取用户详细信息 snsapi_userinfo
String scope = "snsapi_userinfo";//非静默授权
String redirect_uri = "http://LILUO/GetUserInfoAccredit";//自己的回调地址
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+自己的appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope="+scope+"#wechat_redirect";
//设置用户点击跳转地址为url,必须为用户主动点击跳转才行
微信服务器接收到请求后将含有code信息的内容添加在回调地址中并访问该回调地址,用户后台接收到访问请求后处理code,将code发送到指定的微信链接地址,拿code去换取access_token和用户openid
String code = req.getParameter("code");
//换取access_token地址
String url = " https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";//指定微信链接地址
String result = getAndPost.get(url);//发送get请求,换取access_token和用户openid
JSONObject json = JSONObject.fromObject(result);
//得到access_token
String tocken = json.getString("access_token");
//得到openid
String openid = json.getString("openid");
利用openid和access_token拼接到指定的url中发送给微信服务器,换取用户信息
//拉取用户基本信息,根据openid和access_token去换
String urlUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token="+tocken+"&openid="+openid+"&lang=zh_CN";//指定url
result = getAndPost.get(urlUserInfo);//发送到微信服务器
//System.out.println(result);
JSONObject jsObj = JSONObject.fromObject(result);//将返回的数据格式化为json数据
jsObj.get("name");//获取名字
jsObj.get("gender");//获取性别
将获取到的信息直接存入数据库即可
获取用户详细信息(整体流程)
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String appid = "fb";
String secret = "86";
//获取code
String code = req.getParameter("code");
//换取access_token地址
String url = " https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
String result = getAndPost.get(url);
JSONObject json = JSONObject.fromObject(result);
//得到access_token
String tocken = json.getString("access_token");
String openid = json.getString("openid");
//拉取用户基本信息
String urlUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token="+tocken+"&openid="+openid+"&lang=zh_CN";
result = getAndPost.get(urlUserInfo);
//System.out.println(result);
JSONObject jsObj = JSONObject.fromObject(result);
//获取详情
jsObj.get("name");
jsObj.get("gender");
}
//用户点击时地址凭借参数
String scope = "snsapi_userinfo";/只获取openid snsapi_base; 获取详细信息 snsapi_userinfo
String redirect_uri = "http:LILUO/GetUserInfoAccredit";
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+自己的appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope="+scope+"#wechat_redirect";
可以通过a标签让用户访问我们的地址
通过openid获取已关注用户的基本信息
/**
* 获取已经关注用户的基本信息
*/
public static String getUserInfo(String openid) {
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+微信公众号的accesstoken+"&openid="+该用户的openid+"&lang=zh_CN";
String resutl = getAndPost.get(url);//发送到微信服务器
return resutl;
}