欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot 微信授权网页登录操作流程

程序员文章站 2023-12-31 23:02:10
操作流程假设你已经有自己的域名,因为微信公众号和微信回调都需要域名先看看官方给的文档根据官方文档,主要流程如下:(1)引导用户进入授权页面同意授权,获取code(2)通过code换取网页授权acces...

操作流程

假设你已经有自己的域名,因为微信公众号和微信回调都需要域名

先看看官方给的文档

根据官方文档,主要流程如下:

(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();
   /*start 获取微信用户基本信息*/
   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);
 
   /*
   { "access_token":"access_token",
   "expires_in":7200,
   "refresh_token":"refresh_token",
   "openid":"openid",
   "scope":"scope" 
   }
   */
    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":"access_token",
    "expires_in":7200,
    "refresh_token":"refresh_token",
    "openid":"openid",
    "scope":"scope" }
    */
    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));
   /*
   { "openid":" openid",
   "nickname": nickname,
   "sex":"1",
   "province":"province"
   "city":"city",
   "country":"country",
   "headimgurl": "http://wx.qlogo.cn/mmopen/g3monuztnhkdmzicilibx6iafqac56vxlsufpb6n5wksyvy0chqkkiajsgq1dzutogvllrhjberqq4emsv84eavhiaiceqxibjxcfhe/46",
   "privilege":[ "privilege1" "privilege2"  ],
   "unionid": "o6_bmasdasdsad6_2sgvt7hmzopfl"
   }
   */
   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<string, string> 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, */*");
   httpget.setheader("accept-encoding", "gzip, deflate, br");
   httpget.setheader("connection", "keep-alive");
   httpget.setheader("accept-language", "zh-cn");
   httpget.setheader("cache-control", "no-cache");
 
   // 执行请求
   response = httpclient.execute(httpget);
   // 判断返回状态是否为200
   if (response.getstatusline().getstatuscode() == 200) {
    resultstring = entityutils.tostring(response.getentity(), "utf-8");
   }
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   try {
    if (response != null) {
     response.close();
    }
    httpget.releaseconnection();
    httpclient.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
  return resultstring;
 }
 
 public static string doget(string url) {
  return doget(url, null);
 }
 
 public static string dopost(string url, map<string, string> param) {
  // 创建httpclient对象
  closeablehttpclient httpclient = httpclients.createdefault();
  closeablehttpresponse response = null;
  string resultstring = "";
  try {
   // 创建http post请求
   httppost httppost = new httppost(url);
   // 创建参数列表
   if (param != null) {
    list<namevaluepair> paramlist = new arraylist<>();
    for (string key : param.keyset()) {
     paramlist.add(new basicnamevaluepair(key, param.get(key)));
    }
    // 模拟表单
    urlencodedformentity entity = new urlencodedformentity(paramlist);
    httppost.setentity(entity);
   }
   // 执行http请求
   response = httpclient.execute(httppost);
   resultstring = entityutils.tostring(response.getentity(), "utf-8");
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   try {
    response.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
 
  return resultstring;
 }
 
 public static string dopost(string url) {
  return dopost(url, null);
 }
 
 public static string dopostjson(string url, string json) {
  // 创建httpclient对象
  closeablehttpclient httpclient = httpclients.createdefault();
  closeablehttpresponse response = null;
  string resultstring = "";
  try {
   // 创建http post请求
   httppost httppost = new httppost(url);
   // 创建请求内容
   stringentity entity = new stringentity(json, contenttype.application_json);
   httppost.setentity(entity);
   // 执行http请求
   response = httpclient.execute(httppost);
   resultstring = entityutils.tostring(response.getentity(), "utf-8");
  } catch (exception e) {
   e.printstacktrace();
  } finally {
   try {
    response.close();
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }
  return resultstring;
 }
 
 public static string dogetstr(string httpurl) {
  httpurlconnection connection = null;
  inputstream is = null;
  bufferedreader br = null;
  string result = null;// 返回结果字符串
  try {
   // 创建远程url连接对象
   url url = new url(httpurl);
   // 通过远程url连接对象打开一个连接,强转成httpurlconnection类
   connection = (httpurlconnection) url.openconnection();
   // 设置连接方式:get
   connection.setrequestmethod("get");
   // 设置连接主机服务器的超时时间:15000毫秒
   connection.setconnecttimeout(15000);
   // 设置读取远程返回的数据时间:60000毫秒
   connection.setreadtimeout(60000);
   //设置请求头
   connection.setrequestproperty("host", "api.weixin.qq.com");
   connection.setrequestproperty("user-agent", "mozilla/5.0 (windows nt 6.1; wow64; trident/7.0; rv:11.0) like gecko");
   connection.setrequestproperty("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("\r\n");
    }
    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 微信授权登录内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

上一篇:

下一篇: