第一天了解公众号,第二天写有关公众号的代码!有点挑战但不大!如果有更好的解决办法请告知!
一、授权获取code,要用静默的那种(&scope=snsapi_base) 注:此步骤要在前端做操作,要不然会发生错误!
二、通过code获取openid
三、根据appid和secret获取access_token
四、根据openid和access_token获取subscribe。注:subscribe的值1代表已关注、0代表未关注
开始:根据以上步骤完成操作
一、授权获取code,这个步骤我只是在html页面做的,url 是你重定向的地址,比如:我的这个是查询列表的
var code = '${code!}';
var url = "";
var urlquanxian = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=" + url +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=kcxw#wechat_redirect";
if (!code) {
window.location.href = urlquanxian;
} else {
mui.ajax("http://。。。/weixin/oauthss/wxcallback", {
data: {code: code},
dataType: "json",
success: function (data) {
if ("1"==data) {
pub();
} else {
}
}
})
}
二、2、3、4步骤在同一个方法里执行的,在这个Controller里还有个方法是传url返回json字符串的
@RequestMapping("/wxcallback")
@ResponseBody
public String wxcallback(String code) throws IOException {
//二、通过code获取openid
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
"&secret=" + APP_SECRET +
"&code=" + code +
"&grant_type=authorization_code";
JSONObject param = doGet(url);
String openid = param.getString("openid");
//三、获取access_token
String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APP_SECRET;
JSONObject paramt = doGet(tokenUrl);
String access_token = paramt.getString("access_token");
//四、判断是否关注
String url2 = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token +
"&openid=" + openid +
"&lang=zh_CN";
JSONObject jsonObject = doGet(url2);
String subscribe = jsonObject.getString("subscribe");
System.out.println("是否关注了: " + subscribe);
return jsonObject.getString("subscribe");
}
//返回JSON字符串
public static JSONObject doGet(String url) throws IOException {
JSONObject jsonObject = null;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSONObject.parseObject(result);
}
httpGet.releaseConnection();
return jsonObject;
}