前端
config包下
// 本地环境
const Url= 'http://本机地址:端口号/**********';
//暴露接口
export default Url;
common交互逻辑
// 引入本地环境
import Url from '../config/config.js';
//清除登录用户信息
export default {
//获取openid方法
getOpenIdSessionKey() {
var that = this;
uni.login({
provider: 'weixin',
success: (res) => {
//这里获取的是用户的code,用来换取 openid、unionid、session_key 等信息,再将信息丢给后台自己的登录业务就行了
uni.request({
url: Url + '/*****/*******',
method: 'post',
dataType: 'json',
responseType: 'text',
header: {
'content-type': 'application/json',
},
data: {
code: res.code
},
}).then((res) => {
console.log(res);
console.log(res[1].data.code);
// if (res.data.code == 200) {
// console.log("测试");
// }
})
}
})
},
/**
* 判断当前参数是否为空(空返回true,不空返回flase)
* @param {*} options 需要判空的参数
*/
fieldIsNull(options) {
if (typeof options === "undefined" || options === null || options === "") {
return true;
} else {
return false;
}
}
}
index页面
<script>
//引入common交互逻辑
import h from '../../common/common.js';
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
// 获取token oppenId
h.getOpenIdSessionKey();
},
methods: {
}
}
</script>
后端Java
过滤拦截token文章来源:https://www.toymoban.com/news/detail-518621.html
package com.skiff.manufacture.config;
import com.alibaba.fastjson.JSON;
import com.skiff.manufacture.util.ReturnResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
*
* 登录验证拦截并验证token是否正确
* @author Kylin
* @since 2022/11/16
*/
@Component
public class LoginStatusInterceptor implements HandlerInterceptor {
static Logger logger = Logger.getLogger(LoginStatusInterceptor.class.getName());
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 功能描述: token验证
*
* @param request
* @param response
* @param handler
* @return boolean
* @author Carver
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
// 从请求头获取token
String token = request.getHeader("token");
System.out.println(token + "00000000000");
if (StringUtils.isBlank(token)) {
printJson(response);
return false;
}
Object redisObj = redisTemplate.opsForValue().get(token);
if (null != redisObj) {
// 用户操作,给redis加时间
redisTemplate.expire(token, 30, TimeUnit.MINUTES);
return true;
}
// token错误
printJson(response);
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
/**
* 功能描述: token校验失败
*
* @param response
* @author Carver
*/
private static void printJson(HttpServletResponse response) {
// token验证失败
logger.warning("token校验失败!");
ReturnResult rt = new ReturnResult();
rt.setErrorCode(ErrorCode.TOKEN_VERIFICATION_FAILED);
String content = JSON.toJSONString(rt);
printContent(response, content);
}
/**
* 功能描述: token错误状态下向前端响应状态
*
* @param response 响应
* @param content 响应内容
* @author Carver
*/
private static void printContent(HttpServletResponse response, String content) {
try {
response.reset();
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store");
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.write(content);
writer.flush();
} catch (IOException e) {
logger.warning("响应json数据异常!" + e.getMessage());
}
}
}
校验token文章来源地址https://www.toymoban.com/news/detail-518621.html
package com.skiff.manufacture.controller;
import com.skiff.manufacture.config.ErrorCode;
import com.skiff.manufacture.dto.UserLoginCode;
import com.skiff.manufacture.dto.WeAppParamsDto;
import com.skiff.manufacture.util.FastJsonUtil;
import com.skiff.manufacture.util.OkHttpUtils;
import com.skiff.manufacture.util.ReturnResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
/**
*
* 获取微信open_id
* @author kylin
* @since 2022/11/16
*/
@RestController
@RequestMapping("/******")
public class AuthorizationController {
static Logger logger = Logger.getLogger(AuthorizationController.class.getName());
@Value("${weapp.app-id}")
private String appId;
@Value("${weapp.app-url}")
private String appUrl;
@Value("${weapp.app-secret}")
private String appSecret;
@Value("${weapp.grant_type}")
private String grantType;
/**
*
* 功能描述: 通过小程序code获取openId和sessionKey传到前端
* 1.获取小程序code 2.从yml文件读取参数 3.发送请求,获取数据 4.将数据返回到前端
* @author kylin
* @since 2022/11/16
* @param userLoginCode
* @return com.skiff.manufacture.util.ReturnResult
*/
@RequestMapping("/******")
public ReturnResult getAuthorizationInfo(@RequestBody UserLoginCode userLoginCode) {
String code = userLoginCode.getCode();
System.out.println(code+"校验");
logger.info("进入小程序校验Controller,code:" + code);
ReturnResult rt = new ReturnResult();
// 登录凭证不能为空
if (StringUtils.isBlank(code)) {
logger.warning("参数[code]不存在!");
rt.setErrorCode(ErrorCode.INCOMPLETE_INFORMATION);
return rt;
}
//1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
// 请求参数
String params = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type="
+ grantType;
// 发送请求
String sr = OkHttpUtils.sendGet(appUrl, params);
//将sessionkey和openid的json字符串转成bean
WeAppParamsDto weAppParams = FastJsonUtil.strToBean(sr, WeAppParamsDto.class);
rt.setData(weAppParams);
return rt;
}
}
到了这里,关于uniApp微信小程序前后端交互的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!