直接步入正题
先获取小程序code后端解析
Java代码
/*
* appid,appSecret 微信小程公众号拿取
* code 小程序传入的code
* 切记 一个code只能使用一次,使用后在到小程序刷新code
*/
public static JSONObject getOpenIdToolXcx(String appId, String code, String appSecret){
String url = "https://api.weixin.qq.com/sns/jscode2session?appId="+appId+"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
String result = HttpUtil.sendGet(url);
return JSONObject.parseObject(result);
// openId = jsonObject.getString("openid");// 用户唯一标识 这样就可以拿到openid
}
/**
* 发送HttpGet请求
* @param url
* @return
*/
public static String sendGet(String url) {
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = null;
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(10000).setSocketTimeout(10000).build();
httpget.setConfig(requestConfig);
try {
response = httpclient.execute(httpget);
} catch (Exception e1) {
response = null;
e1.printStackTrace();
}
String result = null;
try {
if(response != null)
{
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
}
}
} catch (Exception e) {
result = null;
e.printStackTrace();
} finally {
try {
if(response != null)
{
response.close();
}
} catch (Exception e) {
response = null;
e.printStackTrace();
}
}
if(response == null || response.getStatusLine().getStatusCode() != HttpStatus.SC_OK){
return null;
}
return result;
}
公众号解析code路径
public static JSONObject getOpenIdTool(String appId,String code,String appSecret){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId+"&secret="+appSecret+"&code="+code+"&grant_type=authorization_code";
String result =HttpUtil.sendGet(url);
return JSON.parseObject(result);
}