校快送 2024.12.5 v0.0.5

This commit is contained in:
tsukiyalo 2024-12-03 15:51:03 +08:00
parent 65420d9f9e
commit f0debc7d38
28 changed files with 728 additions and 450 deletions

View File

@ -126,6 +126,8 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -255,4 +255,26 @@ create table collect
id bigint auto_increment comment 'id' primary key ,
userId bigint not null comment '用户id',
businessId bigint not null comment '商家id'
) comment '收藏';
# 用户评分表
create table user_rating
(
id bigint auto_increment primary key comment 'id',
businessId bigint not null comment '商家id',
userId bigint not null comment '用户id',
orderId bigint not null comment '订单id',
rating tinyint not null comment '评分',
createTime datetime default CURRENT_TIMESTAMP not null comment '创建时间'
) comment '用户评分' collate = utf8mb4_unicode_ci;
# 商家等级表
create table business_level
(
id bigint auto_increment primary key comment 'id',
businessId bigint not null comment '商家id',
averageScore DECIMAL(3, 2) not null default 0 comment '综合评分',
level tinyint not null comment '等级',
createTime DATETIME default CURRENT_TIMESTAMP comment '创建时间',
updateTime DATETIME default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP comment '更新时间'
)

View File

@ -3,10 +3,12 @@ package com.bsz.school_send_back_end;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@MapperScan("com.bsz.school_send_back_end.mapper")
@SpringBootApplication
@EnableScheduling
public class UserCenterApplication {
public static void main(String[] args) {

View File

@ -1,347 +0,0 @@
package com.bsz.school_send_back_end.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bsz.school_send_back_end.common.BaseResponse;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.common.ResultUtils;
import com.bsz.school_send_back_end.config.AlipayClients;
import com.bsz.school_send_back_end.contant.RedisKeyConstant;
import com.bsz.school_send_back_end.mapper.UserMapper;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.vo.UserVO;
import com.bsz.school_send_back_end.utils.RandomNumberGenerator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("/Alipay")
public class AlipayController {
@Value("${alipay.appId}")
public String appId;
@Value("${alipay.appPrivateKey}")
public String appPrivateKey;
@Value("${alipay.alipayPublicKey}")
public String PublicKey;
@Resource
private UserMapper userMapper;
@Resource
private RandomNumberGenerator randomNumberGenerator;
private static String authToken;
public static final String NOURL = "http://39.101.78.35:6271/Alipay/notifyUrl";
/**
* 解析code获取open_id和token
* @return aaa
* @throws AlipayApiException 支付宝api异常
*/
@GetMapping("/parseCode")
public BaseResponse<UserVO> login(String authcode, HttpServletRequest req) throws AlipayApiException {
String privateKey = appPrivateKey;
String alipayPublicKey = PublicKey;
AlipayConfig alipayConfig = new AlipayConfig();
//沙箱网关
alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
//支付宝网关
alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
alipayConfig.setAppId(appId);
alipayConfig.setPrivateKey(privateKey);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(alipayPublicKey);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setCode(authcode);
request.setGrantType("authorization_code");
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
// System.out.println(response.getBody());打印所有响应
authToken = response.getAccessToken();
if (!response.isSuccess()) {
return ResultUtils.error(ErrorCode.PARAMS_ERROR);
}
AlipayUserInfoShareRequest request1 = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response1 = alipayClient.execute(request1, authToken);
User oid = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, response.getOpenId()));
UserVO userVO = new UserVO();
if (response1.isSuccess()) {
if (oid == null) {
User user = new User();
user.setOpenId(response.getOpenId());
user.setUsername(StringUtils.isAnyBlank(response1.getNickName()) ? "随机名字" + randomNumberGenerator.generateRandomNumber() : response1.getNickName());
user.setUserPassword("123456");
user.setUserAccount("用户" + randomNumberGenerator.generateRandomNumber());
user.setAvatarUrl(StringUtils.isAnyBlank(response1.getAvatar()) ? "https://tfs.alipayobjects.com/images/partner/ATuihpR50zu7UAAAAAAAAAAAAADtl2AA" : response1.getAvatar());
userMapper.insert(user);
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,user);
BeanUtils.copyProperties(user, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"注册成功");
}
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE, oid);
BeanUtils.copyProperties(oid, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"登录成功");
}
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,oid);
BeanUtils.copyProperties(oid, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"登录成功");
}
// @GetMapping("/login")
// public BaseResponse<User> getMessage() throws AlipayApiException {
// AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, appPrivateKey, "json", "GBK", PublicKey, "RSA2");
// AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
// AlipayUserInfoShareResponse response = alipayClient.execute(request, authToken);
// User oid = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, response.getOpenId()));
// if (response.isSuccess()) {
// if (oid == null) {
// User user = new User();
// user.setOpenId(response.getOpenId());
// user.setUsername(StringUtils.isAnyBlank(response.getNickName()) ? "随机名字" + randomNumberGenerator.generateRandomNumber() : response.getNickName());
// user.setUserPassword("123456");
// user.setAvatarUrl(StringUtils.isAnyBlank(response.getAvatar()) ? "https://tfs.alipayobjects.com/images/partner/ATuihpR50zu7UAAAAAAAAAAAAADtl2AA" : response.getAvatar());
// userMapper.insert(user);
// return ResultUtils.success(user,"注册成功");
// }
// return ResultUtils.success(oid,"登录成功");
// }
// return ResultUtils.error(ErrorCode.PARAMS_ERROR);
//
// }
@GetMapping("/test/parseCode")
public BaseResponse<User> test_login(String authcode, HttpServletRequest req) throws AlipayApiException {
AlipayClients clients = new AlipayClients();
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setCode(authcode);
request.setGrantType("authorization_code");
AlipaySystemOauthTokenResponse response = clients.alipayClient().execute(request);
// System.out.println(response.getBody());打印所有响应
authToken = response.getAccessToken();
if (!response.isSuccess()) {
return ResultUtils.error(ErrorCode.PARAMS_ERROR);
}
AlipayUserInfoShareRequest request1 = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response1 = clients.alipayClient().execute(request1, authToken);
User oid = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, response.getOpenId()));
if (response.isSuccess()) {
if (oid == null) {
User user = new User();
user.setOpenId(response.getOpenId());
user.setUsername(StringUtils.isAnyBlank(response1.getNickName()) ? "随机名字" + randomNumberGenerator.generateRandomNumber() : response1.getNickName());
user.setUserPassword("123456");
user.setAvatarUrl(StringUtils.isAnyBlank(response1.getAvatar()) ? "https://tfs.alipayobjects.com/images/partner/ATuihpR50zu7UAAAAAAAAAAAAADtl2AA" : response1.getAvatar());
userMapper.insert(user);
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,oid);
return ResultUtils.success(user,"注册成功");
}
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,oid);
return ResultUtils.success(oid,"登录成功");
}
return ResultUtils.error(ErrorCode.PARAMS_ERROR);
}
/* @GetMapping("/test/login")
public BaseResponse<User> test_getMessage() throws AlipayApiException {
AlipayClients clients = new AlipayClients();
AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response = clients.alipayClient().execute(request, authToken);
User oid = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, response.getOpenId()));
if (response.isSuccess()) {
if (oid == null) {
User user = new User();
user.setOpenId(response.getOpenId());
user.setUsername(StringUtils.isAnyBlank(response.getNickName()) ? "随机名字" + randomNumberGenerator.generateRandomNumber() : response.getNickName());
user.setUserPassword("123456");
user.setAvatarUrl(StringUtils.isAnyBlank(response.getAvatar()) ? "https://tfs.alipayobjects.com/images/partner/ATuihpR50zu7UAAAAAAAAAAAAADtl2AA" : response.getAvatar());
userMapper.insert(user);
return ResultUtils.success(user,"注册成功");
}
return ResultUtils.success(oid,"登录成功");
}
return ResultUtils.error(ErrorCode.PARAMS_ERROR);
}*/
@GetMapping("/trade")
public BaseResponse<String> AlipayTradeCreate() throws AlipayApiException {
//创建客户端
AlipayClients clients = new AlipayClients();
//AlipayClient client = clients.alipayClient();
//创建交易请求
AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
//创建实体类
AlipayTradeCreateModel model = new AlipayTradeCreateModel();
//请求参数 沙箱内部参数
//TODO 后续传入 数据库中菜品
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String datePart = dateFormat.format(new Date());
// 生成随机部分确保其长度为9位
Random random = new Random();
String randomPart = String.format("%09d", random.nextInt(1000000000)); // 生成一个0到8位的随机数补足到9位
// 拼接日期和随机部分并赋值给String a
String a = datePart + randomPart;
System.out.println(a);
model.setOutTradeNo(a);
model.setTotalAmount("88.88");
model.setSubject("Iphone6 16G");
model.setProductCode("JSAPI_PAY");
model.setSellerId("2088721035350152");
model.setBuyerId("2088722035366541");
model.setOpAppId("2021004151684053");
///回调地址
request.setNotifyUrl("http://39.101.78.35:6271/api/Alipay/notifyUrl");
request.setBizModel(model);
String tradeNo = "";
try {
AlipayTradeCreateResponse response = clients.alipayClient().execute(request);
String trade_no = response.getTradeNo();
tradeNo = trade_no;
} catch (AlipayApiException e) {
e.printStackTrace();
}
return ResultUtils.success(tradeNo);
}
@GetMapping("/test/close")
public String closeOrder(String orderNo) throws AlipayApiException {
AlipayClients clients = new AlipayClients();
AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
AlipayTradeCloseModel model = new AlipayTradeCloseModel();
//model.setTradeNo(); 这是订单项
//订单项可能会有多个支付单
model.setOutTradeNo(orderNo);
request.setBizModel(model);
request.setNotifyUrl(NOURL);
AlipayTradeCloseResponse response = clients.alipayClient().execute(request);
//这里应该写进日志
return "";
}
@GetMapping("/test/refund")
public String test_refund(String orderNo) throws AlipayApiException {
AlipayClients clients = new AlipayClients();
AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
AlipayTradeRefundModel model = new AlipayTradeRefundModel();
model.setOutTradeNo(orderNo);
model.setRefundAmount("1");
//退款请求单号 要求唯一 需改
model.setOutRequestNo("123");
request.setBizModel(model);
request.setNotifyUrl(NOURL);
AlipayTradeRefundResponse response = clients.alipayClient().execute(request);
return response.getBody();
}
@GetMapping("/test/query")
public String test_query (String orderNo) throws AlipayApiException {
AlipayClients clients = new AlipayClients();
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
AlipayTradeQueryModel model = new AlipayTradeQueryModel();
model.setOutTradeNo(orderNo);
request.setBizModel(model);
request.setNotifyUrl(NOURL);
AlipayTradeQueryResponse response = clients.alipayClient().execute(request);
String body = response.getBody();
return body;
}
@PostMapping("/notifyUrl")
public void aliPayNotifyUrl(HttpServletRequest request, HttpServletResponse response) {
// HttpServletRequest 的参数转换为 Map<String, String>
Map<String,String> params = new HashMap<>();Map<String, String[]> requestParams = request.getParameterMap();
for(String name : requestParams.keySet()) {
params.put(name, request.getParameter(name));
}
String resultInfo = "buyer_id=208****42&total_amount=0.01&body=***试&trade_no=20190329**941025940236&notify_time=2019-03-29 19:42:04&subject=**电脑网站支付&sign_type=RSA2&charset=UTF-8&auth_app_id=201****222&notify_type=trade_status_sync&invoice_amount=0.01&out_trade_no=20190329ygyg45484544100003&trade_status=TRADE_SUCCESS&gmt_payment=2019-03-29 19:42:03&version=1.0&point_amount=0.00&sign=LDDUIGQmc+1qNtk3oyoAKVeMUKTngdX3ZjVeZOK0EjiPDJ/+Nk+0WSqcE6J7/5xb96Z/vP0yY3pVhZUiFVJ1G45/ys/HAleHh+EERZ1lkCkule1sSyaGFTKQGKx4uHpTyqIgRB1bouf19RPbSx1EkA0VkCarSy9G/OEG5Qmg8UdL2dRulMhlbOHS7tdMJJycDA8vOspOUMeQmk/H6IK9R2Kou5hN2T3KR1GWLYFK+z1jeZhQB3q52lZynO0OFjSzU4aQUBMW5QskQppBYd/ghtY/2YP+2H6YVGNgVmaheZMQ3PVTBALEV+8rZa91salH9DkKN2UCYGvNSNDT1VGCTQ==&gmt_create=2019-03-29 19:42:00&buyer_pay_amount=0.01&receipt_amount=0.01&fund_bill_list=[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]&seller_id=208****5&app_id=2014100***22&notify_id=20190329002221942040**8";
//编码格式
String charset="utf-8";
//支付宝公钥
String alipaypublicKey="";
//签名方式
String sign_type="RSA2";
//对待签名字符串数据通过&进行拆分
String [] temp = resultInfo.split("&");
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
//把拆分数据放在map集合内
for (int i = 0; i < temp.length; i++) {
String[] arr = temp[i].split("=", 2); //通过"="号分割成2个数据
String[] tempAagin = new String[arr.length]; //再开辟一个数组用来接收分割后的数据
for (int j = 0; j < arr.length; j++) {
tempAagin[j] = arr[j];
}
map.put(tempAagin[0], tempAagin[1]);
}
System.out.println(map);
String alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3JKMG3clg/1MqewlIK/koEhiQiSLagckb/2/Dyvg+rJ2snGiAgzNvhvvc1GdVC+Xnn/P+U+2tAytyuvbOuhmGgNZjeObczJXpo/0D6LBdYDrg4PVMDxpStCxLUpaShHbc/l/IquaorBwd94UJxIPAbUQkUBCbo94mGbhDX+yU4FQ6k1yeUtn03jvZ3AY0BEHpenCxWKgr5S/CUAYEitMbi/r7extBy6f4FCR120NM7VaNEK1xpHbGHo6rDpyiAOR1lWFuiqOJ1hv14UL/SfOLlzvUZiiPysIxdNjycZyiyRvFRHP3n8GBAaJDm9vVHwDfgQ5s3Ig2ggBeYXkFHZqWwIDAQAB";
try {
//验签方法
boolean signVerified = AlipaySignature.rsaCheckV1(params,PublicKey,charset,sign_type);
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
if (signVerified && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
// 业务处理
writer.println("success");
} else {
writer.println("fail");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -12,6 +12,7 @@ import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.model.domain.Business;
import com.bsz.school_send_back_end.model.domain.BusinessAuth;
import com.bsz.school_send_back_end.model.domain.BusinessLevel;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.dto.business.BusinessAddRequest;
import com.bsz.school_send_back_end.model.dto.business.BusinessQueryRequest;
@ -20,6 +21,7 @@ import com.bsz.school_send_back_end.model.dto.business.BusinessUpdateRequest;
import com.bsz.school_send_back_end.model.vo.BusinessAdminVO;
import com.bsz.school_send_back_end.model.vo.BusinessVO;
import com.bsz.school_send_back_end.service.BusinessAuthService;
import com.bsz.school_send_back_end.service.BusinessLevelService;
import com.bsz.school_send_back_end.service.BusinessService;
import com.bsz.school_send_back_end.service.UserService;
import lombok.extern.slf4j.Slf4j;
@ -31,6 +33,7 @@ import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import static com.bsz.school_send_back_end.contant.UserConstant.USER_SALT;
@ -52,6 +55,9 @@ public class BusinessController {
@Resource
private UserService userService;
@Resource
private BusinessLevelService businessLevelService;
@PostMapping("/add")
public BaseResponse<Long> addBusiness(@RequestBody BusinessAddRequest businessAddRequest) {
@ -179,9 +185,9 @@ public class BusinessController {
* 查询所有商家
*/
@PostMapping("/list")
public BaseResponse<List<Business>> listBusinessAll(){
List<Business> businessList = businessService.list();
return new BaseResponse<>(0,businessList,"查询成功");
public BaseResponse<List<BusinessVO>> listBusinessAll(){
List<BusinessVO> business = businessService.findAllBusiness();
return new BaseResponse<>(0,business,"查询成功");
}

View File

@ -3,6 +3,7 @@ package com.bsz.school_send_back_end.controller;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsz.school_send_back_end.annotation.AuthCheck;
import com.bsz.school_send_back_end.common.BaseResponse;
@ -138,6 +139,21 @@ public class OrdersController {
return ResultUtils.success(ordersService.getOrdersVO(orders));
}
/**
* 根据 id 获取订单信息仅管理员
*/
@GetMapping("/get/my")
public BaseResponse<OrdersVO> getOrderVOByMyId(@RequestParam Long id, HttpServletRequest request) {
if (id <= 0) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
User loginUser = userService.getLoginUser(request);
Orders orders = ordersService.getOne(Wrappers.<Orders>lambdaQuery().eq(Orders::getId, id)
.eq(Orders::getUserId, loginUser.getId()));
ThrowUtils.throwIf(orders == null, ErrorCode.NOT_FOUND_ERROR);
return ResultUtils.success(ordersService.getOrdersVO(orders));
}
/**
* 分页获取订单列表管理员
*/

View File

@ -5,49 +5,45 @@ import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeCloseModel;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bsz.school_send_back_end.common.BaseResponse;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.common.ResultUtils;
import com.bsz.school_send_back_end.config.AlipayClients;
import com.bsz.school_send_back_end.contant.RedisKeyConstant;
import com.bsz.school_send_back_end.contant.RedisKeyConstant;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.mapper.UserMapper;
import com.bsz.school_send_back_end.model.domain.Orders;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.dto.CommonRequest;
import com.bsz.school_send_back_end.model.vo.UserVO;
import com.bsz.school_send_back_end.service.AliPayService;
import com.bsz.school_send_back_end.service.OrdersService;
import com.bsz.school_send_back_end.service.UserService;
import com.bsz.school_send_back_end.service.WebsocketService;
import com.bsz.school_send_back_end.utils.RandomNumberGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping("/Alipay1")
@Slf4j
@RequestMapping("/Alipay")
public class TestAlipayController {
@Resource
@ -59,6 +55,9 @@ public class TestAlipayController {
@Resource
private AliPayService aliPayService;
@Resource
private WebsocketService websocketService;
@ -79,7 +78,7 @@ public class TestAlipayController {
private static String authToken;
public static final String NOURL = "http://39.101.78.35:6448/api/Alipay1/notifyUrl";
public static final String NOURL = "http://39.101.78.35:6448/api/Alipay/notifyUrl";
/**
* 解析code获取open_id和token
@ -87,18 +86,8 @@ public class TestAlipayController {
* @throws AlipayApiException 支付宝api异常
*/
@GetMapping("/parseCode")
public BaseResponse<UserVO> login(String authcode, HttpServletRequest req) throws AlipayApiException {
String privateKey = appPrivateKey;
String alipayPublicKey = PublicKey;
AlipayConfig alipayConfig = new AlipayConfig();
//支付宝网关
alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
alipayConfig.setAppId(appId);
alipayConfig.setPrivateKey(privateKey);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(alipayPublicKey);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
public BaseResponse<UserVO> login(String authcode, long severId, HttpServletRequest req) throws AlipayApiException {
AlipayConfig alipayConfig = choiceServer(severId);
AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setCode(authcode);
@ -139,66 +128,6 @@ public class TestAlipayController {
return ResultUtils.success(userVO,"登录成功");
}
/**
* 解析code获取open_id和token
* @return aaa
* @throws AlipayApiException 支付宝api异常
*/
@GetMapping("/parseCode1")
public BaseResponse<UserVO> login1(String authcode, HttpServletRequest req) throws AlipayApiException {
//String privateKey = appPrivateKey;
// String alipayPublicKey = PublicKey;
String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc1rWOaCHl7KnDDMctWIgFJqerq9ZU8QsxSA+wQC4nrTfoQVSVZn8fDNosilCHda7yv910A9aJYqZKx0+NOXY9YvMbKYifWtO8TtzAQ9Q0EQXce85gnVQ3yn9evE1MVwfmMIiXJ2jx/dmGrxuADrLcsNB/U4xsusKcNQaA76vALtAYTnKwOODaDt5Qd2OC25PRcGtKupKIbir/f62tNquBkCX+Z5URBpy0rZY2hCu30v3uPv8I3OlpxegFwNDHpKMIY3+wjQtqsogQTn20E5wzeV3VNabNxbORq6B6nh8mvxlo9q14XvmMJDPUoWiJgyUUpaAPZFWSpRCrLvWQY/klAgMBAAECggEAZJ/Ahig7L2gClriZBXfadOuTAapS7dZkpu6j2iGjOyOATgu0N9I11vcI9zCab/5KC0abzzYzK5vWMv3jBSmLueDFNnUUSaEdXaB/Mv+RowIU75ujEgt+n/jUdTR8p3DjCYWz7L6FL1T9fdLU4vkLOlpauoYg/xVnjI7cqFacq8SWr3jiGj/I31O18y02/eDiyAb5RMlSlNGnzvDuRwJ3h2Sn1u7znbMCi6CydG3hx+I0GE2iJqVPymc1f0T0vm7Jy3l/zL84oNKLTgPCqG9k+eriC7RaMkbvPQFjWCDCuWxgYM2pi1L9ZDG+FkReTFsZw6r/TWc4sl2xtj3GDSrHYQKBgQD1NwFBMQwsUQ/aJP63R0gILWSFR0+yQ314vfRRVKoZTujbQr7RBAzgQff97DirINIxXCBeV0zifpc2IaAPaY29YjDnQU+xGqIO91EWPjMkQ6XUvGGesKnKDYkA5yBMyD3/BH8BwJruidW2DwtC2rGTW1hatkXNtYccEI79/00UOQKBgQCjvKIySZdRolOYUfSPHHipOygWClFy1DlI54XDnj0gRBoOrFkeqrXr+G8dYeXP6UnMqLWX8V3RuEJB8klwKGLkMtUWdqMQUFM5yvjuX2d1Y9R2ESw0ch70B/6aItMVv6aN4GjGwCJWD1XD54IpWxtAKJsUxbDiN+343cVqSQQETQKBgQDq9JBcMa3TTLyerbHuVPt88lmNpr2DNk2kAoZ142S0qTpO1M5XIcVgn3UKNWw69FDSgM529rkxkFA8ys0910q7erkW7Cp6rOU459onMOP5zGO5yeLTlbyqYHu0hMEbMQbOMjWrrSwGgcVnE1Ub8sYRRoYLLPkHWPcjee45C4WEaQKBgHkUUeDb+JD+d9DIsg9uH3ANdcwunyJJ+36E7q7EgjEtCxPUsSZzWIoBsbFJppbDzbYRABA3BYjDOAPqNhJBWzeiu16cJmM28wRmqwQi+q+dPgx9EHJL/cW5b7XtkKihi3mY/AIVLI71UhfHR8JrQ9CC9oM62V2/vDNvU8AP9G91AoGANdvRubukeWgvWryBTaPuUTpjkP1mOuJuHiHEW5/XePsURwS6gGP/qJ9bSbhYhQ6iDaMOQ8vahfYM3Q4jvDxgcKS/N1fxFTohcN4bVdvekq62YdTNqcGhNzaxMNboFZYt2dPeDm8PRRMP+abddrS2NqgVSOC3Ru5Kh9iRIs2LOgE=";
String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3JKMG3clg/1MqewlIK/koEhiQiSLagckb/2/Dyvg+rJ2snGiAgzNvhvvc1GdVC+Xnn/P+U+2tAytyuvbOuhmGgNZjeObczJXpo/0D6LBdYDrg4PVMDxpStCxLUpaShHbc/l/IquaorBwd94UJxIPAbUQkUBCbo94mGbhDX+yU4FQ6k1yeUtn03jvZ3AY0BEHpenCxWKgr5S/CUAYEitMbi/r7extBy6f4FCR120NM7VaNEK1xpHbGHo6rDpyiAOR1lWFuiqOJ1hv14UL/SfOLlzvUZiiPysIxdNjycZyiyRvFRHP3n8GBAaJDm9vVHwDfgQ5s3Ig2ggBeYXkFHZqWwIDAQAB";
AlipayConfig alipayConfig = new AlipayConfig();
//沙箱网关
alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
alipayConfig.setAppId("2021004151684053");
alipayConfig.setPrivateKey(privateKey);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(alipayPublicKey);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
request.setCode(authcode);
request.setGrantType("authorization_code");
AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
System.out.println(response.getBody());
authToken = response.getAccessToken();
if (!response.isSuccess()) {
return ResultUtils.error(ErrorCode.PARAMS_ERROR);
}
AlipayUserInfoShareRequest request1 = new AlipayUserInfoShareRequest();
AlipayUserInfoShareResponse response1 = alipayClient.execute(request1, authToken);
User oid = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getOpenId, response.getOpenId()));
UserVO userVO = new UserVO();
if (response1.isSuccess()) {
if (oid == null) {
User user = new User();
user.setOpenId(response.getOpenId());
user.setUsername(StringUtils.isAnyBlank(response1.getNickName()) ? "随机名字" + randomNumberGenerator.generateRandomNumber() : response1.getNickName());
user.setUserPassword("123456");
user.setUserAccount("用户" + randomNumberGenerator.generateRandomNumber());
user.setAvatarUrl(StringUtils.isAnyBlank(response1.getAvatar()) ? "https://tfs.alipayobjects.com/images/partner/ATuihpR50zu7UAAAAAAAAAAAAADtl2AA" : response1.getAvatar());
userMapper.insert(user);
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,user);
BeanUtils.copyProperties(user, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"注册成功");
}
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE, oid);
BeanUtils.copyProperties(oid, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"登录成功");
}
req.getSession().setAttribute(RedisKeyConstant.USER_LOGIN_STATE,oid);
BeanUtils.copyProperties(oid, userVO);
userVO.setSessionId(req.getSession().getId());
return ResultUtils.success(userVO,"登录成功");
}
@GetMapping("/payment/create")
public BaseResponse<String> AlipayTradeCreate(@RequestParam Long id, HttpServletRequest request) throws AlipayApiException {
@ -215,7 +144,7 @@ public class TestAlipayController {
}
String tradeNo = aliPayService.createPayment(String.valueOf(orderId), miniOpenId, order.getTotalPrice());
log.info("tradeNo:" + tradeNo);
return ResultUtils.success(tradeNo);
}
@ -304,16 +233,14 @@ public class TestAlipayController {
Date date = new Date();
orders.setUpdateTime(date);
boolean update = ordersService.updateById(orders);
log.info("orders:" + orders);
ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "修改订单状态失败");
//TODO 商家通知
websocketService.sendOrderMessage(orders);
String resultInfo = "buyer_id=208****42&total_amount=0.01&body=***试&trade_no=20190329**941025940236&notify_time=2019-03-29 19:42:04&subject=**电脑网站支付&sign_type=RSA2&charset=UTF-8&auth_app_id=201****222&notify_type=trade_status_sync&invoice_amount=0.01&out_trade_no=20190329ygyg45484544100003&trade_status=TRADE_SUCCESS&gmt_payment=2019-03-29 19:42:03&version=1.0&point_amount=0.00&sign=LDDUIGQmc+1qNtk3oyoAKVeMUKTngdX3ZjVeZOK0EjiPDJ/+Nk+0WSqcE6J7/5xb96Z/vP0yY3pVhZUiFVJ1G45/ys/HAleHh+EERZ1lkCkule1sSyaGFTKQGKx4uHpTyqIgRB1bouf19RPbSx1EkA0VkCarSy9G/OEG5Qmg8UdL2dRulMhlbOHS7tdMJJycDA8vOspOUMeQmk/H6IK9R2Kou5hN2T3KR1GWLYFK+z1jeZhQB3q52lZynO0OFjSzU4aQUBMW5QskQppBYd/ghtY/2YP+2H6YVGNgVmaheZMQ3PVTBALEV+8rZa91salH9DkKN2UCYGvNSNDT1VGCTQ==&gmt_create=2019-03-29 19:42:00&buyer_pay_amount=0.01&receipt_amount=0.01&fund_bill_list=[{\"amount\":\"0.01\",\"fundChannel\":\"PCREDIT\"}]&seller_id=208****5&app_id=2014100***22&notify_id=20190329002221942040**8";
//编码格式
String charset="utf-8";
//支付宝公钥
String alipaypublicKey="";
//签名方式
String sign_type="RSA2";
//对待签名字符串数据通过&进行拆分
@ -331,7 +258,6 @@ public class TestAlipayController {
System.out.println(map);
String alipayrsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3JKMG3clg/1MqewlIK/koEhiQiSLagckb/2/Dyvg+rJ2snGiAgzNvhvvc1GdVC+Xnn/P+U+2tAytyuvbOuhmGgNZjeObczJXpo/0D6LBdYDrg4PVMDxpStCxLUpaShHbc/l/IquaorBwd94UJxIPAbUQkUBCbo94mGbhDX+yU4FQ6k1yeUtn03jvZ3AY0BEHpenCxWKgr5S/CUAYEitMbi/r7extBy6f4FCR120NM7VaNEK1xpHbGHo6rDpyiAOR1lWFuiqOJ1hv14UL/SfOLlzvUZiiPysIxdNjycZyiyRvFRHP3n8GBAaJDm9vVHwDfgQ5s3Ig2ggBeYXkFHZqWwIDAQAB";
try {
//验签方法
boolean signVerified = AlipaySignature.rsaCheckV1(params,PublicKey,charset,sign_type);
@ -349,4 +275,34 @@ public class TestAlipayController {
}
}
private AlipayConfig choiceServer(long serverId) {
String testPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCc1rWOaCHl7KnDDMctWIgFJqerq9ZU8QsxSA+wQC4nrTfoQVSVZn8fDNosilCHda7yv910A9aJYqZKx0+NOXY9YvMbKYifWtO8TtzAQ9Q0EQXce85gnVQ3yn9evE1MVwfmMIiXJ2jx/dmGrxuADrLcsNB/U4xsusKcNQaA76vALtAYTnKwOODaDt5Qd2OC25PRcGtKupKIbir/f62tNquBkCX+Z5URBpy0rZY2hCu30v3uPv8I3OlpxegFwNDHpKMIY3+wjQtqsogQTn20E5wzeV3VNabNxbORq6B6nh8mvxlo9q14XvmMJDPUoWiJgyUUpaAPZFWSpRCrLvWQY/klAgMBAAECggEAZJ/Ahig7L2gClriZBXfadOuTAapS7dZkpu6j2iGjOyOATgu0N9I11vcI9zCab/5KC0abzzYzK5vWMv3jBSmLueDFNnUUSaEdXaB/Mv+RowIU75ujEgt+n/jUdTR8p3DjCYWz7L6FL1T9fdLU4vkLOlpauoYg/xVnjI7cqFacq8SWr3jiGj/I31O18y02/eDiyAb5RMlSlNGnzvDuRwJ3h2Sn1u7znbMCi6CydG3hx+I0GE2iJqVPymc1f0T0vm7Jy3l/zL84oNKLTgPCqG9k+eriC7RaMkbvPQFjWCDCuWxgYM2pi1L9ZDG+FkReTFsZw6r/TWc4sl2xtj3GDSrHYQKBgQD1NwFBMQwsUQ/aJP63R0gILWSFR0+yQ314vfRRVKoZTujbQr7RBAzgQff97DirINIxXCBeV0zifpc2IaAPaY29YjDnQU+xGqIO91EWPjMkQ6XUvGGesKnKDYkA5yBMyD3/BH8BwJruidW2DwtC2rGTW1hatkXNtYccEI79/00UOQKBgQCjvKIySZdRolOYUfSPHHipOygWClFy1DlI54XDnj0gRBoOrFkeqrXr+G8dYeXP6UnMqLWX8V3RuEJB8klwKGLkMtUWdqMQUFM5yvjuX2d1Y9R2ESw0ch70B/6aItMVv6aN4GjGwCJWD1XD54IpWxtAKJsUxbDiN+343cVqSQQETQKBgQDq9JBcMa3TTLyerbHuVPt88lmNpr2DNk2kAoZ142S0qTpO1M5XIcVgn3UKNWw69FDSgM529rkxkFA8ys0910q7erkW7Cp6rOU459onMOP5zGO5yeLTlbyqYHu0hMEbMQbOMjWrrSwGgcVnE1Ub8sYRRoYLLPkHWPcjee45C4WEaQKBgHkUUeDb+JD+d9DIsg9uH3ANdcwunyJJ+36E7q7EgjEtCxPUsSZzWIoBsbFJppbDzbYRABA3BYjDOAPqNhJBWzeiu16cJmM28wRmqwQi+q+dPgx9EHJL/cW5b7XtkKihi3mY/AIVLI71UhfHR8JrQ9CC9oM62V2/vDNvU8AP9G91AoGANdvRubukeWgvWryBTaPuUTpjkP1mOuJuHiHEW5/XePsURwS6gGP/qJ9bSbhYhQ6iDaMOQ8vahfYM3Q4jvDxgcKS/N1fxFTohcN4bVdvekq62YdTNqcGhNzaxMNboFZYt2dPeDm8PRRMP+abddrS2NqgVSOC3Ru5Kh9iRIs2LOgE=";
String testAlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3JKMG3clg/1MqewlIK/koEhiQiSLagckb/2/Dyvg+rJ2snGiAgzNvhvvc1GdVC+Xnn/P+U+2tAytyuvbOuhmGgNZjeObczJXpo/0D6LBdYDrg4PVMDxpStCxLUpaShHbc/l/IquaorBwd94UJxIPAbUQkUBCbo94mGbhDX+yU4FQ6k1yeUtn03jvZ3AY0BEHpenCxWKgr5S/CUAYEitMbi/r7extBy6f4FCR120NM7VaNEK1xpHbGHo6rDpyiAOR1lWFuiqOJ1hv14UL/SfOLlzvUZiiPysIxdNjycZyiyRvFRHP3n8GBAaJDm9vVHwDfgQ5s3Ig2ggBeYXkFHZqWwIDAQAB";
String privateKey = appPrivateKey;
String alipayPublicKey = PublicKey;
AlipayConfig alipayConfig = new AlipayConfig();
if (serverId == 0) {
alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
alipayConfig.setAppId(appId);
alipayConfig.setPrivateKey(privateKey);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(alipayPublicKey);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
}
else if (serverId == 1) {
alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
alipayConfig.setAppId(appId);
alipayConfig.setPrivateKey(testPrivateKey);
alipayConfig.setFormat("json");
alipayConfig.setAlipayPublicKey(testAlipayPublicKey);
alipayConfig.setCharset("UTF-8");
alipayConfig.setSignType("RSA2");
}
else {
throw new BusinessException(ErrorCode.PARAMS_ERROR,"网关选择错误");
}
return alipayConfig;
}
}

View File

@ -0,0 +1,86 @@
package com.bsz.school_send_back_end.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bsz.school_send_back_end.common.BaseResponse;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.common.ResultUtils;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.domain.UserRating;
import com.bsz.school_send_back_end.model.dto.CommonRequest;
import com.bsz.school_send_back_end.model.dto.userRating.UserRatingAddRequest;
import com.bsz.school_send_back_end.service.UserRatingService;
import com.bsz.school_send_back_end.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@Slf4j
@RequestMapping("/level")
public class UserRatingController {
@Resource
private UserRatingService userRatingService;
@Resource
private UserService userService;
/**
* 添加用户评分
* @param userRatingAddRequest 用户评分请求
* @param request 当期那登录用户
* @return 是否添加成功
*/
@PostMapping("/add")
public BaseResponse<Boolean> addRating (@RequestBody UserRatingAddRequest userRatingAddRequest, HttpServletRequest request) {
if (userRatingAddRequest == null) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
UserRating userRating = new UserRating();
BeanUtils.copyProperties(userRatingAddRequest, userRating);
userRatingService.validUserRating(userRating, request);
boolean save = userRatingService.save(userRating);
ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "添加失败");
return ResultUtils.success(true);
}
/**
* 删除用户评分
* @param commonRequest 用户评分id
* @return 是否删除成功
*/
@PostMapping("/delete")
public BaseResponse<Boolean> deleteUserRating (@RequestBody CommonRequest commonRequest) {
if (commonRequest == null) {
throw new BusinessException(ErrorCode.PARAMS_ERROR);
}
boolean remove = userRatingService.removeById(commonRequest.getId());
ThrowUtils.throwIf(!remove, ErrorCode.SYSTEM_ERROR, "删除失败");
return ResultUtils.success(true);
}
/**
* 展示当前用户评分
* @param request 当前用户
* @return 评分列表
*/
@PostMapping("/list")
public BaseResponse<List<UserRating>> listUserRating (HttpServletRequest request) {
User loginUser = userService.getLoginUser(request);
Long userId = loginUser.getId();
List<UserRating> list = userRatingService.list(Wrappers.<UserRating>lambdaQuery().eq(UserRating::getUserId, userId));
return ResultUtils.success(list);
}
}

View File

@ -0,0 +1,20 @@
package com.bsz.school_send_back_end.mapper;
import com.bsz.school_send_back_end.model.domain.BusinessLevel;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* @author pc
* @description 针对表business_level的数据库操作Mapper
* @createDate 2024-11-22 14:02:11
* @Entity com.bsz.school_send_back_end.model.domain.BusinessLevel
*/
public interface BusinessLevelMapper extends BaseMapper<BusinessLevel> {
}

View File

@ -0,0 +1,23 @@
package com.bsz.school_send_back_end.mapper;
import com.bsz.school_send_back_end.model.domain.UserRating;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
/**
* @author pc
* @description 针对表user_rating(用户评分)的数据库操作Mapper
* @createDate 2024-11-29 22:23:08
* @Entity com.bsz.school_send_back_end.model.domain.UserRating
*/
public interface UserRatingMapper extends BaseMapper<UserRating> {
// @Select("select avg(rating) from school_send.user_rating where businessId = #{businessId}")
@Select("select avg(rating) from xiaokuaisong.user_rating where businessId = #{businessId}")
Double findAvgByBusinessId(@Param("businessId") Long businessId);
}

View File

@ -0,0 +1,55 @@
package com.bsz.school_send_back_end.model.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import lombok.Data;
/**
*
* @TableName business_level
*/
@TableName(value ="business_level")
@Data
public class BusinessLevel implements Serializable {
/**
* id
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 商家id
*/
private Long businessId;
/**
* 综合评分
*/
private BigDecimal averageScore;
/**
* 等级
*/
private Integer level;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
@TableField(exist = false)
@Serial
private static final long serialVersionUID = 1L;
}

View File

@ -0,0 +1,51 @@
package com.bsz.school_send_back_end.model.domain;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 用户评分
* @TableName user_rating
*/
@TableName(value ="user_rating")
@Data
public class UserRating implements Serializable {
/**
* id
*/
@TableId(type = IdType.AUTO)
private Long id;
/**
* 商家id
*/
private Long businessId;
/**
* 用户id
*/
private Long userId;
/**
* 订单id
*/
private Long orderId;
/**
* 评分
*/
private Integer rating;
/**
* 创建时间
*/
private Date createTime;
@TableField(exist = false)
private static final long serialVersionUID = 1L;
}

View File

@ -11,6 +11,11 @@ import java.io.Serializable;
@Data
public class CartUpdateRequest implements Serializable {
/**
* 商家id
*/
private Long businessId;
/**
* id
*/

View File

@ -0,0 +1,29 @@
package com.bsz.school_send_back_end.model.dto.userRating;
import lombok.Data;
import java.io.Serializable;
@Data
public class UserRatingAddRequest implements Serializable {
/**
* 商家id
*/
private Long businessId;
/**
* 用户id
*/
private Long userId;
/**
* 订单id
*/
private Long orderId;
/**
* 评分
*/
private Integer rating;
}

View File

@ -86,4 +86,9 @@ public class BusinessVO implements Serializable {
*/
private Date createTime;
/**
* 等级
*/
private Integer level;
}

View File

@ -0,0 +1,31 @@
package com.bsz.school_send_back_end.scheduler;
import com.bsz.school_send_back_end.model.domain.Business;
import com.bsz.school_send_back_end.service.BusinessLevelService;
import com.bsz.school_send_back_end.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Component
@Slf4j
public class UpdateBusiness {
@Resource
private BusinessService businessService;
@Resource
private BusinessLevelService businessLevelService;
@Scheduled(cron = "0 0 0 * * ?")
public void updateBusinessLevels() {
List<Business> list = businessService.list();
for (Business business : list) {
businessLevelService.updateBusinessLevel(business.getId());
}
log.info("更新时间:" + new Date());
}
}

View File

@ -0,0 +1,24 @@
package com.bsz.school_send_back_end.service;
import com.bsz.school_send_back_end.model.domain.BusinessLevel;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* @author pc
* @description 针对表business_level的数据库操作Service
* @createDate 2024-11-22 14:02:11
*/
public interface BusinessLevelService extends IService<BusinessLevel> {
/**
* 更新商家等级
*/
void updateBusinessLevel(Long businessId);
/**
* 查询所有商家
*/
List<BusinessLevel> findAllOrdered();
}

View File

@ -52,4 +52,9 @@ public interface BusinessService extends IService<Business> {
* 获取当前登录商家
*/
Business getLoginBusiness(HttpServletRequest request);
/**
* 查询所有商家
*/
List<BusinessVO> findAllBusiness();
}

View File

@ -0,0 +1,19 @@
package com.bsz.school_send_back_end.service;
import com.bsz.school_send_back_end.model.domain.UserRating;
import com.baomidou.mybatisplus.extension.service.IService;
import javax.servlet.http.HttpServletRequest;
/**
* @author pc
* @description 针对表user_rating(用户评分)的数据库操作Service
* @createDate 2024-11-29 22:23:08
*/
public interface UserRatingService extends IService<UserRating> {
/**
* 校验
*/
void validUserRating(UserRating userRating, HttpServletRequest request);
}

View File

@ -2,13 +2,17 @@ package com.bsz.school_send_back_end.service;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.model.domain.Business;
import com.bsz.school_send_back_end.model.domain.Orders;
import com.bsz.school_send_back_end.model.domain.PrivateMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
@Slf4j
public class WebsocketService {
@Resource
@ -17,20 +21,56 @@ public class WebsocketService {
@Resource
private PrivateMessageService privateMessageService;
@Resource
private BusinessService businessService;
/**
* 简单点对点聊天
*/
public void sendChatMessage(PrivateMessage message) {
System.out.println("Sending message: " + message);
message.setMessage(message.getFrom_userAccount() + "发送:" + message.getMessage());
//使用template获取前端传来的参数来指定订阅地址
//一个参数是订阅地址 第二个参数是消息
template.convertAndSend("/topic/ServerToClient.private." + message.getTo_userAccount(), message);
if (message == null || message.getTo_userAccount() == null || message.getMessage() == null) {
log.error("发送消息失败,消息内容不完整: {}", message);
throw new BusinessException(ErrorCode.PARAMS_ERROR, "消息内容不完整");
}
//将消息存储到数据库中
log.info("正在发送消息: {}", message);
message.setMessage(message.getFrom_userAccount() + "发送:" + message.getMessage());
// 推送消息
String destination = "/topic/ServerToClient.private." + message.getTo_userAccount();
template.convertAndSend(destination, message);
// 存储消息到数据库
boolean save = privateMessageService.save(message);
if (!save) {
throw new BusinessException(ErrorCode.SYSTEM_ERROR);
log.error("消息存储失败: {}", message);
throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息存储失败");
}
log.info("消息发送成功并存储: {}", message);
}
/**
* 给商家传送订单信息
*/
public void sendOrderMessage(Orders orders) {
if (orders == null || orders.getBusinessId() == null) {
log.error("订单信息不完整,无法推送: {}", orders);
throw new BusinessException(ErrorCode.PARAMS_ERROR, "订单信息不完整");
}
log.info("正在推送订单信息: {}", orders);
Long businessId = orders.getBusinessId();
Business business = businessService.getById(businessId);
if (business == null || business.getUserId() == null) {
log.error("商家信息未找到商家ID: {}", businessId);
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "商家信息未找到");
}
Long userId = business.getUserId();
String destination = "/topic/ServerToClient.order." + userId;
template.convertAndSend(destination, orders);
log.info("订单信息推送成功目标用户ID: {}", userId);
}
}

View File

@ -5,9 +5,11 @@ import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeCreateModel;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.config.AlipayClients;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.model.domain.OrderDetails;
import com.bsz.school_send_back_end.model.domain.Orders;
import com.bsz.school_send_back_end.service.AliPayService;
@ -60,10 +62,14 @@ public class AlipayServiceImpl implements AliPayService {
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "订单不存在,订单号:" + outTradeNo);
}
OrderDetails orderDetails = orderDetailsService.getById(orderId);
LambdaQueryWrapper<OrderDetails> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderDetails::getOrderId, orderId);
OrderDetails orderDetails = orderDetailsService.getOne(wrapper);
//给支付宝的订单号设置成取餐码
order.setPickupCode(outTradeNo);
boolean update = ordersService.updateById(order);
ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "修改订单状态失败");
model.setOutTradeNo(outTradeNo);
model.setTotalAmount(String.valueOf(amount));
model.setSubject(orderDetails.getAttributeNames());
@ -73,7 +79,7 @@ public class AlipayServiceImpl implements AliPayService {
model.setOpAppId("2021004151684053");
///回调地址
aliRequest.setNotifyUrl("http://39.101.78.35:6448/api/Alipay1/notifyUrl");
aliRequest.setNotifyUrl("http://39.101.78.35:6448/api/Alipay/notifyUrl");
aliRequest.setBizModel(model);
String trade_no = null;
try {

View File

@ -0,0 +1,85 @@
package com.bsz.school_send_back_end.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.mapper.UserRatingMapper;
import com.bsz.school_send_back_end.model.domain.BusinessLevel;
import com.bsz.school_send_back_end.service.BusinessLevelService;
import com.bsz.school_send_back_end.mapper.BusinessLevelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* @author pc
* @description 针对表business_level的数据库操作Service实现
* @createDate 2024-11-22 14:02:11
*/
@Service
@Slf4j
public class BusinessLevelServiceImpl extends ServiceImpl<BusinessLevelMapper, BusinessLevel>
implements BusinessLevelService{
@Resource
private BusinessLevelMapper businessLevelMapper;
@Resource
private UserRatingMapper userRatingMapper;
@Override
public void updateBusinessLevel(Long businessId) {
Double avg = userRatingMapper.findAvgByBusinessId(businessId);
if (avg == null) {
avg = 1.0;
log.info("warn: avg没有值将赋初始值1" + avg);
log.info("当前商家id" + businessId);
}
int level = calculateLevel(avg);
BusinessLevel businessLevel = businessLevelMapper.selectOne(Wrappers.<BusinessLevel>lambdaQuery()
.eq(BusinessLevel::getBusinessId, businessId));
if (businessLevel == null) {
businessLevel = new BusinessLevel();
businessLevel.setBusinessId(businessId);
businessLevel.setLevel(1);
businessLevel.setAverageScore(BigDecimal.valueOf(1));
}
businessLevel.setAverageScore(BigDecimal.valueOf(avg));
businessLevel.setLevel(level);
this.saveOrUpdate(businessLevel);
}
@Override
public List<BusinessLevel> findAllOrdered() {
List<BusinessLevel> list = businessLevelMapper.selectList(Wrappers.<BusinessLevel>lambdaQuery()
.orderByDesc(BusinessLevel::getLevel,BusinessLevel::getAverageScore)
.orderByAsc(BusinessLevel::getCreateTime));
return list;
}
private int calculateLevel(Double averageScore) {
if (averageScore >= 4.5) {
return 5;
} else if (averageScore >= 4.0) {
return 4;
} else if (averageScore >= 3.0) {
return 3;
} else if (averageScore >= 2.0) {
return 2;
} else {
return 1;
}
}
}

View File

@ -9,10 +9,12 @@ import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.model.domain.Business;
import com.bsz.school_send_back_end.model.domain.BusinessAuth;
import com.bsz.school_send_back_end.model.domain.BusinessLevel;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.dto.business.BusinessQueryRequest;
import com.bsz.school_send_back_end.model.vo.BusinessVO;
import com.bsz.school_send_back_end.service.BusinessAuthService;
import com.bsz.school_send_back_end.service.BusinessLevelService;
import com.bsz.school_send_back_end.service.BusinessService;
import com.bsz.school_send_back_end.mapper.BusinessMapper;
import com.bsz.school_send_back_end.service.UserService;
@ -27,7 +29,9 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@ -46,6 +50,12 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
@Resource
private BusinessAuthService businessAuthService;
@Resource
private BusinessLevelService businessLevelService;
@Resource
private BusinessMapper businessMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public synchronized void addBusiness(User user, Business business, BusinessAuth businessAuth) {
@ -200,5 +210,33 @@ public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business>
return business;
}
@Override
public List<BusinessVO> findAllBusiness() {
List<BusinessLevel> businessLevels = businessLevelService.findAllOrdered();
// 获取商家 ID 列表
List<Long> businessIds = businessLevels.stream()
.map(BusinessLevel::getBusinessId)
.distinct()
.collect(Collectors.toList());
List<Business> businesses = businessMapper.selectBatchIds(businessIds);
//将商家等级信息映射到商家实体
Map<Long, Integer> levelMap = businessLevels.stream()
.collect(Collectors.toMap(BusinessLevel::getBusinessId, BusinessLevel::getLevel));
// Step 5: 构建 BusinessVO 并将等级添加到商家数据中
List<BusinessVO> businessVOs = businesses.stream()
.map(business -> {
BusinessVO vo = new BusinessVO();
BeanUtils.copyProperties(business, vo); // 自动复制 Business BusinessVO
vo.setLevel(levelMap.getOrDefault(business.getId(), 1)); // 设置等级
return vo;
})
// Step 6: 按等级排序
.sorted(Comparator.comparingLong(BusinessVO::getLevel).reversed()) // 按等级降序排序
.collect(Collectors.toList());
return businessVOs;
}
}

View File

@ -119,7 +119,7 @@ public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes>
}
long count = getCount(dishes);
DishesVO dishesVO = new DishesVO();
BeanUtils.copyProperties(dishes, dishesVO);
if (count > 0) {
dishesVO.setIsSpecification(1);
}

View File

@ -0,0 +1,58 @@
package com.bsz.school_send_back_end.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsz.school_send_back_end.common.ErrorCode;
import com.bsz.school_send_back_end.exception.BusinessException;
import com.bsz.school_send_back_end.exception.ThrowUtils;
import com.bsz.school_send_back_end.model.domain.Orders;
import com.bsz.school_send_back_end.model.domain.User;
import com.bsz.school_send_back_end.model.domain.UserRating;
import com.bsz.school_send_back_end.service.OrdersService;
import com.bsz.school_send_back_end.service.UserRatingService;
import com.bsz.school_send_back_end.mapper.UserRatingMapper;
import com.bsz.school_send_back_end.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* @author pc
* @description 针对表user_rating(用户评分)的数据库操作Service实现
* @createDate 2024-11-29 22:23:08
*/
@Service
public class UserRatingServiceImpl extends ServiceImpl<UserRatingMapper, UserRating>
implements UserRatingService{
@Resource
private UserService userService;
@Resource
private OrdersService ordersService;
@Override
public void validUserRating(UserRating userRating, HttpServletRequest request) {
if (userRating.getRating() < 1 || userRating.getRating() > 5) {
throw new BusinessException(ErrorCode.PARAMS_ERROR, "分数不在可选范围内");
}
User loginUser = userService.getLoginUser(request);
if (!loginUser.getId().equals(userRating.getUserId())) {
throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "当前登录用户与评分中的用户不匹配");
}
Orders orders = ordersService.getOne(Wrappers.<Orders>lambdaQuery().eq(Orders::getId, userRating.getOrderId()));
ThrowUtils.throwIf(orders == null, ErrorCode.NOT_FOUND_ERROR, "订单不存在");
ThrowUtils.throwIf(!orders.getBusinessId().equals(userRating.getBusinessId()) ,ErrorCode.NOT_FOUND_ERROR, "该商家与订单商家不一致");
long count = this.count(Wrappers.<UserRating>lambdaQuery().eq(UserRating::getOrderId, userRating.getOrderId()));
ThrowUtils.throwIf(count > 0, ErrorCode.SYSTEM_ERROR, "该订单已评分");
}
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bsz.school_send_back_end.mapper.BusinessLevelMapper">
<resultMap id="BaseResultMap" type="com.bsz.school_send_back_end.model.domain.BusinessLevel">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="businessId" column="businessId" jdbcType="BIGINT"/>
<result property="averageScore" column="averageScore" jdbcType="DECIMAL"/>
<result property="level" column="level" jdbcType="TINYINT"/>
<result property="createTime" column="createTime" jdbcType="TIMESTAMP"/>
<result property="updateTime" column="updateTime" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List">
id,businessId,averageScore,
level,createTime,updateTime
</sql>
</mapper>

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bsz.school_send_back_end.mapper.UserRatingMapper">
<resultMap id="BaseResultMap" type="com.bsz.school_send_back_end.model.domain.UserRating">
<id property="id" column="id" jdbcType="BIGINT"/>
<result property="businessId" column="businessId" jdbcType="BIGINT"/>
<result property="userId" column="userId" jdbcType="BIGINT"/>
<result property="orderId" column="orderId" jdbcType="BIGINT"/>
<result property="rating" column="rating" jdbcType="TINYINT"/>
<result property="createTime" column="createTime" jdbcType="TIMESTAMP"/>
</resultMap>
<sql id="Base_Column_List">
id,businessId,userId,
orderId,rating,createTime
</sql>
</mapper>

View File

@ -1,13 +1,14 @@
package com.bsz.school_send_back_end;
import com.bsz.school_send_back_end.utils.UniqueNumberGenerator;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UserCenterApplicationTests {
@Test
void contextLoads() {
public static void main(String[] args) {
System.out.println(UniqueNumberGenerator.generateNumber());
}
}