假设你已经有自己的域名,因为微信公众号和微信回调都需要域名
先看看官方给的文档根据官方文档,主要流程如下:
(1)引导用户进入授权页面同意授权,获取code
(2)通过code换取网页授权access_token(与基础支持中的access_token不同)
(3)刷新access_token(如果有需要)
(3)通过网页授权access_token和openid获取用户基本信息
提示:以下是本篇文章正文内容,下面案例可供参考
编写微信授权方法和获取用户信息方法 二、使用步骤 获取微信二维码信息代码如下(示例):
@RequestMapping("/wxLogin")
public void wxLogin(HttpServletResponse response) throws IOException {
//这个url的域名必须在公众号中进行注册验证,这个地址是成功后的回调地址
String backUrl = "http://7ca0c439f61c.ngrok.io/callback";//使用自己的域名
// 第一步:用户同意授权,获取code
//请求地址 snsapi_base snsapi_userinfo
String url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
"?appid=" + HttpClientUtil.APPID +
"&redirect_uri=" + URLEncoder.encode(backUrl,"utf-8") +
"&response_type=code" +
"&scope=snsapi_userinfo" +
"&state=STATE#wechat_redirect";
logger.info("forward重定向地址{" + url + "}");
//必须重定向,否则不能成功
response.sendRedirect(url);
}
备注:在前端页面直接加载url 就可以出现二维码界面了。直接用的微信的页面,也可以根据自己的爱好进行设计页面
@RequestMapping("/callback")
public UserLoginRes callback(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
UserLoginRes userLoginRes = new UserLoginRes();
try{
WXUserInfoReq weixinUserInfo = new WXUserInfoReq();
String code = req.getParameter("code");
//第二步:通过code换取网页授权access_token
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
+ "appid=" + HttpClientUtil.APPID
+ "&secret=" + HttpClientUtil.APPSECRET
+ "&code=" + code
+ "&grant_type=authorization_code";
System.out.println(url);
String result = HttpClientUtil.doGet(url);
JSonObject jsonObject = JSON.parseObject(result);
String openid = jsonObject.getString("openid");
String access_token = jsonObject.getString("access_token");
//第三步验证access_token是否失效;
String chickUrl = "https://api.weixin.qq.com/sns/auth?access_token="
+ access_token + "&openid=" + openid;
String resultInfo = HttpClientUtil.doGet(chickUrl);
JSonObject chickuserInfo = JSON.parseObject(resultInfo);
System.out.println(chickuserInfo.toString());
if (!"0".equals(chickuserInfo.getString("errcode"))) {
String refreshInfo1 = HttpClientUtil.doGet(chickUrl);
JSonObject refreshInfo = JSON.parseObject(refreshInfo1);
access_token = refreshInfo.getString("access_token");
}
// 第四步:拉取用户信息
String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token
+ "&openid=" + openid
+ "&lang=zh_CN";
JSonObject userInfo = JSON.parseObject(HttpClientUtil.doGet(infoUrl));
System.out.println(userInfo.getString("openid") + ":" + userInfo.getString("nickname") +":" + userInfo.getString("sex"));
}catch (Exception e){
e.printStackTrace();
userLoginRes.setResult("NO");
userLoginRes.setRtnErrId("ERROR");
userLoginRes.setRtnErrMsg(e.getMessage());
}
return userLoginRes;
}
使用到的HttpClientUtil工具类
代码如下(示例):
public class HttpClientUtil {
//appid、secret为自己公众号平台的appid和secret
public static final String APPID="xxxxxxx";
public static final String APPSECRET ="xxxxxxx";
public static String doGet(String url, Map param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
HttpGet httpGet = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
httpGet = new HttpGet(uri);
httpGet.setHeader("Host", "api.weixin.qq.com");
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
httpGet.setHeader("Accept", "text/html, application/xhtml+xml, **");
connection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
connection.setRequestProperty("Connection", "keep-alive");
connection.setRequestProperty("Accept-Language", "zh-CN");
connection.setRequestProperty("Cache-Control", "no-cache");
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("rn");
}
result = sbf.toString();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
connection.disconnect();// 关闭远程连接
}
return result;
}
}
最后根据实际业务处理用户登录
//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,"用户添加失败,请重新操作");
}
到此这篇关于springboot 微信授权网页登录操作流程的文章就介绍到这了,更多相关springboot 微信授权登录内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!



