微信授权api:https://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
login页面:
$("#wx").on("click",function(){
var url = "http://xm.ysyisu.cn/wxlogin";
var json = "{%22lon%22:"+lon+",%22lat%22:"+lat+"}";
var str = "https://open.weixin.qq.com/connect/oauth2/authorize?"+
"appid=wx87019669d6f33b43&"+
"redirect_uri="+encodeURI(url)+"&"+
"response_type=code&"+
"scope=snsapi_userinfo&"+
"state="+json+
"#wechat_redirect";
window.location.href=str;
});
通过code 获取access_token
/**
* 获取请求用户信息的access_token
*
* @param code
* @return
*/
public static Map<String, String> getUserInfoAccessToken(String code) {
JsonObject object = null;
Map<String, String> data = new HashMap<String, String>();
try {
String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
"wx87019669d6f33b43", "591913436493c1c71b9a5cd90232c5dc", code);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String tokens = EntityUtils.toString(httpEntity, "utf-8");
//Gson token_gson = new Gson();
//object = token_gson.fromJson(tokens, JsonObject.class);
JSONObject result = new JSONObject(tokens); //Convert String to JSON Object
data.put("openid", result.get("openid").toString().replaceAll("\"", ""));
data.put("access_token", result.get("access_token").toString().replaceAll("\"", ""));
} catch (Exception ex) {
}
return data;
}
/**
* 获取用户信息
*
* @param accessToken
* @param openId
* @return
*/
public static Map<String, String> getUserInfo(String accessToken, String openId) {
Map<String, String> data = new HashMap();
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
JsonObject userInfo = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity, "utf-8");
//Gson token_gson = new Gson();
//userInfo = token_gson.fromJson(response, JsonObject.class);
JSONObject result = new JSONObject(response); //Convert String to JSON Object
data.put("openid", result.get("openid").toString().replaceAll("\"", ""));
data.put("nickname", result.get("nickname").toString().replaceAll("\"", ""));
data.put("city", result.get("city").toString().replaceAll("\"", ""));
data.put("province", result.get("province").toString().replaceAll("\"", ""));
data.put("country", result.get("country").toString().replaceAll("\"", ""));
data.put("headimgurl", result.get("headimgurl").toString().replaceAll("\"", ""));
} catch (Exception ex) {
}
return data;
}