1.获取token
public String getToken(){
try {
HttpClient client = HttpClients.createDefault();
String tokenUrl = MessageFormat.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", APP_ID, APP_SECRET);
HttpGet request = new HttpGet(tokenUrl);
HttpResponse response = client.execute(request);
JSonObject object = getResponseJson(response);
if (object == null) {
return null;
}
return ObjectUtils.isEmpty(object) ? null : object.getString("access_token");
}catch (Exception e){ log.info(e.getMessage()); }
return null;
}
2.获取用户openId
// code前端传;type:1.公众号 2.小程序
public UserOpenIdDto getUserOpenId(String code,Integer type ) {
String resultStr;
UserOpenIdDto userOpenIdDto = new UserOpenIdDto();
try {
if(OpenIdTypeEnum.TYPE_PUBLIC.getCode().equals(type)){
//公众号发送请求
resultStr = wxUtils.executeHttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", publicappid, publicSecret, code);
}else {
//小程序发送请求
resultStr = wxUtils.executeHttpGet("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", uappid, uSecret, code);
}
//解析响应
JSonObject jsonObject = JSONObject.parseObject(resultStr);
if (ObjectUtils.isEmpty(jsonObject)){
throw new CommonException(ErrorCodeEnum.LOGIN_GET_THIRD_PARTY_USER_INFO_FAIL);
}
userOpenIdDto.setOpenId(jsonObject.getString("openid"));
userOpenIdDto.setUnionId(jsonObject.getString("unionid"));
} catch (IOException e) {
throw new CommonException(ErrorCodeEnum.LOGIN_GET_THIRD_PARTY_USER_INFO_FAIL);
}
return userOpenIdDto;
}
2-1 执行get url
public String executeHttpGet(String url,String appId,String secret,String code) throws IOException {
String formatUrl = MessageFormat.format(url,appId,secret,code);
HttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(formatUrl);
HttpResponse response = client.execute(request);
return readResponse(response);
}
3.查询用户是否关注了公众号
public boolean userIsFollowPublic(String token,String openid){
Integer subscribe = 0;
String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";
url = MessageFormat.format(url,token,openid);
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSonObject demoJson = JSONObject.parseObject(message);
subscribe = demoJson.getIntValue("subscribe"); // 此字段为关注字段 关注为1 未关注为0
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return 1 == subscribe;
}



