创建一个微信授权的工具类
public class WXAuthUtil {
public static final String APPID = "xxxxxxxxx"; //微信Appid
public static final String APPSECRET = "xxxxxxxx";//微信APPSECRET
private static final String TOKEN = "immco";
public static JSONObject doGetJson(String url) throws ClientProtocolException, IOException {
JSONObject jsonObject = null;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response =client.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
//把返回的结果转换为JSON对象
String result = EntityUtils.toString(entity, "UTF-8");
jsonObject = JSON.parseObject(result);
}
return jsonObject;
}
}
创建一个微信的Controller
@Controller
@RequestMapping("/api/Wx")
@CrossOrigin("*")
public class wwController extends BaseController {
@Autowired
private UserinfoService userinfoService;
private static Logger log = LoggerFactory.getLogger(WxController.class);
@RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
public String wxLogin(HttpServletRequest request,
HttpServletResponse response)
throws ParseException {
//这个url的域名必须要进行再公众号中进行注册验证,这个地址是成功后的回调地址
String backUrl = "http://qgjava.nat300.top/api/Wx/callBack";
// 第一步:用户同意授权,获取code
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WXAuthUtil.APPID
+ "&redirect_uri=" + URLEncoder.encode(backUrl)
+ "&response_type=code"
+ "&scope=snsapi_userinfo"
+ "&state=STATE#wechat_redirect";
log.info("forward重定向地址{" + url + "}");
//response.sendRedirect(url);
return "redirect:" + url;//必须重定向,否则不能成功
}
@RequestMapping(value = "/callBack", method = RequestMethod.GET)
public String callBack(ModelMap modelMap, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//start 获取微信用户基本信息
String code = req.getParameter("code");
//第二步:通过code换取网页授权access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WXAuthUtil.APPID
+ "&secret=" + WXAuthUtil.APPSECRET
+ "&code=" + code
+ "&grant_type=authorization_code";
System.out.println("url:" + url);
com.alibaba.fastjson.JSONObject jsonObject = WXAuthUtil.doGetJson(url);
/*
{ "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
*/
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
String refresh_token = jsonObject.getString("refresh_token");
//第五步验证access_token是否失效;展示都不需要
String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
com.alibaba.fastjson.JSONObject chickuserInfo = WXAuthUtil.doGetJson(chickUrl);
System.out.println(chickuserInfo.toString());
if (!"0".equals(chickuserInfo.getString("errcode"))) {
// 第三步:刷新access_token(如果需要)-----暂时没有使用,参考文档https://mp.weixin.qq.com/wiki,
String refreshTokenUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + openid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
com.alibaba.fastjson.JSONObject refreshInfo = WXAuthUtil.doGetJson(chickUrl);
/*
* { "access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE" }
*/
// System.out.println(refreshInfo.toString());
access_token = refreshInfo.getString("access_token");
}
// 第四步:拉取用户信息(需scope为 snsapi_userinfo)
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
+ "&openid=" + openid
+ "&lang=zh_CN";
// System.out.println("infoUrl:" + infoUrl);
JSONObject userInfo = WXAuthUtil.doGetJson(infoUrl);
/*
{ "openid":" OPENID",
" nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE"
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[ "PRIVILEGE1" "PRIVILEGE2" ],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}
*/
System.out.println("JSON-----" + userInfo.toString());
System.out.println("名字-----" + userInfo.getString("nickname"));
System.out.println("头像-----" + userInfo.getString("headimgurl"));
Integer userId=0;
UserinfoDO userinfoDO=userinfoService.getUserDetilByOpenId(userInfo.getString("openid"));
if (userinfoDO!=null){
//已经存在 更新用户名称 头像
userinfoDO.setUserName(userInfo.getString("nickname"));
userinfoDO.setUserPic(userInfo.getString("headimgurl"));
userinfoService.update(userinfoDO);
userId=userinfoDO.getId();
}else{
//新用户 注册
UserinfoDO userNew=new UserinfoDO();
userNew.setUserName(userInfo.getString("nickname"));
userNew.setRegisterTime(new Date());
userNew.setUserPic(userInfo.getString("headimgurl"));
userNew.setOpenid(userInfo.getString("openid"));
userinfoService.save(userNew);
userId=userNew.getId();
}
/*
* end 获取微信用户基本信息
*/
//获取到用户信息后就可以进行重定向,走自己的业务逻辑了。。。。。。
//下面地址为 授权成功后 页面将要跳转的地址
String redUrl = "http://xxxxxxxxx:5500/index.html?userId="+userId;
return "redirect:" + redUrl;
}
}
摸索了好半天 最后才发现前端直接用href请求 不需要ajax 希望走过的坑不会再犯