1、配置网页受权域名不能带http,wwwjava
2、获取用户信息web
package com.dongpeng.controller; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.dongpeng.utils.HttpUtils; @Controller public class OAuthTokenController { public static final String APP_ID=""; public static final String APP_SECRET=""; /** * 跳转到微信端获取code信息 * @return * @throws UnsupportedEncodingException */ @RequestMapping("/auth") public String auth() throws UnsupportedEncodingException { StringBuilder authUrl = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize?"); authUrl.append("appid=").append(APP_ID).append("&").append("redirect_uri=").append(URLEncoder.encode("http://lianghao.xdp8.cn/getUserInfo","utf-8")) .append("&").append("response_type=code").append("&").append("scope=snsapi_userinfo").append("&").append("state=1").append("#wechat_redirect"); System.out.println(authUrl); return "redirect:"+authUrl.toString(); } /** * 经过code获取用户信息 * @param code * @return */ @RequestMapping("/getUserInfo") @ResponseBody public String getUserInfo(String code) { StringBuilder accessTokenUrl = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?"); accessTokenUrl.append("appid=").append(APP_ID).append("&").append("secret=").append(APP_SECRET).append("&").append("code=").append(code).append("&grant_type=authorization_code"); String result = HttpUtils.get(accessTokenUrl.toString()); JSONObject jsonObject = JSON.parseObject(result); StringBuilder userUrl = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?"); userUrl.append("access_token=").append(jsonObject.getString("access_token")).append("&").append("openid=").append(jsonObject.getString("openid")).append("&lang=zh_CN"); return HttpUtils.get(userUrl.toString()); } }
先访问/auth接口跳转微信端获取codespring
再经过redirect_uri指定回调地址跳转到getUserInfo接口获取用户信息json