一、创建网站应用
1. 在微信开发平台上面创建以个网站应用
2. 微信开发平台地址 https://open.weixin.qq.com/https://open.weixin.qq.com/
二、配置基本信息
1. 把公用的信息放在application.yml中
#微信开放平台创建的网站应用的appid
AppID: *********
#微信开放平台创建的网站应用的appsecret
AppSecret: ***********************************
scope: snsapi_login
#微信开放平台创建的网站 设置的授权回调域
redirect_url: 自己的回调地址,必须是公网能够访问的
2. 获取微信二维码信息
@Value("${AppID}")
private String appid;
@Value("${redirect_url}")
private String callBack;
@Value("${scope}")
private String scope;
@Value("${AppSecret}")
private String appsecret;
@Override
public String getWechatCode() {
try {
String oauthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
String redirect_uri = URLEncoder.encode(callBack, "utf-8");
oauthUrl = oauthUrl.replace("APPID",appid).replace("REDIRECT_URI",redirect_uri).replace("SCOPE",scope);
logger.info(oauthUrl);
return ReturnMessage.success(0,"获取完成",oauthUrl);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return ReturnMessage.fail(44,"失败");
}
备注:在前端页面直接加载oauthUrl 就可以出现二维码界面了。直接用的微信的页面,也可以根据自己的爱好进行设计页面。如下图
3. 接收扫码之后的信息
@Override
public String callBackUserInfo(String code, String state) {
try {
//1.通过code获取access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
url = url.replace("APPID",appid).replace("SECRET",appsecret).replace("CODE",code);
JSONObject tokenInfoObject = HttpUtils.httpGet(url);
logger.info("tokenInfoObject:{}",tokenInfoObject);
//2.通过access_token和openid获取用户信息
String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
userInfoUrl = userInfoUrl.replace("ACCESS_TOKEN",tokenInfoObject.getString("access_token")).replace("OPENID",tokenInfoObject.getString("openid"));
JSONObject userInfoStr = HttpUtils.httpGet(userInfoUrl);
logger.info("userInfoObject:{}",userInfoStr);
if (userInfoStr == null) {
return ReturnMessage.fail(40,"获取失败");
}
//3.根据uuid查询用户是否存在,如果存在直接登录。如果不存在则自动注册,在登录
UserInfoModel userInfoByWechat = iUserDao.getUserInfoByWechat(userInfoStr.get("unionid").toString());
if (userInfoByWechat != null) {
return ReturnMessage.success(0,"获取成功",userInfoByWechat);
}
//4.数据库添加用户信息
String username = userInfoStr.get("nickname").toString();
String unionid = userInfoStr.get("unionid").toString();
UserInfoBean userInfoBean = new UserInfoBean();
userInfoBean.setUuid(unionid);
userInfoBean.setUsername(username);
// 微信登录
userInfoBean.setStatus(2);
iUserDao.insertUser(userInfoBean);
//5.根据uuid查询新注册的用户信息
UserInfoModel userInfoModel= iUserDao.getUserInfoByWechat(unionid);
if (userInfoModel == null) {
return ReturnMessage.fail(400,"用户添加失败,请重新操作");
}
return ReturnMessage.success(0,"获取成功",userInfoModel);
} catch (Exception e) {
e.printStackTrace();
}
return ReturnMessage.fail(400,"获取失败"