網頁獲取用戶信息文檔說明
進入微信公衆平臺,接口權限—>網頁服務—>網頁授權—->修改—>網頁授權域名設置,填寫你想要的域名,並按照說明下載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了
}
}