由前端调用后端来获取用户授权的微信路径,打开后台的返回的url,然后根据用户的是否允许来回调后台获取用户的基本参数
-
前台代码 // 用户进行授权 this.$http({ method: 'get', url: config.url.list + '/customerInfo/customerLogin', params: {companyId: companyId}, responseType: 'json' // 响应格式 }).then(res => { if(res.data.body){ window.location.replace(res.data.body) } })
-
后台代码 public String customerLogin()( urls="http://phys.natapp1.cc";//当前的域名且在微信公众号中配置过 String REDIRECT_URI = urls + "/customerInfo/getOpenId";//getOpenId 回调的地址 String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ WeixinConstants.APPID+"&redirect_uri="+ URLEncoder.encode(redirectUrl, "UTF-8")+"&response_type=code&scope=snsapi_userinfo#wechat_redirect";//cope=snsapi_userinfo 非静默授权 return url; }
- 授权回调方法
public void getOpenId(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 获取微信授权端返回的code
String code = request.getParameter("code");
Map openId = getOpenIdInfo(code);
String openId1 = (String) openId.get("openid");//用户的openId
//[设置响应码为302,表示重定向]
response.setStatus(302);
indexUrl="http://192.168.1.113:8089/#/index";
response.setHeader("Location", a);//设置新请求的URL,回到前端授权页面
}
/**
*
* 获取用户code 的回调方法,会把code信息返回在此方法中
* 静默授权回调,只获取openId就可以了
*
*/
@Anonymous
@RequestMapping(value = "/getOpenIdInfo")
public Map getOpenIdInfo(String code) throws IOException {
Map map=new HashMap();
//通过code换取网页授权access_token
String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+WeixinConstants.APPID+"&secret="+WeixinConstants.APPSECRET+"&code="+code+"&grant_type=authorization_code";
JSONObject json = httpRequestUtil.httpsRequest(url, "GET", null);
System.out.println(json);
if (null != json) {
try{
String accessToken=json.get("access_token").toString();
String refreshToken=json.get("refresh_token").toString();
String openid=json.get("openid").toString();
String scope=json.get("scope").toString();
map.put("access_token",accessToken);
map.put("refresh_token",refreshToken);
map.put("openid",openid);
//拉取用户信息(需scope为 snsapi_userinfo)
String url2="https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
net.sf.json.JSONObject json2 = httpRequestUtil.httpsRequest(url2, "GET", null);//用户的基本信息
map.put("nickname",json2.getString("nickname"));
map.put("headimgurl",json2.getString("headimgurl"));
System.out.println(json2);
}catch (Exception e){
e.printStackTrace();
}
}
return map;
}