首先 你登陆微信的公众号平台https://mp.weixin.qq.com/
搞个账号后 到开发者工具->公众平台测试账号
第一步 设置一个域名 这个域名要外网能访问 如果是自己测试的话 不用服务器 就用内网映射(这里推荐netapp)
这里注意不用加什么http://
第二步 后台写一个接口 返回一个echostr给微信去认证这个域名就可以了
@GetMapping("/sign")
@ResponseBody
public String test(String echostr) {
return echostr;
}
第三步 配置另外2个重要信息(这里的js接口应该是可以不配置的 大佬们可以试试)
第四步
就是授权认证了 注意 以下的appid secret是填自己微信测试号上的
userinfo就是拿到的微信用户的信息了 有头像 昵称 国家信息等
@GetMapping("/sign/auth")
public String auth(@RequestParam(value = "code",required = false) String code, Model model) {
String codeUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+SECRET+"&code=" + code + "&grant_type=authorization_code";
RestTemplate restTemplate = new RestTemplate();
String codeResponse=restTemplate.getForObject(codeUrl,String.class);
JSONObject tokenJson = JSONObject.parseObject(codeResponse);
String reflushUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid="+appid+"&grant_type=refresh_token&refresh_token="+tokenJson.get("refresh_token");
String reflushUrlResponse=restTemplate.getForObject(reflushUrl,String.class);
System.out.println(reflushUrlResponse+"========================================reflushUrlResponse");
String userinfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+tokenJson.get("access_token")+"&openid="+tokenJson.get("openid")+"&lang=zh_CN";
String userinfoUrlResponse = restTemplate.getForObject(userinfoUrl,String.class);
System.out.println(userinfoUrlResponse+"============================================userinfoUrl");
model.addAttribute("userinfo",JSONObject.parseObject(userinfoUrlResponse));
return "test";//这里是返回到自己的页面当中
}
然后就是拼接那条用来微信端点的链接了
这里我用一个代码拼接了起来了 注意这里的scope有两种的样子
@GetMapping("/test")
@ResponseBody
public String testDemo(){
try {
String url = "http://3p3hqu.natappfree.cc/sign/auth";
String first = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+ URLEncoder.encode(url,"UTF-8")+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
return first;
}catch(Exception e){
return "";
}
}
那么ojbk了 万事大吉