springboot实现微信小程序登录简介
微信小程序登录是开发者通过微信提供的身份验证机制,获取用户唯一标识(openid)和会话密钥(session_key)的过程。springboot作为后端框架,可以与小程序前端配合完成完整的登录流程。
小程序端调用wx.login()
小程序前端调用此api获取临时登录凭证code
示例代码:
wx.login({ success(res) { if (res.code) { // 发送code到后端 } } })
springboot后端处理登录
接收小程序传来的code
向微信接口服务发起请求验证code
获取用户唯一标识openid和会话密钥session_key
返回自定义登录态
后端生成自定义登录态(如token)并返回给小程序
小程序后续请求携带此登录态
springboot后端实现微信登录
1.导入httpclient的maven坐标
<dependency> <groupid>org.apache.httpcomponents</groupid> <artifactid>httpclient</artifactid> <version>4.5.13</version> </dependency>
2.http工具类
/** * http工具类 */ public class httpclientutil { static final int timeout_msec = 5 * 1000; /** * 发送get方式请求 * @param url * @param parammap * @return */ public static string doget(string url,map<string,string> parammap){ // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); string result = ""; closeablehttpresponse response = null; try{ uribuilder builder = new uribuilder(url); if(parammap != null){ for (string key : parammap.keyset()) { builder.addparameter(key,parammap.get(key)); } } uri uri = builder.build(); //创建get请求 httpget httpget = new httpget(uri); //发送请求 response = httpclient.execute(httpget); //判断响应状态 if(response.getstatusline().getstatuscode() == 200){ result = entityutils.tostring(response.getentity(),"utf-8"); } }catch (exception e){ e.printstacktrace(); }finally { try { response.close(); httpclient.close(); } catch (ioexception e) { e.printstacktrace(); } } return result; } /** * 发送post方式请求 * @param url * @param parammap * @return * @throws ioexception */ public static string dopost(string url, map<string, string> parammap) throws ioexception { // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); closeablehttpresponse response = null; string resultstring = ""; try { // 创建http post请求 httppost httppost = new httppost(url); // 创建参数列表 if (parammap != null) { list<namevaluepair> paramlist = new arraylist(); for (map.entry<string, string> param : parammap.entryset()) { paramlist.add(new basicnamevaluepair(param.getkey(), param.getvalue())); } // 模拟表单 urlencodedformentity entity = new urlencodedformentity(paramlist); httppost.setentity(entity); } httppost.setconfig(builderrequestconfig()); // 执行http请求 response = httpclient.execute(httppost); resultstring = entityutils.tostring(response.getentity(), "utf-8"); } catch (exception e) { throw e; } finally { try { response.close(); } catch (ioexception e) { e.printstacktrace(); } } return resultstring; } /** * 发送post方式请求 * @param url * @param parammap * @return * @throws ioexception */ public static string dopost4json(string url, map<string, string> parammap) throws ioexception { // 创建httpclient对象 closeablehttpclient httpclient = httpclients.createdefault(); closeablehttpresponse response = null; string resultstring = ""; try { // 创建http post请求 httppost httppost = new httppost(url); if (parammap != null) { //构造json格式数据 jsonobject jsonobject = new jsonobject(); for (map.entry<string, string> param : parammap.entryset()) { jsonobject.put(param.getkey(),param.getvalue()); } stringentity entity = new stringentity(jsonobject.tostring(),"utf-8"); //设置请求编码 entity.setcontentencoding("utf-8"); //设置数据类型 entity.setcontenttype("application/json"); httppost.setentity(entity); } httppost.setconfig(builderrequestconfig()); // 执行http请求 response = httpclient.execute(httppost); resultstring = entityutils.tostring(response.getentity(), "utf-8"); } catch (exception e) { throw e; } finally { try { response.close(); } catch (ioexception e) { e.printstacktrace(); } } return resultstring; } private static requestconfig builderrequestconfig() { return requestconfig.custom() .setconnecttimeout(timeout_msec) .setconnectionrequesttimeout(timeout_msec) .setsockettimeout(timeout_msec).build(); } }
3.jwt工具类
import io.jsonwebtoken.claims; import io.jsonwebtoken.jwtbuilder; import io.jsonwebtoken.jwts; import io.jsonwebtoken.signaturealgorithm; import java.nio.charset.standardcharsets; import java.util.date; import java.util.map; public class jwtutil { /** * 生成jwt * 使用hs256算法, 私匙使用固定秘钥 * * @param secretkey jwt秘钥 * @param ttlmillis jwt过期时间(毫秒) * @param claims 设置的信息 * @return */ public static string createjwt(string secretkey, long ttlmillis, map<string, object> claims) { // 指定签名的时候使用的签名算法,也就是header那部分 signaturealgorithm signaturealgorithm = signaturealgorithm.hs256; // 生成jwt的时间 long expmillis = system.currenttimemillis() + ttlmillis; date exp = new date(expmillis); // 设置jwt的body jwtbuilder builder = jwts.builder() // 如果有私有声明,一定要先设置这个自己创建的私有的声明,这个是给builder的claim赋值,一旦写在标准的声明赋值之后,就是覆盖了那些标准的声明的 .setclaims(claims) // 设置签名使用的签名算法和签名使用的秘钥 .signwith(signaturealgorithm, secretkey.getbytes(standardcharsets.utf_8)) // 设置过期时间 .setexpiration(exp); return builder.compact(); } /** * token解密 * * @param secretkey jwt秘钥 此秘钥一定要保留好在服务端, 不能暴露出去, 否则sign就可以被伪造, 如果对接多个客户端建议改造成多个 * @param token 加密后的token * @return */ public static claims parsejwt(string secretkey, string token) { // 得到defaultjwtparser claims claims = jwts.parser() // 设置签名的秘钥 .setsigningkey(secretkey.getbytes(standardcharsets.utf_8)) // 设置需要解析的jwt .parseclaimsjws(token).getbody(); return claims; } }
4.准备好签名所需使用的密钥,过期时间等
sky: jwt: user-secret-key: itcast # 设置jwt过期时间 user-ttl: 7200000 # 设置前端传递过来的令牌名称 user-token-name: authentication
5.用对象类将配置文件的属性封装
@component @configurationproperties(prefix = "sky.jwt") @data public class jwtproperties { /** * 用户端微信用户生成jwt令牌相关配置 */ private string usersecretkey; private long userttl; private string usertokenname; }
6.wechatproperties对象类部分属性以及配置文件
关于怎么注册大家可以移步最下方。
@component @configurationproperties(prefix = "sky.wechat") @data public class wechatproperties { private string appid; //小程序的appid private string secret; //小程序的秘钥 } //application.yml配置文件 sky: wechat: appid: ${sky.wechat.appid} secret: ${sky.wechat.secret} //application-dev.yml配置文件 sky: wechat: # todo:需要在微信公众平台申请相关信息并填入 appid: ****** secret: ******
7.准备好dto数据对象
/** * c端用户登录 */ @data public class userlogindto implements serializable { private string code; }
8.控制层接口
@restcontroller @requestmapping("/user/user") @slf4j @requiredargsconstructor // lombok 自动生成构造函数 @api(tags = "c端用户相关接口") public class usercontroller { private final userservice userservice; private final jwtproperties jwtproperties; /** * 微信登录 * @param userlogindto * @return */ @postmapping("/login") @apioperation("微信登录") public result<userloginvo> login(@requestbody userlogindto userlogindto){ log.info("微信用户登录:{}",userlogindto.getcode()); //微信登录 user user = userservice.wxlogin(userlogindto); //为微信用户生成jwt令牌 map<string,object> claims = new hashmap<>(); claims.put(jwtclaimsconstant.user_id,user.getid()); string token = jwtutil.createjwt(jwtproperties.getusersecretkey(),jwtproperties.getuserttl(),claims); userloginvo userloginvo = userloginvo.builder() .id(user.getid()) .openid(user.getopenid()) .token(token) .build(); return result.success(userloginvo); } }
9.微信登录的服务层的接口和实现类
//接口 public interface userservice { /** * 微信登录接口 * @param userlogindto * @return */ user wxlogin(userlogindto userlogindto); } //实现类 @service @slf4j public class userserviceimpl implements userservice { public static final string wx_login = "https://api.weixin.qq.com/sns/jscode2session"; @autowired private wechatproperties wechatproperties; @autowired private usermapper usermapper; /** * 微信登录 * @param userlogindto * @return */ @override public user wxlogin(userlogindto userlogindto) { string openid = getopenid(userlogindto.getcode()); //判断openid是否为空,如果为空表示登录失败,抛出业务异常 if(openid == null){ throw new loginfailedexception(messageconstant.login_failed); } //判断当前用户是否是新用户 user user = usermapper.getbyopenid(openid); //如果是新用户,自动完成注册 if(user == null){ user = user.builder() .openid(openid) .createtime(localdatetime.now()) .build(); usermapper.insert(user); } //返回这个用户对象 return user; } /** * 调用微信接口服务,获取当前微信用户的openid * @param code * @return */ private string getopenid(string code){ map<string, string> map = new hashmap<>(); map.put("appid",wechatproperties.getappid()); map.put("secret",wechatproperties.getsecret()); map.put("js_code",code); map.put("grant_type","authorization_code"); string json = httpclientutil.doget(wx_login, map); jsonobject jsonobject =json.parseobject(json); string openid = jsonobject.getstring("openid"); return openid; } }
注册小程序,获取key
微信公众平台
到此这篇关于springboot后端实现小程序微信登录的文章就介绍到这了,更多相关springboot小程序微信登录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论