准备工作
https://open.weixin.qq.com
参考文档: https://open.weixin.qq.com/cgi-bin/showdocument?
action=dir_list&t=resource/res_list&verify=1&id=open1419316505&token=e547653f995d8f402704d5cb2945177dc8aa4e7e&la
ng=zh_CN
application.properties
# 微信开放平台 appid
wx.open.app_id=wxed9954c01bb89b47
# 微信开放平台 appsecret
wx.open.app_secret=a7482517235173ddb4083788de60b90e
# 微信开放平台 重定向url
wx.open.redirect_url=http://localhost:8160/ucenter/wx/callback
获取配置文件
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil implements InitializingBean {
@Value("${wx.open.app_id}")
private String appId;
@Value("${wx.open.app_secret}")
private String appSecret;
@Value("${wx.open.redirect_url}")
private String redirectUrl;
public static String WX_OPEN_APP_ID;
public static String WX_OPEN_APP_SECRET;
public static String WX_OPEN_REDIRECT_URL;
@Override
public void afterPropertiesSet() throws Exception {
WX_OPEN_APP_ID = appId;
WX_OPEN_APP_SECRET = appSecret;
WX_OPEN_REDIRECT_URL = redirectUrl;
}
}
前后端分离
@CrossOrigin
@Controller//注意这里没有配置 @RestController
@RequestMapping("/ucenter/wx")
public class WxApiController {
@Autowired
private UcenterMemberService ucenterMemberService;
@GetMapping("login")
public String genQrConnect(HttpSession session) {
// 微信开放平台授权baseUrl,%s占位符
String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
"?appid=%s" +
"&redirect_uri=%s" +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=%s" +
"#wechat_redirect";
// 回调地址
String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
try {
redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //redirectUrl编码
} catch (UnsupportedEncodingException e) {
throw new zdyException(20001, e.getMessage());
}//生成二维码,返回跳转路劲/callback
String qrcodeUrl = String.format(//填写%s字符串
baseUrl,
ConstantPropertiesUtil.WX_OPEN_APP_ID,
redirectUrl,
"atguigu");
return "redirect:"+qrcodeUrl; }//重定向到/callback
@GetMapping("/callback")//通过 code 获取access_token
public String vcallback(String code,String state) throws Exception {
String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
"?appid=%s" +"&secret=%s" +"&code=%s" +"&grant_type=authorization_code";
String accessTokenUrl = String.format(baseAccessTokenUrl,
ConstantPropertiesUtil.WX_OPEN_APP_ID,
ConstantPropertiesUtil.WX_OPEN_APP_SECRET,code);
String result = HttpClientUtils.get(accessTokenUrl);//第二次请求使用httpclien参数访问
//解析json字符串
Gson gson = new Gson();
HashMap map = gson.fromJson(result, HashMap.class);
String accessToken = (String)map.get("access_token");
String openid = (String)map.get("openid");
UcenterMember ucenterMember=ucenterMemberService.selectopenid(openid);
if (ucenterMember==null){
//访问微信的资源服务器,获取用户信息
String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=%s" + "&openid=%s";
String userInfoUrl=String.format(baseUserInfoUrl, accessToken, openid);
String resultUserInfo