admin 管理员组文章数量: 1184232
微信小程序登入
前端登入流程
1-获取code
2-获取昵称 头像
3-把code 昵称 头像 封装成data对象
4-调用登入接口 传入data对象
5-把请求结果token缓存到本地
uniapp代码
<template><view><button @click="login">登入</button></view></template><script>
export default{
methods:{
async login(){Promise.all([this.getCode(),this.getUserInfo()]).then(res =>{// 3-把code 昵称 头像 封装成data对象
let data ={
code: res[0].code,
nickName: res[1].userInfo.nickName,
avatarUrl: res[1].userInfo.avatarUrl
}
console.log('用户的登入信息', data);// 4-调用登入接口 传入data对象
uni.request({
url:"",
method:'POST',
data: data,
success:(res)=>{// 5-把请求结果token缓存到本地
console.log("登入结果", res);
uni.setStorageSync('token', res.data.token);}});})},// 1-获取codegetCode(){returnnewPromise((resolve, reject)=>{
wx.login({
timeout:5000,
success:(res)=>{resolve(res)},
fail:(err)=>{reject(err)}})});},// 2-获取头像和昵称getUserInfo(){returnnewPromise((resolve, reject)=>{
wx.getUserProfile({
desc:"获取用户信息",
success:(res)=>{resolve(res)},
fail:(err)=>{reject(err)}})});},}}</script>服务器
服务器登入流程
1-整理数据,需要如下
// 请求地址 固定值String url="";// AppID(小程序ID)String appid="wx8e25486c2bdafe11";// AppSecret(小程序密钥)String secret="cce5a87eeb5f0ff39f75db1be2f05088";// 登录时获取的 codeString js_code=user.getCode();// 授权类型,此处只需填写 authorization_code 固定值String grant_type="authorization_code";2-拼接地址
String path=url+"?appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type="+grant_type;
3-使用HttpClientUtil工具类发送get请求拼接后的地址得到json结果
4-使用fastjson解析json结果得到openid
5-根据openid查询数据库判断该用户是否存在
-存在,更新该用户的数据
-不存在,添加该用户
6-根据openid生成token返回前端
SpringBoot代码
登入接口
packagecom.example.server.controller;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONObject;importcom.example.server.constant.SystemConstant;importcom.example.server.pojo.WxUser;importcom.example.server.utils.HttpClientUtil;importcom.example.server.utils.JwtUtils;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.web.bind.annotation.PostMapping;importorg.springframework.web.bind.annotation.RequestBody;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;importjava.util.HashMap;importjava.util.Map;/**
* @Author 刘帅乐
* @Date 2022/6/29 11:44
* @Version 1.0
*/@RestController@RequestMapping("/my")publicclassMyController{@AutowiredHttpClientUtil http;@PostMapping("/login")publicMaplogin(@RequestBodyWxUser user){System.out.println("用户信息:"+user);/* 1-整理数据,需要如下 */// 请求地址String url="";//小程序 appIdString appid="wx8e25486c2bdafe11";//小程序 appSecretString secret="cce5a87eeb5f0ff39f75db1be2f05088";//登录时获取的 codeString js_code=user.getCode();// 授权类型,此处只需填写 authorization_codeString grant_type="authorization_code";/* 2-拼接地址 */String path=url+"?appid="+appid+"&secret="+secret+"&js_code="+js_code+"&grant_type="+grant_type;System.out.println("拼接后的请求路径:"+path);/* 3-使用HttpClientUtil工具类发送get请求拼接后的地址得到json结果 */String res=http.sendHttpGet(path);System.out.println("请求结果:"+res);/* 4-使用fastjson解析json结果得到openid */JSONObject jsonObject= JSON.parseObject(res);String openid = jsonObject.get("openid").toString();System.out.println("openid是:"+openid);/* 5-根据openid查询数据库判断该用户是否存在 */// 主要是演示登入的代码,为了不混淆视听操作数据库的代码就不演示了。这一步不写也能跑通/* 6-根据openid生成token返回前端 */String token =JwtUtils.createJWT(openid, user.getNickName(),SystemConstant.JWT_TTL);Map<String,Object> resultMap=newHashMap<>();
resultMap.put("token",token);System.out.println("返回前端token:"+token);return resultMap;}}上面代码还需要下面几个步骤才能运行
1-引入依赖
<!-- JWT --><dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>3.2.0</version></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency><!-- 添加Httpclient支持 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><!--json--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.40</version></dependency>2-创建SystemConstant类
在如下位置创建
packagecom.example.server.constant;/**
* 系统级静态变量
* @Author 刘帅乐
* @Date 2022/6/29 14:53
* @Version 1.0
*/publicclassSystemConstant{//Token不存在publicstaticfinalint JWT_ERRCODE_NULL =4000;//Token过期publicstaticfinalint JWT_ERRCODE_EXPIRE =4001;//验证不通过publicstaticfinalint JWT_ERRCODE_FAIL =4002;//密匙publicstaticfinalString JWT_SECERT ="8677df7fc3a34e26a61c034d5ec8245d";publicstaticfinallong JWT_TTL =24*60*60*1000;}3-创建HttpClientUtil工具类
packagecom.example.server.utils;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.NameValuePair;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.config.RequestConfig;importorg.apache.http.client.entity.UrlEncodedFormEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.conn.ssl.DefaultHostnameVerifier;importorg.apache.http.conn.util.PublicSuffixMatcher;importorg.apache.http.conn.util.PublicSuffixMatcherLoader;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importorg.apache.http.message.BasicNameValuePair;importorg.apache.http.util.EntityUtils;importorg.springframework.stereotype.Component;importjava.io.*;importjava.net.URL;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;/**
* @Author 刘帅乐
* @Date 2022/6/29 14:32
* @Version 1.0
*/@ComponentpublicclassHttpClientUtil{/**
* 默认参数设置
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
* setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
*/privateRequestConfig requestConfig =RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();/**
* 静态内部类---作用:单例产生类的实例
* @author Administrator
*
*/privatestaticclassLazyHolder{privatestaticfinalHttpClientUtil INSTANCE =newHttpClientUtil();}privateHttpClientUtil(){}publicstaticHttpClientUtilgetInstance(){returnLazyHolder.INSTANCE;}/**
* 发送 post请求
* @param httpUrl 地址
*/publicStringsendHttpPost(String httpUrl){HttpPost httpPost =newHttpPost(httpUrl);// 创建httpPostreturnsendHttpPost(httpPost);}/**
* 发送 post请求
* @param httpUrl 地址
* @param params 参数(格式:key1=value1&key2=value2)
*/publicStringsendHttpPost(String httpUrl,String params){HttpPost httpPost =newHttpPost(httpUrl);// 创建httpPosttry{//设置参数StringEntity stringEntity =newStringEntity(params,"UTF-8");
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);}catch(Exception e){
e.printStackTrace();}returnsendHttpPost(httpPost);}/**
* 发送 post请求
* @param httpUrl 地址
* @param maps 参数
*/publicStringsendHttpPost(String httpUrl,Map<String,String> maps){HttpPost httpPost =newHttpPost(httpUrl);// 创建httpPost// 创建参数队列List<NameValuePair> nameValuePairs =newArrayList<NameValuePair>();for(String key : maps.keySet()){
nameValuePairs.add(newBasicNameValuePair(key, maps.get(key)));}try{
httpPost.setEntity(newUrlEncodedFormEntity(nameValuePairs,"UTF-8"));}catch(Exception e){
e.printStackTrace();}returnsendHttpPost(httpPost);}/**
* 发送Post请求
* @param httpPost
* @return
*/privateStringsendHttpPost(HttpPost httpPost){CloseableHttpClient httpClient =null;CloseableHttpResponse response =null;HttpEntity entity =null;String responseContent =null;try{// 创建默认的httpClient实例
httpClient =HttpClients.createDefault();
httpPost.setConfig(requestConfig);// 执行请求long execStart =System.currentTimeMillis();
response = httpClient.execute(httpPost);long execEnd =System.currentTimeMillis();System.out.println("=================执行post请求耗时:"+(execEnd-execStart)+"ms");long getStart =System.currentTimeMillis();
entity = response.getEntity();
responseContent =EntityUtils.toString(entity,"UTF-8");long getEnd =System.currentTimeMillis();System.out.println("=================获取响应结果耗时:"+(getEnd-getStart)+"ms");}catch(Exception e){
e.printStackTrace();}finally{try{// 关闭连接,释放资源if(response !=null){
response.close();}if(httpClient !=null){
httpClient.close();}}catch(IOException e){
e.printStackTrace();}}return responseContent;}/**
* 发送 get请求
* @param httpUrl
*/publicStringsendHttpGet(String httpUrl){HttpGet httpGet =newHttpGet(httpUrl);// 创建get请求returnsendHttpGet(httpGet);}/**
* 发送 get请求Https
* @param httpUrl
*/publicStringsendHttpsGet(String httpUrl){HttpGet httpGet =newHttpGet(httpUrl);// 创建get请求returnsendHttpsGet(httpGet);}/**
* 发送Get请求
* @param httpGet
* @return
*/privateStringsendHttpGet(HttpGet httpGet){CloseableHttpClient httpClient =null;CloseableHttpResponse response =null;HttpEntity entity =null;String responseContent =null;try{// 创建默认的httpClient实例.
httpClient =HttpClients.createDefault();
httpGet.setConfig(requestConfig);// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent =EntityUtils.toString(entity,"UTF-8");}catch(Exception e){
e.printStackTrace();}finally{try{// 关闭连接,释放资源if(response !=null){
response.close();}if(httpClient !=null){
httpClient.close();}}catch(IOException e){
e.printStackTrace();}}return responseContent;}/**
* 发送Get请求Https
* @param httpGet
* @return
*/privateStringsendHttpsGet(HttpGet httpGet){CloseableHttpClient httpClient =null;CloseableHttpResponse response =null;HttpEntity entity =null;String responseContent =null;try{// 创建默认的httpClient实例.PublicSuffixMatcher publicSuffixMatcher =PublicSuffixMatcherLoader.load(newURL(httpGet.getURI().toString()));DefaultHostnameVerifier hostnameVerifier =newDefaultHostnameVerifier(publicSuffixMatcher);
httpClient =HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
httpGet.setConfig(requestConfig);// 执行请求
response = httpClient.execute(httpGet);
entity = response.getEntity();
responseContent =EntityUtils.toString(entity,"UTF-8");}catch(Exception e){
e.printStackTrace();}finally{try{// 关闭连接,释放资源if(response !=null){
response.close();}if(httpClient !=null){
httpClient.close();}}catch(IOException e){
e.printStackTrace();}}return responseContent;}/**
* 发送xml数据
* @param url
* @param xmlData
* @return
* @throws ClientProtocolException
* @throws IOException
*/publicstaticHttpResponsesendXMLDataByPost(String url,String xmlData)throwsClientProtocolException,IOException{HttpClient httpClient =HttpClients.createDefault();HttpPost httppost =newHttpPost(url);StringEntity entity =newStringEntity(xmlData);
httppost.setEntity(entity);
httppost.setHeader("Content-Type","text/xml;charset=UTF-8");HttpResponse response = httpClient.execute(httppost);return response;}/**
* 获得响应HTTP实体内容
*
* @param response
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/publicstaticStringgetHttpEntityContent(HttpResponse response)throwsIOException,UnsupportedEncodingException{HttpEntity entity = response.getEntity();if(entity !=null){InputStream is = entity.getContent();BufferedReader br =newBufferedReader(newInputStreamReader(is,"UTF-8"));String line = br.readLine();StringBuilder sb =newStringBuilder();while(line !=null){
sb.append(line +"\n");
line = br.readLine();}return sb.toString();}return"";}}4-创建JwtUtils工具类
packagecom.example.server.utils;importcom.example.server.constant.SystemConstant;importcom.example.server.pojo.CheckResult;importio.jsonwebtoken.*;importorg.bouncycastle.util.encoders.Base64;importjavax.crypto.SecretKey;importjavax.crypto.spec.SecretKeySpec;importjava.util.Date;/**
*
* @Author 刘帅乐
* @Date 2022/6/29 14:45
* @Version 1.0
*/publicclassJwtUtils{/**
* 签发JWT
* @param id
* @param subject 可以是JSON数据 尽可能少
* @param ttlMillis
* @return
*/publicstaticStringcreateJWT(String id,String subject,long ttlMillis){SignatureAlgorithm signatureAlgorithm =SignatureAlgorithm.HS256;long nowMillis =System.currentTimeMillis();Date now =newDate(nowMillis);SecretKey secretKey =generalKey();JwtBuilder builder =Jwts.builder().setId(id).setSubject(subject)// 主题.setIssuer("hrkj")// 签发者.setIssuedAt(now)// 签发时间.signWith(signatureAlgorithm, secretKey);// 签名算法以及密匙if(ttlMillis >=0){long expMillis = nowMillis + ttlMillis;Date expDate =newDate(expMillis);
builder.setExpiration(expDate);// 过期时间}return builder.compact();}/**
* 验证JWT
* @param jwtStr
* @return
*/publicstaticCheckResultvalidateJWT(String jwtStr){CheckResult checkResult =newCheckResult();Claims claims =null;try{
claims =parseJWT(jwtStr);
checkResult.setSuccess(true);
checkResult.setClaims(claims);}catch(ExpiredJwtException e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);
checkResult.setSuccess(false);}catch(SignatureException e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
checkResult.setSuccess(false);}catch(Exception e){
checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);
checkResult.setSuccess(false);}return checkResult;}/**
* 生成加密Key
* @return
*/publicstaticSecretKeygeneralKey(){byte[] encodedKey =Base64.decode(SystemConstant.JWT_SECERT);SecretKey key =newSecretKeySpec(encodedKey,0, encodedKey.length,"AES");return key;}/**
* 解析JWT字符串
* @param jwt
* @return
* @throws Exception
*/publicstaticClaimsparseJWT(String jwt)throwsException{SecretKey secretKey =generalKey();returnJwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();}}最后可以会报错
<dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.0</version></dependency><dependency><groupId>com.sun.xml.bind</groupId><artifactId>jaxb-impl</artifactId><version>2.3.0</version></dependency><dependency><groupId>com.sun.xml.bind</groupId><artifactId>jaxb-core</artifactId><version>2.3.0</version></dependency><dependency><groupId>javax.activation</groupId><artifactId>activation</artifactId><version>1.1.1</version></dependency>版权声明:本文标题:跨平台神器UniApp结合SpringBoot,打造微信小程序登陆流程秘籍 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1771309457a3543143.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论