1.登录微信公众平台
在对接微信授权时可以使用测试账号进行操作,当然你也可以使用进行企业认证的公众号进行对接,此次对接使用测试账号
微信沙箱账号链接,点击该链接使扫码登录测试公众平台,登录后如下:
2.在测试平台下方,使用开发者的微信关注该测试平台
3.点击修改,添加授权回调页面域名,如下:
这里的域名地址可以使用外网映射工具进行映射,可以参考natapp的安装配置教程
4.编码
4.1.添加依赖到pom.xml中
<!-- SpringBoot 对lombok 支持 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- SpringBoot web 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
.4.2.修改application.yml配置文件
#该APPID,secret为测试公众平台的数据
appid: wx6c470ce4236b64fa
secret: 1a82d6d1cefa6ae818c9753c9200d2e5
#使用外网映射工具映射回调地址
redirectUri: http://xi4jsd.natappfree.cc/callback
### 生成微信授权
authorizedUrl: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
###获取code后,请求以下链接获取access_token
access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
###拉取用户信息(需scope为 snsapi_userinfo)
userinfo: https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
4.3.创建一个微信的工具类,方便调用
@Component
public class WeiXinUtils {
@Value("${appid}")
private String appId;
@Value("${secret}")
private String secret;
@Value("${redirecturi}")
private String redirectUri;
@Value("${authorizedUrl}")
private String authorizedUrl;
@Value("${access_token}")
private String accessToken;
@Value("${userinfo}")
private String userinfo;
/**
* @Description: 微信授权地址
*/
public String getAuthorizedUrl() {
return authorizedUrl.replace("APPID", appId).replace("REDIRECT_URI", URLEncoder.encode(redirectUri));
}
/**
* @Description: 获取微信AccessToken
*/
public String getAccessTokenUrl(String code) {
return accessToken.replace("APPID", appId).replace("SECRET", secret).replace("CODE", code);
}
/**
* @Description: 获取微信用户信息
*/
public String getUserInfo(String accessToken, String openId) {
return userinfo.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
}
}
4.4.创建一个授权的控制器,此处没有写在业务层,可以自己写在业务层
@Slf4j
@Controller
public class AuthController {
@Autowired
private WeiXinUtils weiXinUtils;
private String errorPage = "errorPage";
private static RequestConfig requestConfig = null;
/**
* @Description: 获取授权链接,重定向到微信开发平台
*/
@GetMapping("/authorizedUrl")
public String authUrl() {
String authorizedUrl = weiXinUtils.getAuthorizedUrl();
return "redirect:" + authorizedUrl;
}
@RequestMapping("/callback")
@ResponseBody
public String callback(String code) {
if (StringUtils.isEmpty(code)){
return errorPage;
}
// 1.使用Code 获取 access_token
String accessTokenUrl = weiXinUtils.getAccessTokenUrl(code);
//2.使用HTTPclient技术调用 accessTokenUrl 接口地址
JSONObject resultAccessToken = httpGet(accessTokenUrl);
//3.判断返回的json是否正确,当含有errorcode时,则为报错信息
boolean errcodeKey = resultAccessToken.containsKey("errcode");
if (errcodeKey) {
return errorPage;
}
// 4.使用access_token获取用户信息
String accessToken = resultAccessToken.getString("access_token");
if (StringUtils.isEmpty(accessToken)){
return errorPage;
}
//5.获取openid
String openid = resultAccessToken.getString("openid");
if (StringUtils.isEmpty(openid)){
return errorPage;
}
// 6.获取用户信息(需scope为 snsapi_userinfo)
String userInfoUrl = weiXinUtils.getUserInfo(accessToken, openid);
JSONObject userInfoResult = httpGet(userInfoUrl);
log.info("userInfoResult:" + userInfoResult);
return userInfoResult.toJSONString();
}
/**
* 发送get请求
* @param url 请求路径
* @return
*/
public static JSONObject httpGet(String url) {
// get请求返回结果
JSONObject jsonResult = null;
CloseableHttpClient client = HttpClients.createDefault();
// 发送get请求
HttpGet request = new HttpGet(url);
request.setConfig(requestConfig);
try {
CloseableHttpResponse response = client.execute(request);
// 请求发送成功,并得到响应
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 读取服务器返回过来的json字符串数据
HttpEntity entity = response.getEntity();
String strResult = EntityUtils.toString(entity, "utf-8");
// 把json字符串转换成json对象
jsonResult = JSONObject.parseObject(strResult);
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
} finally {
request.releaseConnection();
}
return jsonResult;
}
}
5.启动服务进行测试
测试使用微信web开发者工具 下载地址,安装该工具后使用关注过测试公众平的的微信用户进行登录测试
5.1.输入获取授权链接的接口地址
http://127.0.0.1:8080/authorizedUrl
5.2.同意授权,进行异步回调