网页获取用户信息文档说明
进入微信公众平台,接口权限—>网页服务—>网页授权—->修改—>网页授权域名设置,填写你想要的域名,并按照说明下载txt文件放到对应的域名下,接下来开始码代码
public static String codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="
+ 你的appid
+ "&redirect_uri="
+ URLEncoder.encode("你想跳转到的地址")
+ "&response_type=code&scope="
+ scope
+ "&state="+state+"#wechat_redirect";
把上面的那个字符串写成二维码就可以了,我博客有相关二维码的代码,这里就不赘述了,下面这段是上面那个跳转的网页里面的代码,获取openID和用户信息的
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取微信返回的code
String code = request.getParameter("code");
System.out.println("code: "+code);
String access_token = "appid="
+ 你的appid
+ "&secret="
+ 你的appid对应的secret
+ "&code="+code+"&grant_type=authorization_code";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
// 这段是发送get请求并获取返回结果,你可以找个get请求替换掉就行
//我用的jsonlib的jar包
String getopenid = HttpRequest.sendGet("https://api.weixin.qq.com/sns/oauth2/access_token", access_token);
System.out.println("--------------------------获取openID时间 [ "+df.format(new Date())+" ] --------------------------");
System.out.println("access_token 返回:"+getopenid);
JSONObject fromObject = JSONObject.fromObject(getopenid);
System.out.println("fromObject : "+fromObject);
boolean containsKey = fromObject.containsKey("openid");
if (!containsKey) {
System.out.println("======获取openID失败!!");
}
else {
String openid = fromObject.getString("openid");
System.out.println("获取的openID "+openid);
//-------------------------------------------------------
// 获取用户信息
// https://api.weixin.qq.com/cgi-bin/user/info? //access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
String accesstoken = fromObject.getString("access_token");
String Unionid="access_token="+accesstoken+"&openid="+openid+"&lang=zh_CN";
System.out.println("-----------------用户信息=---------------------");
//get方法获取用户信息
String sendGet = HttpRequest.sendGet("https://api.weixin.qq.com/sns/userinfo", Unionid);
System.out.println("用户信息 : "+sendGet);
//自己解析下json串存数据库就OK了
}
}