String url = "https://open.weixin.qq.com/connect/oauth2/authorize"
+ "?appid=APPID"
+ "&redirect_uri=REDIRECT_URI"
+ "&response_type=code"
+ "&scope=snsapi_base"
+ "&state=STATE"
+ "#wechat_redirect";
String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
+ "?appid=AppId"
+ "&secret=AppSecret"
+ "&code=CODE"
+ "&grant_type=authorization_code";
@GetMapping("/getCode")
public void getCode(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException {
String url = WxUtils.getOpenIdUrl("xiaoming");
System.out.println("微信网址:"+url);
response.sendRedirect(url);
}
@GetMapping("/getOpenId")
public Map getOpenId(HttpServletRequest request, HttpServletResponse response) throws ClientProtocolException, IOException {
Map map = new HashMap();
String code = request.getParameter("code");//微信会返回code值,用code获取openid
String openId = WxUtils.getOpendId(code);
map.put("openId", openId);
return map;}
public static String getopendid(String code) throws ParseException, IOException {
String appid = "xxx";
String secret = "xxx";
String url = "https://api.weixin.qq.com/sns/oauth2/access_token"
+ "?appid=AppId"
+ "&secret=AppSecret"
+ "&code=CODE"
+ "&grant_type=authorization_code";
url = url.replace("AppId", appid)
.replace("AppSecret", secret)
.replace("CODE", code);
HttpGet get = HttpClientConnectionManager.getGetMethod(url);
HttpResponse response = httpclient.execute(get);
String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
JSONObject jsonTexts = (JSONObject) JSON.parse(jsonStr);
String openid = "";
if (jsonTexts.get("openid")!=null) {
openid = jsonTexts.get("openid").toString();
}
return openid;
}