无卡消费 后端你代码完成

parents
Pipeline #161 failed with stages
# Created by .ignore support plugin (hsz.mobi)
### Example user template template
### Example user template
# IntelliJ project files
.idea
.idea/*
*.iml
out
gen
/rebel.xml
/logs/*
/target
### Java template
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>card-consume</artifactId>
<groupId>cn.wise.sc.cmbapp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>consume-business</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<!--<version>5.1.45</version>-->
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>cn.wise.sc.cmbapp</groupId>
<artifactId>common-swagger</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<!--*******************************************-->
<!--招行app使用-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.8</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk16</artifactId>
<version>1.46</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<!--腾讯短信依赖-->
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>zip</nonFilteredFileExtension>
<nonFilteredFileExtension>cer</nonFilteredFileExtension>
<nonFilteredFileExtension>pfx</nonFilteredFileExtension>
<nonFilteredFileExtension>py</nonFilteredFileExtension>
<nonFilteredFileExtension>keystore</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>*.xlsx</include>
<include>*</include>
</includes>
</resource>
<resource>
<directory>src/main/java/cn/wise/sc/consume/business/mapper/xml</directory>
<filtering>true</filtering>
<includes>
<include>*.xml</include>
</includes>
<targetPath>cn/wise/sc/consume/business/mapper</targetPath>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
package cn.wise.sc.consume.business;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.TimeZone;
/**
* 启动类
*
* @author zhutianwei
*
*/
@SpringBootApplication
@MapperScan("cn.wise.sc.consume.business.mapper")
public class SecurityApplication {
public static void main(String[] args) {
// 系统默认的时区
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
SpringApplication.run(SecurityApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
package cn.wise.sc.consume.business.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Configuration
public class DateConfig {
/** 默认日期时间格式 */
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/** 默认日期格式 */
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/** 默认时间格式 */
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
/**
* LocalDate转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDate> localDateConverter() {
return new Converter<String, LocalDate>() {
@Override
public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
}
};
}
/**
* LocalDateTime转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalDateTime> localDateTimeConverter() {
return new Converter<String, LocalDateTime>() {
@Override
public LocalDateTime convert(String source) {
return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
}
};
}
/**
* LocalTime转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, LocalTime> localTimeConverter() {
return new Converter<String, LocalTime>() {
@Override
public LocalTime convert(String source) {
return LocalTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
}
};
}
/**
* Date转换器,用于转换RequestParam和PathVariable参数
*/
@Bean
public Converter<String, Date> dateConverter() {
return new Converter<String, Date>() {
@Override
public Date convert(String source) {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
try {
return format.parse(source);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
};
}
/**
* Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
*/
@Bean
public ObjectMapper objectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//ObjectMapper忽略多余字段
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class,new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//Date序列化和反序列化
javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String formattedDate = formatter.format(date);
jsonGenerator.writeString(formattedDate);
}
});
javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String date = jsonParser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
// 注册新的模块到objectMapper
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* @date :Created in 2019-03-21 10:21
* @description:用途:
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static {
//解决fastJson autoType is not support错误
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
package cn.wise.sc.consume.business.config;
import cn.wise.sc.consume.business.exception.BusinessException;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@ControllerAdvice
@RestController
public class GlobalDefaultExceptionHandler extends AbstractErrorController {
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public Wrapper defaultErrorHandler(HttpServletResponse response, BusinessException e) {
response.setStatus(e.getStatusCode().value());
return WrapMapper.error(e.getMessage());
}
public GlobalDefaultExceptionHandler(ErrorAttributes errorAttributes) {
super(errorAttributes);
}
private static final String ERROR_PATH = "/error";
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public Wrapper error(HttpServletRequest request) {
WebRequest webRequest = new ServletWebRequest(request);
Throwable e = getError(webRequest);
if (e == null) {
Map<String, Object> attributes = getErrorAttributes(request, false);
Object timestamp = attributes.get("timestamp");
Object status = attributes.get("status");
String error = attributes.get("error").toString();
String message = attributes.get("message").toString();
Object path = attributes.get("path");
//todo 上线后更改为error
return WrapMapper.wrap(Integer.parseInt(status.toString()), message);
}else {
return WrapMapper.error(e.getMessage());
}
}
private Throwable getError(WebRequest webRequest) {
return (Throwable) this.getAttribute(webRequest, "javax.servlet.error.exception");
}
private Object getAttribute(RequestAttributes requestAttributes, String name) {
return requestAttributes.getAttribute(name, 0);
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class MapStringTypeHandler<T> extends BaseTypeHandler<Map<String, T>> {
private Class<T> clazz;
//private static final TypeReference<HashMap<String, String>> mapStrStrTypeRef = new TypeReference<HashMap<String, String>>(){};
private final TypeReference<HashMap<String, T>> typeRef = new TypeReference<HashMap<String, T>>() {
};
public MapStringTypeHandler(Class<T> clazz) {
this.clazz = clazz;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Map<String, T> parameter, JdbcType jdbcType) throws SQLException {
String json = JSON.toJSONString(parameter);
ps.setString(i, json);
}
@Override
public Map<String, T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parseJson(rs.getString(columnName));
}
@Override
public Map<String, T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parseJson(rs.getString(columnIndex));
}
@Override
public Map<String, T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parseJson(cs.getString(columnIndex));
}
private Map<String, T> parseJson(String json) {
if (String.class == clazz || Integer.class == clazz || Boolean.class == clazz) {
return JSON.parseObject(json, typeRef);
}
Map<String, T> result = new HashMap<>();
JSON.parseObject(json).forEach((k, v) -> result.put(k, JSON.parseObject(JSON.toJSONString(v), clazz)));
return result;
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author miemie
* @since 2018-08-10
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
// 开启 count 的 join 优化,只针对 left join !!!
return new PaginationInterceptor().setCountSqlParser(new JsqlParserCountOptimize(true));
}
}
package cn.wise.sc.consume.business.config;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @description:用途: @EnableCaching 开启声明式缓存支持. 之后就可以使用 @Cacheable/@CachePut/@CacheEvict 注解缓存数据.
*/
@Configuration
@EnableCaching
public class RedisCacheConfig {
private RedisConnectionFactory redisConnectionFactory;
public RedisCacheConfig(RedisConnectionFactory redisConnectionFactory) {
this.redisConnectionFactory = redisConnectionFactory;
}
// @Bean
// public Jedis jedis() {
// JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// jedisPoolConfig.setMaxTotal(80);
// jedisPoolConfig.setMinIdle(20);
// jedisPoolConfig.setMaxIdle(80);
// JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379);
// return jedisPool.getResource();
// }
/**
* 覆盖默认的配置
*
* @return RedisTemplate
*/
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// 设置value的序列化规则和key的序列化规则
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(fastJsonRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(fastJsonRedisSerializer);
template.setDefaultSerializer(fastJsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
/**
* 解决注解方式存放到redis中的值是乱码的情况
*
* @param factory
* @return CacheManager
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);
// 配置注解方式的序列化
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
RedisCacheConfiguration redisCacheConfiguration =
config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
//配置注解默认的过期时间
.entryTtl(Duration.ofDays(1));
// 加入白名单 https://github.com/alibaba/fastjson/wiki/enable_autotype
ParserConfig.getGlobalInstance().addAccept("cn.wise");
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
}
}
package cn.wise.sc.consume.business.config;
import cn.wise.sc.consume.business.util.GlobalHolder;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 上下文初始化
* 以及跨域的支持
*/
public class RequestInterceptor extends HandlerInterceptorAdapter {
/**
* 拦截request和response并放到上下文中
* @param request 要拦截的request
* @param response 要拦截的response
* @param handler spring 机制传递过来的
* @return 不中断,继续执行,返回为true
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
//request 和response存到 上下文中
GlobalHolder.setHttpResponse(response);
GlobalHolder.setHttpRequest(request);
return super.preHandle(request, response, handler);
}
/**
* 处理完成 从上下文中移除 request 和respseon
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
GlobalHolder.remove();
super.afterCompletion(request, response, handler, ex);
}
}
package cn.wise.sc.consume.business.config;
import cn.wise.sc.consume.business.security.*;
import cn.wise.sc.consume.business.security.jwt.JwtAuthenticationProvider;
import cn.wise.sc.consume.business.security.jwt.JwtUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.header.Header;
import org.springframework.security.web.header.writers.StaticHeadersWriter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
/**
* spring security配置
*
* @author zhutianwei
*/
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// 基于token,所以不需要session
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests()
.antMatchers("/", "/*.html", "/favicon.ico", "/css/**", "/js/**", "/fonts/**", "/layui/**", "/img/**",
"/v2/api-docs/**", "/swagger-resources/**", "/webjars/**", "/pages/**", "/druid/**",
"/statics/**", "/login/**","/test-websocket/**","/testWebsocket/**","/common/**","/cmbOneNet/**")
.permitAll().anyRequest().authenticated()
.and()
.formLogin().disable()
.sessionManagement().disable()
.cors()
.and()
.headers()
.addHeaderWriter(
new StaticHeadersWriter(
Arrays.asList(
new Header("Access-control-Allow-Origin", "*"),
new Header("Access-Control-Expose-Headers", "Authorization"))))
.and()
.addFilterAfter(new OptionsRequestFilter(), CorsFilter.class)
.apply(new JsonLoginConfigurer<>()).loginSuccessHandler(jsonLoginSuccessHandler())
.and()
.apply(new JwtLoginConfigurer<>()).tokenValidSuccessHandler(jwtRefreshSuccessHandler())
.and()
.logout()
// .logoutUrl("/logout") //默认就是"/logout"
.addLogoutHandler(tokenClearLogoutHandler())
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
.and()
.sessionManagement().disable();
// 解决不允许显示在iframe的问题
http.headers().frameOptions().disable();
http.headers().cacheControl();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder())
.and().authenticationProvider(jwtAuthenticationProvider());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean("jwtAuthenticationProvider")
protected AuthenticationProvider jwtAuthenticationProvider() {
return new JwtAuthenticationProvider(userService);
}
@Bean("daoAuthenticationProvider")
protected AuthenticationProvider daoAuthenticationProvider() throws Exception {
//这里会默认使用BCryptPasswordEncoder比对加密后的密码,注意要跟createUser时保持一致
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setUserDetailsService(userDetailsService());
return daoProvider;
}
@Autowired
JwtUserService userService;
@Override
protected UserDetailsService userDetailsService() {
return userService;
}
@Bean
protected JsonLoginSuccessHandler jsonLoginSuccessHandler() {
return new JsonLoginSuccessHandler(userService);
}
@Bean
protected JwtRefreshSuccessHandler jwtRefreshSuccessHandler() {
return new JwtRefreshSuccessHandler(userService);
}
@Bean
protected TokenClearLogoutHandler tokenClearLogoutHandler() {
return new TokenClearLogoutHandler(userService);
}
@Bean
protected CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "HEAD", "OPTION"));
configuration.setAllowedHeaders(Arrays.asList("*"));
configuration.addExposedHeader("Authorization");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
package cn.wise.sc.consume.business.config;
import cn.wise.sc.consume.business.filter.SwaggerInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.MappedInterceptor;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "cn.wise.sc.consume";
public static final String VERSION = "1.0.0";
/*@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("swagger接口文档")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.enableUrlTemplating(false)
.build(); //.host("192.168.110.84/consume");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger接口文档") //设置文档的标题
.contact(new Contact("Wisenergy", "http://www.wisenergy.cn/", "service@wisenergy.cn"))
.description("cmb接口服务 API 接口文档") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.termsOfServiceUrl("http://www.wisenergy.cn") // 设置文档的License信息->1.3 License information
.build();
}
*/
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).groupName("swagger接口文档")
.apiInfo(new ApiInfoBuilder().title("swagger接口文档")
.contact(new Contact("Wisenergy", "http://www.wisenergy.cn/", "service@wisenergy.cn")).version("1.0").build())
.select().paths(PathSelectors.any()).build()
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.enableUrlTemplating(false)
;
}
private ApiKey apiKey() {
return new ApiKey("BearerToken", "Authorization", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/.*"))
.build();
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(new SecurityReference("BearerToken", authorizationScopes));
}
@Value("${swagger.basic.username}")
private String username;
@Value("${swagger.basic.password}")
private String password;
/* 必须在此处配置拦截器,要不然拦不到swagger的静态资源 */
@Bean
@ConditionalOnProperty(name = "swagger.basic.enable", havingValue = "true")
public MappedInterceptor getMappedInterceptor() {
return new MappedInterceptor(new String[]{"/swagger-ui.html", "/webjars/**"}, new SwaggerInterceptor(username, password));
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.config;
/**
* top地址相关配置
*
* @author openapi@dingtalk
* @date 2020/2/4
*/
public class UrlConstant {
private static final String HOST = "https://oapi.dingtalk.com";
/**
* 钉钉网关 gettoken 地址
*/
public static final String URL_GET_TOKEN = HOST + "/gettoken";
/**
* 获取 jsapi_ticket 地址
*/
public static final String URL_GET_JSTICKET = HOST + "/get_jsapi_ticket";
/**
* 获取用户在企业内 userId 的接口URL
*/
public static final String URL_GET_USER_INFO = HOST + "/user/getuserinfo";
/**
* 获取用户姓名的接口URL
*/
public static final String URL_USER_GET = HOST + "/user/get";
/**
* 获取部门列表接口URL
*/
public static final String URL_DEPARTMENT_LIST = HOST + "/department/list";
/**
* 获取部门用户接口URL
*/
public static final String URL_USER_SIMPLELIST = HOST + "/user/simplelist";
}
package cn.wise.sc.consume.business.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 加载自定义的 拦截器
*/
@Configuration
public class WebInterceptorConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**");
}
}
package cn.wise.sc.consume.business.config.lock;
import org.redisson.api.RLock;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
public interface DistributedLocker {
RLock lock(String lockKey);
RLock lock(String lockKey, int timeout);
RLock lock(String lockKey, TimeUnit unit, int timeout);
boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime);
void unlock(String lockKey);
void unlock(RLock lock);
<T> T executeLock(String key, Function<String, T> consumer, String t);
<T> void executeLock(String lockKey, Consumer<T> consumer, T t);
}
\ No newline at end of file
package cn.wise.sc.consume.business.config.lock;
import org.redisson.api.RLock;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
public class RedissLockUtil {
private static DistributedLocker redissLock;
public static void setLocker(DistributedLocker locker) {
redissLock = locker;
}
public static RLock lock(String lockKey) {
return redissLock.lock(lockKey);
}
public static <T> T readWriteLock(String lockKey, Function<String,T> function) {
return redissLock.executeLock(lockKey,function,null);
}
public static <T> void playersLock(String lockKey, Consumer<T> consumer,T t){
redissLock.executeLock(lockKey,consumer,null);
}
public static void unlock(String lockKey) {
redissLock.unlock(lockKey);
}
public static void unlock(RLock lock) {
redissLock.unlock(lock);
}
public static RLock lock(String lockKey, int timeout) {
return redissLock.lock(lockKey, timeout);
}
public static RLock lock(String lockKey, TimeUnit unit , int timeout) {
return redissLock.lock(lockKey, unit, timeout);
}
public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
return redissLock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
}
public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
return redissLock.tryLock(lockKey, unit, waitTime, leaseTime);
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.config.lock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
@Slf4j
public class RedissonDistributedLocker implements DistributedLocker {
private RedissonClient redissonClient;
@Override
public RLock lock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock();
return lock;
}
@Override
public RLock lock(String lockKey, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(leaseTime, TimeUnit.SECONDS);
return lock;
}
@Override
public RLock lock(String lockKey, TimeUnit unit, int timeout) {
RLock lock = redissonClient.getLock(lockKey);
lock.lock(timeout, unit);
return lock;
}
@Override
public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
RLock lock = redissonClient.getLock(lockKey);
try {
return lock.tryLock(waitTime, leaseTime, unit);
} catch (InterruptedException e) {
return false;
}
}
public static void realeaseLock(RLock fairLock) {
fairLock.unlock();
}
@Override
public void unlock(String lockKey) {
RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
}
@Override
public void unlock(RLock lock) {
lock.unlock();
}
@Override
public <T> T executeLock(String key, Function<String, T> function, String t) {
RLock lock = redissonClient.getLock(key);
boolean locked = false;
try {
lock.lock();
return (T) function.apply(t);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
@Override
public <T> void executeLock(String lockKey, Consumer<T> consumer, T t) {
RLock lock = redissonClient.getLock(lockKey);
boolean locked = false;
try {
while (true) {
locked = lock.tryLock();
if (locked) break;
}
if (locked) {
consumer.accept(t);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (locked) {
lock.unlock();
}
}
}
public void setRedissonClient(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.controller;
import cn.wise.sc.consume.business.util.UserUtil;
import cn.wise.sc.consume.business.util.dfs.FastDFSUtils;
import cn.wise.sc.consume.business.util.dfs.FileTypeUtil;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 附件管理Controller
* @author ztw
*/
@Api(tags = "附件管理")
@RestController
@RequestMapping("/enclosure")
public class EntityEnclosureController {
private static final Logger logger = LoggerFactory.getLogger("adminLogger");
@Autowired
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
@ApiOperation(value = "单个文件上传")
@PostMapping("/fileUpLoad")
public Wrapper fileUpLoad(MultipartFile file){
Map<String,Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
Long userId = UserUtil.getLoginUser().getId();
if(userId != null){
filePath = FastDFSUtils.uploadPic(file.getBytes(),file.getOriginalFilename(),file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}else {
return WrapMapper.wrap(400,"该账号已在其他地方登陆");
}
String picUrl = filePath;
map.put("fileUrl",picUrl);
map.put("fileName",fileName);
map.put("extName",extName);
return WrapMapper.wrap(200,"成功", map);
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "单个图片上传")
@PostMapping("/imgUpLoad")
public Wrapper imgUpLoad(MultipartFile file){
Map<String,Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
Long userId = UserUtil.getLoginUser().getId();
if(userId != null){
if(!FileTypeUtil.isImageByExtension(file.getOriginalFilename())){
return WrapMapper.wrap(400,"请上传有效图片");
}
filePath = FastDFSUtils.uploadPic(file.getBytes(),file.getOriginalFilename(),file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
}else {
return WrapMapper.wrap(400,"该账号已在其他地方登陆");
}
String picUrl = filePath;
map.put("fileUrl",picUrl);
map.put("fileName",fileName);
map.put("extName",extName);
return WrapMapper.wrap(200,"成功", map);
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "多个文件上传")
@PostMapping("/filesUpLoad")
public Wrapper filesUpLoad(HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
List<MultipartFile> files = null;
String filePath = null;
String fileName = null;
String extName = null;
List<Map<String,Object>> filePathList = null;
try {
filePathList = new ArrayList<>();
files = ((MultipartHttpServletRequest)request).getFiles("files");
Long userId = UserUtil.getLoginUser().getId();
if(userId != null){
if(files != null && files.size() > 0) {
for (MultipartFile file : files) {
Map<String,Object> mapSub = new HashMap<>();
filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String picUrl = filePath;
mapSub.put("fileUrl",picUrl);
mapSub.put("fileName",fileName);
mapSub.put("extName",extName);
filePathList.add(mapSub);
}
}else {
return WrapMapper.wrap(400,"没有文件");
}
}else {
return WrapMapper.wrap(400,"该账号已在其他地方登陆");
}
map.put("status",200);
map.put("message","上传成功");
map.put("filePathList",filePathList);
return WrapMapper.wrap(200,"成功", filePathList);
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "单个文件下载")
@PostMapping("/fileDownload")
public Wrapper fileDownload(String fileUrl,String fileName,String extName){
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename="+fileName+extName);
response.setContentType("application/force-download");
out = response.getOutputStream();
Long userId = UserUtil.getLoginUser().getId();
if(userId != null){
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
}else {
return WrapMapper.wrap(400,"该账号已在其他地方登陆");
}
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "app扫描二维码下载")
@GetMapping("/appDownload")
public Wrapper appDownload(String fileUrl){
Map<String,Object> map = new HashMap<>();
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=app-release.apk");
response.setContentType("application/force-download");
out = response.getOutputStream();
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "删除相关文件")
@PostMapping("/fileDeleted")
public Wrapper fileDeleted(String[] filePaths){
Map<String,Object> map = new HashMap<>();
String filePath = null;
boolean rel = false;
try {
Long userId = UserUtil.getLoginUser().getId();
if(userId != null){
for(String url : filePaths){
/*filePath = url.substring(0,url.indexOf("g"));*/
rel = FastDFSUtils.deletePic(url);
if(!rel){
return WrapMapper.wrap(400,"删除失败");
}
}
}else {
return WrapMapper.wrap(400,"该账号已在其他地方登陆");
}
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
logger.error(e.toString());
}
return WrapMapper.error("失败");
}
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-30
*/
@RestController
@RequestMapping("/business/sms-auth")
public class SmsAuthController {
}
package cn.wise.sc.consume.business.controller;
import cn.wise.sc.consume.business.entity.SysCoupon;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.entity.SysUser;
import cn.wise.sc.consume.business.mapper.SysCouponDetailMapper;
import cn.wise.sc.consume.business.model.CouponDetailDTO;
import cn.wise.sc.consume.business.model.CouponDetailVO;
import cn.wise.sc.consume.business.model.CouponListVO;
import cn.wise.sc.consume.business.model.PageTableRequest;
import cn.wise.sc.consume.business.service.ISysCouponDetailService;
import cn.wise.sc.consume.business.service.ISysCouponService;
import cn.wise.sc.consume.business.service.impl.CommonService;
import cn.wise.sc.consume.business.util.ExcelUtil;
import cn.wise.sc.consume.business.util.UserUtil;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Api(tags = "优惠券管理")
@RestController
@RequestMapping("/business/sys-coupon")
public class SysCouponController {
private static final Logger log = LoggerFactory.getLogger("SysCouponController");
@Autowired
private ISysCouponService couponService;
@Autowired
private ISysCouponDetailService couponDetailService;
@Autowired
private SysCouponDetailMapper couponDetailMapper;
@Autowired
private CommonService commonService;
@ApiOperation(value = "优惠券列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "current", value = "当前页数(从1开始)", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "size", value = "当前每页显示数", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "couponName", value = "优惠券名称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "enterpriseId", value = "所属企业", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "status", value = "状态:0禁用, 1启用", paramType = "query", dataType = "Integer")
})
@GetMapping("getCouponPage")
public Wrapper getCouponPage(PageTableRequest request, String couponName, Long enterpriseId, Integer status) {
try {
couponDetailService.beVerdue();
Page<CouponListVO> page = new Page<>(request.getCurrent(), request.getSize());
Map<String, Object> map = new HashMap<>();
map.put("couponName", couponName);
map.put("enterpriseId", enterpriseId);
map.put("status", status);
List<CouponListVO> couponListVOS = couponService.getPage(map);
page.setRecords(couponListVOS).setTotal(couponListVOS.size());
return WrapMapper.wrap(200,"成功",page);
} catch (Exception e) {
log.debug("优惠券列表{}", e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "添加优惠券")
@PostMapping("/saveCoupon")
public Wrapper saveCoupon(@RequestBody SysCoupon coupon){
try {
coupon.setStatus(1);
coupon.setIsDelete(1);
coupon.setCreateTime(LocalDateTime.now());
couponService.save(coupon);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("添加优惠券{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "修改优惠券")
@PostMapping("/updateCoupon")
public Wrapper updateCoupon(@RequestBody SysCoupon coupon){
try {
SysCoupon c = couponService.getById(coupon.getId());
if(c == null){
return WrapMapper.wrap(400,"信息错误");
}
couponService.updateById(coupon);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("修改优惠券{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "优惠券详情")
@GetMapping("coupon/{id}")
public Wrapper getCouponById(@PathVariable Long id){
try {
CouponDetailVO c = couponService.getCouponDetail(id);
if(c == null){
return WrapMapper.wrap(400,"信息错误");
}
return WrapMapper.wrap(200,"成功",c);
}catch (Exception e){
log.debug("优惠券详情{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "修改优惠券状态")
@PostMapping("/updateStatus/{id}")
public Wrapper updateStatus(@PathVariable Long id) {
try {
SysCoupon e = couponService.getById(id);
if (e == null ) {
return WrapMapper.wrap(400,"优惠券不存在");
}
Integer status = e.getStatus()==0?1:0;
e.setStatus(status);
couponService.updateById(e);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("修改优惠券状态{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "删除优惠券")
@PostMapping("/deleteCoupon/{id}")
public Wrapper deleteCoupon(@PathVariable Long id) {
try {
SysCoupon c = couponService.getById(id);
if (c == null ) {
return WrapMapper.wrap(400,"优惠券不存在");
}
c.setIsDelete(0);
c.setStatus(0);
couponService.updateById(c);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("删除优惠券{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "优惠券详情列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "current", value = "当前页数(从1开始)", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "size", value = "当前每页显示数", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "isReceive", value = "票券状态:0未领取,1已领取,2已过期", paramType = "query", dataType = "Integer"),
@ApiImplicitParam(name = "couponId", value = "优惠券表id", paramType = "query", dataType = "Long")
})
@GetMapping("/getCouponDetailPage")
public Wrapper getCouponDetailPage(PageTableRequest request, Integer isReceive, Long couponId) {
try {
if(couponId == null){
return WrapMapper.wrap(400,"请选择优惠券信息");
}
QueryWrapper<SysCouponDetail> wrapper = new QueryWrapper<>();
wrapper.eq("coupon_id", couponId);
if (isReceive != null) {
wrapper.eq("is_receive", isReceive);
}
wrapper.eq("is_delete", 1);
wrapper.orderByDesc("cmb_no");
IPage<SysCouponDetail> page = new Page<>(request.getCurrent(), request.getSize());
page = couponDetailMapper.selectPage(page, wrapper);
return WrapMapper.wrap(200, "成功", page);
} catch (Exception e) {
log.debug("优惠券详情列表{}", e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "添加优惠券详情")
@PostMapping("/saveCouponDetail")
public Wrapper saveCouponDetail(@RequestBody CouponDetailDTO couponDetailDTO){
try {
int counts = couponDetailMapper.createNo();
SysCouponDetail couponDetail = new SysCouponDetail();
couponDetail.setCouponId(couponDetailDTO.getCouponId())
.setCmbNo(commonService.createNo("cmb_",counts))
.setCouponCode(couponDetailDTO.getCouponCode())
.setStartDate(couponDetailDTO.getStartDate())
.setEndDate(couponDetailDTO.getEndDate())
.setIsReceive(0)
.setCreateTime(LocalDateTime.now())
.setIsDelete(1)
.setRemark(couponDetailDTO.getRemark());
couponDetailService.save(couponDetail);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("添加优惠券详情{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "修改优惠券详情")
@PostMapping("/updateCouponDetail")
public Wrapper updateCouponDetail(@RequestBody CouponDetailDTO couponDetailDTO){
try {
SysCouponDetail couponDetail = couponDetailService.getById(couponDetailDTO.getId());
if(couponDetail == null){
return WrapMapper.wrap(400,"信息错误");
}
couponDetail.setStartDate(couponDetailDTO.getStartDate())
.setEndDate(couponDetailDTO.getEndDate())
.setIsReceive(0)
.setRemark(couponDetailDTO.getRemark());
couponDetailService.updateById(couponDetail);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("修改优惠券详情{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "单张优惠券详情")
@GetMapping("couponDetail/{id}")
public Wrapper getcouponDetailById(@PathVariable Long id){
try {
SysCouponDetail couponDetail = couponDetailService.getById(id);
if(couponDetail == null){
return WrapMapper.wrap(400,"信息错误");
}
return WrapMapper.wrap(200,"成功",couponDetail);
}catch (Exception e){
log.debug("优惠券详情{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "删除单张优惠券详情")
@PostMapping("/deleteCouponDetail/{id}")
public Wrapper deleteCouponDetail(@PathVariable Long id) {
try {
SysCouponDetail couponDetail = couponDetailService.getById(id);
if (couponDetail == null ) {
return WrapMapper.wrap(400,"优惠券详情不存在");
}
couponDetail.setIsDelete(0);
couponDetailService.updateById(couponDetail);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("删除单张优惠券详情{}",e);
}
return WrapMapper.error("失败");
}
protected void download(Resource resource, HttpServletResponse response) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
response.setHeader("Content-Disposition", "attachment;filename="+ new String((resource.getFilename()).getBytes(), "iso-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
InputStream in = null;
OutputStream out = null;
try {
in = resource.getInputStream();
int len = 0;
byte[] buffer = new byte[1024];
out = response.getOutputStream();
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@ApiOperation(value = "下载优惠券模版", httpMethod = "GET", notes = "下载优惠券模版")
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response) throws IOException {
Resource resource = new ClassPathResource("couponDetail.xlsx");
download(resource, response);
}
@ApiOperation(value = "导入优惠券信息", httpMethod = "POST", notes = "导入优惠券信息")
@RequestMapping(value = "/importCouponDetail", method = RequestMethod.POST)
public Wrapper importCouponDetail( @RequestBody MultipartFile file,Long couponId) {
// 当前登录用户
SysUser sysUser = UserUtil.getLoginUser();
if (sysUser == null) {// 用户不存在
return WrapMapper.wrap(400,"用户不存在");
}
if(couponId == null){
return WrapMapper.wrap(400,"请选择优惠券信息");
}
try {
InputStream in = file.getInputStream();
List<Map<Integer, String>> conponDetailmp = ExcelUtil.readData((FileInputStream) in);
List<SysCouponDetail> conponDetailList = new ArrayList<>();
for (Map<Integer, String> hm : conponDetailmp) {
SysCouponDetail couponDetail = new SysCouponDetail();
if ((hm.get(0) == null || "".equals(hm.get(0))) &&
(hm.get(1) == null || "".equals(hm.get(1))) &&
(hm.get(2) == null || "".equals(hm.get(2))) &&
(hm.get(3) == null || "".equals(hm.get(3))) &&
(hm.get(4) == null || "".equals(hm.get(4)))
) {
continue;
}
if (hm.get(0) == null || "".equals(hm.get(0)) ||
hm.get(1) == null || "".equals(hm.get(1)) ||
hm.get(2) == null || "".equals(hm.get(2)) ||
hm.get(3) == null || "".equals(hm.get(3))
) {
return WrapMapper.wrap(400,"数据信息错误");
}
couponDetail.setCouponCode(hm.get(1))
.setStartDate(LocalDate.parse(hm.get(2), DateTimeFormatter.ofPattern("yyyy/MM/dd")))
.setEndDate(LocalDate.parse(hm.get(3), DateTimeFormatter.ofPattern("yyyy/MM/dd")))
.setRemark(hm.get(4));
conponDetailList.add(couponDetail);
}
for (SysCouponDetail couponDetail : conponDetailList) {
int counts = couponDetailMapper.createNo();
couponDetail.setCouponId(couponId)
.setCmbNo(commonService.createNo("cmb_",counts))
.setIsReceive(0)
.setCreateTime(LocalDateTime.now())
.setIsDelete(1);
couponDetailService.save(couponDetail);
}
return WrapMapper.wrap(200,"成功");
} catch (Exception e) {
e.printStackTrace();
log.debug("导入发票信息{}",e);
}
return WrapMapper.error("失败");
}
}
package cn.wise.sc.consume.business.controller;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.mapper.SysEnterpriseMapper;
import cn.wise.sc.consume.business.model.PageTableRequest;
import cn.wise.sc.consume.business.service.ISysEnterpriseService;
import cn.wise.sc.consume.business.util.RedisUtil;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-06-17
*/
@Api(tags = "企业管理")
@RestController
@RequestMapping("/business/sys-enterprise")
public class SysEnterpriseController {
private static final Logger log = LoggerFactory.getLogger("SysEnterpriseController");
@Autowired
RedisUtil redisUtil;
@Autowired
private ISysEnterpriseService enterpriseService;
@Resource
private SysEnterpriseMapper enterpriseMapper;
public String redisExample() {
redisUtil.setString("token", new Object(), 2000);
return "sucess";
}
@ApiOperation(value = "企业列表")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "current", value = "当前页数(从1开始)", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "size", value = "当前每页显示数", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "enterpriseName", value = "企业名称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "status", value = "状态:0禁用, 1启用,2待审批", paramType = "query", dataType = "Integer")
})
@GetMapping("/getList")
public Wrapper getList(PageTableRequest request, String enterpriseName, Integer status) {
try {
QueryWrapper<SysEnterprise> wrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(enterpriseName)) {
wrapper.like("enterprise_name", enterpriseName);
}
if (status != null) {
wrapper.eq("status", status);
}
wrapper.eq("is_delete", 1);
wrapper.orderByDesc("create_time");
IPage<SysEnterprise> page = new Page<>(request.getCurrent(), request.getSize());
page = enterpriseMapper.selectPage(page, wrapper);
return WrapMapper.wrap(200, "成功", page);
} catch (Exception e) {
log.debug("企业列表{}", e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "添加企业")
@PostMapping("/save")
public Wrapper save(@RequestBody SysEnterprise enterprise){
try {
enterprise.setStatus(1);
enterprise.setIsDelete(1);
enterprise.setCreateTime(LocalDateTime.now());
enterpriseService.save(enterprise);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("添加企业{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "修改企业")
@PostMapping("/update")
public Wrapper update(@RequestBody SysEnterprise enterprise){
try {
SysEnterprise e = enterpriseService.getById(enterprise.getId());
if(e == null){
return WrapMapper.wrap(400,"信息错误");
}
enterpriseService.updateById(enterprise);
return WrapMapper.wrap(200,"成功");
}catch (Exception e){
log.debug("修改企业{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "企业详情")
@GetMapping("{id}")
public Wrapper getById(@PathVariable Long id){
try {
SysEnterprise e = enterpriseService.getById(id);
if(e == null){
return WrapMapper.wrap(400,"信息错误");
}
return WrapMapper.wrap(200,"成功",e);
}catch (Exception e){
log.debug("企业详情{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "修改企业状态")
@PostMapping("/updateStatus/{id}")
public Wrapper updateStatus(@PathVariable Long id) {
try {
SysEnterprise e = enterpriseService.getById(id);
if (e == null ) {
return WrapMapper.wrap(400,"企业不存在");
}
Integer status = e.getStatus()==0?1:0;
e.setStatus(status);
enterpriseService.updateById(e);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("修改企业状态{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "删除企业")
@PostMapping("/{id}")
public Wrapper delete(@PathVariable Long id) {
try {
SysEnterprise e = enterpriseService.getById(id);
if (e == null ) {
return WrapMapper.wrap(400,"企业不存在");
}
e.setStatus(0);
e.setIsDelete(0);
enterpriseService.updateById(e);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("删除企业{}",e);
}
return WrapMapper.error("失败");
}
@ApiOperation(value = "审批企业入驻申请")
@PostMapping("/approval")
public Wrapper approval(Long id) {
try {
SysEnterprise e = enterpriseService.getById(id);
if (e == null ) {
return WrapMapper.wrap(400,"企业不存在");
}
e.setStatus(1);
enterpriseService.updateById(e);
return WrapMapper.wrap(200,"成功");
}catch (Exception e) {
log.debug("审批企业入驻申请{}",e);
}
return WrapMapper.error("失败");
}
//****************************************************************************************************
/*@ApiOperation(value = "企业列表(自定义sql实现)")
@ApiImplicitParams(value = {
@ApiImplicitParam(name = "current", value = "当前页数(从1开始)", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "size", value = "当前每页显示数", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "enterpriseName", value = "企业名称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "status", value = "状态:0禁用, 1启用", paramType = "query", dataType = "Integer")
})
@GetMapping("getList1")
public Wrapper getList1(PageTableRequest request, String enterpriseName, Integer status){
try {
Page<SysEnterprise> page = new Page<>(request.getCurrent(), request.getSize());
Map<String, Object> map = new HashMap<>();
map.put("enterpriseName", enterpriseName);
map.put("status", status);
List<SysEnterprise> enterpriseList = enterpriseService.getPage(map);
page.setRecords(enterpriseList).setTotal(enterpriseList.size());
return WrapMapper.wrap(200,"成功",page);
}catch (Exception e){
log.debug("企业列表{}",e);
}
return WrapMapper.error("失败");
}*/
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-29
*/
@RestController
@RequestMapping("/business/sys-logs")
public class SysLogsController {
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-08-03
*/
@RestController
@RequestMapping("/business/sys-member")
public class SysMemberController {
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@RestController
@RequestMapping("/business/sys-permission")
public class SysPermissionController {
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@RestController
@RequestMapping("/business/sys-role")
public class SysRoleController {
}
package cn.wise.sc.consume.business.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 前端控制器
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@RestController
@RequestMapping("/business/sys-user")
public class SysUserController {
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-03
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class RefEntityEnclosure implements Serializable {
private static final long serialVersionUID=1L;
/**
* 主键
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 实体id
*/
private Long entityId;
/**
* 实体类型(0:用户(头像),1:合同附件)
*/
private Integer entityType;
/**
* 附件地址
*/
private String enclosureUrl;
/**
* 创建时间
*/
private LocalDateTime createTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
/**
* 是否删除(0:已经删除,1:未删除)
*/
private Integer isDeleted;
/**
* 文件名
*/
private String alias;
/**
* 扩展名
*/
private String extName;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-30
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SmsAuth implements Serializable {
private static final long serialVersionUID=1L;
/**
* id
*/
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 手机号码
*/
private String iphone;
/**
* 验证码
*/
private String code;
/**
* 类型:1登录 2忘记密码
*/
private String type;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
private LocalDateTime createTime;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysCoupon implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("优惠券名称")
private String couponName;
@ApiModelProperty("企业表id")
private Long enterpriseId;
@ApiModelProperty("优惠券图片")
private String couponLogo;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import java.time.LocalDate;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysCouponDetail implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("优惠券表id")
private Long couponId;
@ApiModelProperty("招行编号(自己生成)")
private String cmbNo;
@ApiModelProperty("券码(第三方生成)")
private String couponCode;
@ApiModelProperty("活动开始时间")
private LocalDate startDate;
@ApiModelProperty("活动结束时间")
private LocalDate endDate;
@ApiModelProperty("领取状态:0未领取,1已领取,2已过期")
private Integer isReceive;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.consume.business.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-06-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysEnterprise implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("企业名称-客户名称")
private String enterpriseName;
@ApiModelProperty("企业成立年限")
private Double years;
@ApiModelProperty("注册资金")
private BigDecimal registerCapital;
@ApiModelProperty("经营范围")
private String businessScope;
@ApiModelProperty("经营产品或者服务")
private String product;
@ApiModelProperty("希望入驻的模块(会员、商圈、物业、出行)")
private String modular;
@ApiModelProperty("联系人姓名")
private String contacts;
@ApiModelProperty("联系人电话")
private String phone;
@ApiModelProperty("联系人邮箱")
private String email;
@ApiModelProperty("推荐理由-公司简介")
private String recommendReason;
@ApiModelProperty("租户logo")
private String logo;
@ApiModelProperty("状态(0禁用,1启用, 2代审批)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("租户地址")
private String address;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("企业app企业ID-客户号")
private String coridc;
@ApiModelProperty("发券类型(抵用,权益,折扣)")
private String couponType;
@ApiModelProperty("自建商城(1有,0无)")
private Integer shoppingSelf;
@ApiModelProperty("商城网址")
private String shoppingAddress;
@ApiModelProperty("券使用链接")
private String couponLink;
@ApiModelProperty("公司品牌")
private String brand;
@ApiModelProperty("会员服务申明")
private String vipStatement;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-29
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysLogs implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 操作用户
*/
@TableField("userId")
private String userId;
/**
* 操作内容
*/
private String module;
/**
* 操作状态1成功,0失败
*/
private Integer flag;
/**
* 备注
*/
private String remark;
/**
* 创建时间
*/
@TableField("createTime")
private LocalDateTime createTime;
/**
* 租户id 超级管理员为0
*/
private String tenantId;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import java.time.LocalDate;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-08-03
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysMember implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 企业id
*/
private Long enterpriseId;
/**
* 企业app用户ID
*/
private String usridc;
/**
* 申请人姓名
*/
private String name;
/**
* 申请人联系电话
*/
private String phone;
/**
* 出生年月日
*/
private LocalDate birthday;
private LocalDateTime createTime;
private String remark;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysPermission implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 上级ID(如果是一级为0)
*/
@TableField("parentId")
private Long parentId;
/**
* 名字
*/
private String name;
/**
* 菜单图标
*/
private String css;
/**
* 链接
*/
private String href;
/**
* 1菜单权限,2按钮权限
*/
private Integer type;
/**
* 接口权限
*/
private String permission;
/**
* 排序
*/
private Integer sort;
private String remark;
private List<SysRole> roleList;
}
package cn.wise.sc.consume.business.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysRole implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private LocalDateTime createTime;
/**
* (0禁用,1启用)
*/
private Integer status;
private String remark;
/**
* 租户id 超级管理员为0
*/
private String tenantId;
// private List<Permission> permissionList;
private List<SysUser> userList;
}
package cn.wise.sc.consume.business.entity;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import java.time.LocalDate;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import java.util.List;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUser implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 登录名
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 姓名
*/
private String nickName;
/**
* 头像
*/
private String headImgUrl;
/**
* 手机
*/
private String phone;
/**
* 电话
*/
private String telephone;
/**
* 邮箱
*/
private String email;
/**
* 开户银行
*/
private String bankName;
/**
* 银行卡号
*/
private String accountNo;
private LocalDate birthday;
/**
* (0男,1女)
*/
private Integer sex;
/**
* 职务表id,用于权限审批
*/
private Long postId;
/**
* (0禁用,1启用)
*/
private Integer status;
/**
* (0删除,1正常)
*/
private Integer isDelete;
private LocalDateTime createTime;
private LocalDateTime updateTime;
/**
* 微信标识
*/
private String openId;
private String remark;
/**
* 已使用额度
*/
private BigDecimal usedMoney;
/**
* 0普通用户,1租户管理员,2超级管理员
*/
private Integer isAdmin;
/**
* 租户id 超级管理员为0
*/
private String tenantId;
/**
* 企业app用户ID
*/
private String usridc;
public interface Status {
int DISABLED = 0;
int VALID = 1;
int LOCKED = 2;
}
}
package cn.wise.sc.consume.business.entity;
import java.time.LocalDateTime;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysUserCoupon implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
/**
* 用户表id
*/
private String userId;
/**
* 优惠券明细表id
*/
private Long couponDetailId;
/**
* 票券使用状态:0可使用,1已使用,2已过期
*/
private Integer isUse;
/**
* 领取时间
*/
private LocalDateTime createTime;
/**
* 使用时间
*/
private LocalDateTime useTime;
/**
* 备注
*/
private String remark;
}
package cn.wise.sc.consume.business.entity;
import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-29
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class TokenModel implements Serializable {
private static final long serialVersionUID=1L;
/**
* token
*/
private String id;
/**
* LoginUser的json串
*/
private String val;
@TableField("expireTime")
private Date expireTime;
@TableField("createTime")
private Date createTime;
@TableField("updateTime")
private Date updateTime;
}
package cn.wise.sc.consume.business.entity.cmbnoenet;
import cn.hutool.core.codec.Base64;
import cn.wise.sc.consume.business.entity.cmbnoenet.model.CMBOneNetTokenInfo;
import com.alibaba.fastjson.JSON;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @description: 企业一卡通工具类
* **商户使用招行公钥加密,商户使用自己的私钥进行签名**
* @author: qh
* @create: 2020-04-08 16:55
**/
public class AllInOneNetUtil {
//测试的公钥私钥
/*public final static String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5Ec7viMyQC5SShRz1jP0IQRLLVGDQ4f1rgZwtxT4ZOgnWxUoAHquj2yIrgFjNpWVnt/1dJGtXWkpp2UN3jMI5ubjVQkL0OFD+8r0IFXYAARsCLAwVLF0LE487KvVRaQC7A7rPlFfBtE/v++KajzMuDauNlIASYobcFKYdZ89vIfE/xMg/44QJqQ2XBkoMnJ7ul0kMdh4YWOQnO0qqvXD2eK3KPaXMRtxieGsVBgsvtETprw98bTl9tPUBUrneyirrccS8/Z6raV6nioyx2RzrMld8YnjlnV2YTJpNAlG+y/wLoKY55Rkjcvg9wSe8qbI/VtYVQfQz8gfeUzFQTKKCwIDAQAB";
public final static String priKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCoJ3fc1nDhrQOj\n" +
"zN70IAGGywkBPXxpxiDXzyhc3bcuk4sUbET4EMSn+RXCdsv37JS5J8GQNjXB4cZI\n" +
"CAkEcHSyJ14WRJrW56bvhyNbfpXXcBpvFpCyBR2Y6XGQIFZcdJZw7ZRm1MLKaRTE\n" +
"dXiwXHs5mWaQaFv9nEU4lqfAa/ICiWRob1KEbgnmB9m4R4Rcc9XwfMF4v9ZAyvx0\n" +
"+tr/wKUnsxCrcmXqNlNDIidikHjZJGXlAZeAVad/1kxqwHzhAoGn87EYzNoGSQ/8\n" +
"UYq/PtFNHwSnY0BBlx3O5fjUApb53sztPKN5p69FVmjtm1OEQ7dB44M3unzWfWAd\n" +
"XFMVh9JlAgMBAAECggEBAIe6S9q6UKUoRO7bN/8vMmw9yEfy/FBYdzwa30aORATZ\n" +
"XQKgHc9poYK/4Ft2Dk9Q6/7D405nI18awTR1H+owZ1FBy4UH3T+n/iwLFXQNqh8a\n" +
"Qov2V9cJoAlELMEcCPlZtfDzI70Y8R32Uaf99evMyj4E3y+ivNXpZEo3+LGtr8tx\n" +
"ERqgNwa4MFIbVBZ38DDHQe2u+ush+RUD2dbNUtVIlWsdqvzTcZSSnrCtPxz134OW\n" +
"oTKHDQ6HbTOurXOSCJiSNN08pxPRkRiXimfZ/ESTeRV9lLrYdVLZ+sd88UIHyYve\n" +
"X1g6bRywE6ybhXGkz1zo1zabvMBW1H9FSazFzVjYe8ECgYEA3jWePOjfMee+oUjM\n" +
"KmGb7xkXY00cXrZ/uhKCSp+aWM6BhYIQ+M/cIBmaWGV+NaN/cauqA3ky6man0r1H\n" +
"8bCuOYGBV/CuAZzPn8hfeG0IIHVBNJtzYqnqRKgX/8+R/ow1xJfLFZr5uY/pV6JO\n" +
"s8caVbhdGovajpHxDuuqb5AIwBECgYEAwbmI4wz2tPvLoIq3yaaQF1PmYjX4oT8O\n" +
"VPNHpOWGzqVrLjQvVNt/QkAFAVAGFFZuQBX5d91SIxzUv0Rj8QgA3OCt4ZUP68iN\n" +
"Gw00R2qcQJfgZVcj+IDBF+HyKb7ZUAmK/kjD8sad9/hg24NRsNj7gLchwwwJLYXx\n" +
"sYM7V4sQARUCgYEArLlE3Neu1l3rAfdSLAdfbEU2tstzp/N36S0F9feFxE4Qw7RM\n" +
"ePspghIktV1+8za5k6P6LWUCPM262cajq6zIYI7X+YFt4HcBtJPOEg++Z2x9WOUU\n" +
"lba6ENAQh5nTQ+e8y6mqBItIXgMNQD87qea0A7mhNUdMhdHPbOemvb1Z7+ECgYBD\n" +
"vqP18mSbqantvFTE+bBN2BMqqQEHMkvKvUCCk5luzj4K7EjY/eEkw8p8SQW3OvpX\n" +
"Atg4aHb+vGhRcpMYiNn0Y8WqqzvkEj/2A8oSZ1+43uOjzLNRhYUA2wyaOJk5+fxX\n" +
"LA8J6Rb4zizg1q1MkLRysJfn41+aQcrhbqjj1keEeQKBgEldcJrPD8ExPCYZnDlM\n" +
"s3XTItZp71+xIfqDfSWhRC92CoTAClellsjb0Xvfh+21S8Y9WkErvxvzyhF3OUdW\n" +
"9FLKAC5eQwhjfb2jKmLCdTnOzvJ0QUkjAIHOQL3cz/Acw04a51Y1DQc9wUcI20yS\n" +
"UmQWm3bR+PADbNDS3qsyqhHt";*/
//生产的公钥私钥
public final static String pubKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqz0Eb885pPGylYdcBcdi/d5O6OSgYBN4ol5l5yigd5oVkbnzb6Ctzs7nqkdpy8oQbnsYWqHvQYb8yf1y/a/v1X7Wt/jtJbOnelGRZvBpkNzzNdLp8jqQ0mdjS0tBYH7THp/zuFJ+G4iT+zw66KnXSyDuwBtFUlIgkajZA9EMNRYw4ACbGG+4XDgzdKpcgWu02Meov2tUn+jVItjtioes77PBsELc7Mi0ErLxVBbfGCRFf/WE6w4Ipj1ZQq+HT2/lSnTYnnW8dVOe1W4q0vDtnoUr04PwdH2e5FjdBWB10zIog5cwGuLn9CITQWBsu7R7Yf5bWhXnP3xraQj8egZ4wIDAQAB";
public final static String priKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDiSLLHLBZ9BkbM\n" +
"DSEgOpIx5sDgwRMrrReiOqJg5xynqmROTKsdf3NxgEOKwzDopu+gg/2dvKts2dNy\n" +
"1jeaKNTjfYl8yJo0O0y2Yx5WzyA5PjBXjYbg8DCxaxwLLlCqX5LshBWHpmOHfOq5\n" +
"pgdLBogDLzcqu+IFV/UZhL9Yk/G37P7soUzPoPUkFp5L0F5zW+iYUCq8ZT/dNH2o\n" +
"jBnwyMhwJq73oHYm5nWmcKPOrJM6bHiYQau54AVzHJ4d3087jqpAccfo229ltGhc\n" +
"R4tK/JhsDncx0lzbSi9Ypd6Z57hsfmMGzHGU0pdwgQwyA8eSJlhZP/nuNxcAh1Y8\n" +
"FSdiXDgHAgMBAAECggEBANdgbplYg0cYtEX/sSnl1cSdZ7QE0WRe6gHFYUxubT3A\n" +
"1pwYKT54Ur8TYDYxNtoaGjZjqv951ohShAnnjyCyAH9Ou5ADt5JDZu6qRPRHTNpv\n" +
"MMAEuv5aX15fHmAeAzVGpqdryLpGSrFo2lk9h++HFepCBHYuQiDn6SgSy7VZi1aM\n" +
"+BbGT9ksluEUYs8nOQF6ndJopqWRLpjWlvbsKw4QAcqhaX6p4+aFy/xLaO4wGpMo\n" +
"qevB0Pn0GNnwCQEGDqz0KjmpWIWkOyQt+rhPSR6HIy6v3b0x2jlmtt8c2rLN+RIU\n" +
"9bHHz8HF+cFz1OoCD3LBW8bWhFtU0723NQ+0xumQLmECgYEA/L3MfE+pyYO8dN/I\n" +
"CiRdoQtGUY8c3Pfh7j3P0+2CcgeKKpnQT7Jsa5bliDN1GyWc/bmYY/ZjlE456qyU\n" +
"LJpT4hVpT3OThDiQACSkecwz7mHjMNgwSgexnHG+a6qE1TAuNcJTdrwcZxr0jfKJ\n" +
"eyFU5cwZFln8JuJBKNqPcepkbI8CgYEA5TOS6vsmU0XBS8p3OBQLeQADtm5yaz5G\n" +
"s1AHtI63a4iRiMHne7n3khmgFR+mHC3ZGoGAU9asC5HVz3wqLmmRTD585HJwF/2O\n" +
"QyP4dW/YHOdMDDVWwlVitjBgDvRfvpYod6Mnda5om8ePVv9zfxKYTypw523goxmk\n" +
"EugFBV02qQkCgYEA6OlUB382faFsS9xqMYZ/zkhgngqf07aQO4g0/R2Up9bw6f9j\n" +
"a/6GUcP2dMTO95x7B4tAt2Y5MFPCpdQynMP/54pJyVE+MYwakDc0Z5XaiaUlxD6G\n" +
"icJ7WCuuCvRSg1BqVVpmpjYGirHZivJm5dS6syaaO/HjIEZDPA3mQVl7AFsCgYEA\n" +
"id3M6NVrRzm1PJ6ruaqs//qXQRwMbR/HrUJdcClMgT1jtSxVzmGdXl9VoH8qDtcx\n" +
"OTVeeI+va0IspyKbyNEtWfxYaZ3AeV3GPfKcGB/Pkgs6/jjzV+++cbKFhVlPYje2\n" +
"XchhCvN+7v1J5l3AHlaUEUKJKVw5fEIHJGw14PUh1OkCgYBUgHJrLVX05cUgoZnf\n" +
"/UySOhjASQBFzUFoMHDFYrEjjmS3AKWDtkzObFI2n+8B3miVvfLZwwyR9gvE1EwS\n" +
"2CTuXaabafTcLOn+6z/oJpn80FqUf7VJknfyu99M6GMvnKNb7eRqA1f+FTIJQm8O\n" +
"1STxVp0EMsSK3Ac+c4m8TCHS4g==";
// public final static String priKey = WxPayConfigure.PRIVATE_KEY;
// public final static String pubKey = WxPayConfigure.PUBLICK_KEY;
public static void main(String[] args) throws Exception {
/*CMBOneNetOrderParams params = new CMBOneNetOrderParams();
params.setCcynbr("10");
params.setMchtyp("MCHTYP004");
params.setRcvbbk("313234001089");
params.setRcveac("sdfasdfs");
params.setReford("201809270009");
params.setTrsamt("1");
params.setRcvean("sdfasdfs");
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("orderinfo", JSON.toJSONString(params));
String body = "{" + JSON.toJSONString(params) + "}";
System.out.println("==================body===================");
System.out.println(body);
String bodyEncrypt = encrypt(pubKey, body, "utf-8");
CMBOneNetRequestDataModel requestDataModel = new CMBOneNetRequestDataModel();
requestDataModel.setBody(bodyEncrypt);
CMBOneNetRequestDataModel.Header header = requestDataModel.new Header();
header.setTppidc("308999179220002");
header.setTrscod("FMORDSUB");
header.setMsgidc("2018022411234501234567890123456789");
String now = DateUtil.format(new Date(), "yyyyMMddHHmmss");
header.setReqtim(now);
requestDataModel.setHead(header);
System.out.println("=====================数据域========================");
System.out.println(JSON.toJSONString(requestDataModel));
String sign = sign(priKey, JSON.toJSONString(requestDataModel), "utf-8");
CMBOneNetRequestModel requestModel = new CMBOneNetRequestModel();
requestModel.setRequest(requestDataModel);
requestModel.setSignature(sign);
System.out.println("=====================最终请求体========================");
System.out.println(JSON.toJSONString(requestModel));*/
String token = AllInOneNetUtil.decrypt(priKey, "i7Dz_xgwTusg8a90Ks8M-4ybYhg38UmgzyF6_LDDzvX5IlY3fSjqVP8w0aql8QvtED9C0eLMXwmCIqPb7mefisvjRvBISsuCow9FYp7Oy4kgHIfH6siLIfLj85BKuXDWFf8OFS1riWuAfp7PRc2eG0d4DecXuRuMuoMKp4P_RPlc4QSwQ8fKzjoNNIcK18CKUfyDrgFnpQoMB6SGXhb4wapvCR53DgGVgYT9wf7saFWC9Na0AJWIxX-Tj040wLAAS9HmQWUoS4M7XVBcOp4UJK0DBQ9uK1VSHaP9s7rRoarDwEFyjRc8ieQQVmyz4p0CpJP6a6w_wr6F7EjsV23CKgjJTCjZ2dQQF6nX10VeBmMKAVj7QpVrGv1Y6alJITigfYrzd-EyDEr6U2xOcSXxnAov3aaNZVYbTK1nqZWmZUuJej6WMC9Wev1sIfkfvDZCb5HSZnYhBpqw_dWPViELDJ0GbIEtMtc6q7vqKIBbP4VSjX6_t7DidvpNSALPksKE0Q194hgqA62LAQ-PnSCt-XU6WyZf3kC8bznpKaW84PuKbALa054xLhUzK43WR1aqVQNvokabS0QDHJe0Kf_htauocd0knRA_qg-zZNdTPOTlbE2F-YdmocXZd4tCkTsp9q55441gHp8T6P0zTM6U065szLxazfmsRHXAkg0v5mk");
CMBOneNetTokenInfo cmbOneNetTokenInfo = JSON.parseObject(token, CMBOneNetTokenInfo.class);
System.out.println(cmbOneNetTokenInfo);
}
// public static void main(String[] args) {
// String rst = "{\n" +
// " \"response\": {\n" +
// " \"head\": {\n" +
// " \"vernbr\": \"1.0\",\n" +
// " \"tppidc\": \"FMORDSUB\",\n" +
// " \"trscod\": \"FMORDSUB\",\n" +
// " \"msgidc\": \"2018022411234501234567890123456789\",\n" +
// " \"sigalg\": \"SHA256WithRSA\",\n" +
// " \"retcod\": \"DCTP007\",\n" +
// " \"retmsg\": \"tppidc invalid or has no permission.#1.tppidc=FMORDSUB.IP=220.172.104.19\",\n" +
// " \"rsptim\": \"20200409135042\"\n" +
// " },\n" +
// " \"body\": \"54654654564654\"\n" +
// " },\n" +
// " \"signature\": \"3NxW1RgHrLW4heDeDaVIMHT6vvmlAgUiVb01GpJ23ZoeaCw1WRcucS6HfoaJa/HzbzDa4zf4wr8L98koDx7/yT2mZ03/0h2QSUxAWRgrQtHYZIQW34IWqziPq9MWouhejHEcp6mPJMQVojTP0dWrSIPOcGRjjzwLLDpg7RioJJOqOKmMpWkAGuYC1zIyUEcK0fuUBk05txW42khLjrdEKMkOww4seSjzTYU/fdoij7M2X+Tb/ce+eAh9nmSF9gCjOiOv4t7ITR4zMMYjsfhQ1OiwwbbpEMmd8UF/7lrSanxJIhCF6xOhrEHrZT6DWdhOqQbQ9+dlExmdHsRpx71D0Q==\"\n" +
// "}";
//
// CMBONeNetResponse cmboNeNetResponses = JSON.parseObject(rst, CMBONeNetResponse.class);
//
// System.out.println(cmboNeNetResponses.getResponse().getHead().getRetmsg());
// }
/**
* RSA加密
*
* @param sPubKey:公钥字符串(BASE64)
* @param pladat:待加密数据
* @param charset:字符编码
* @return 加密结果
* @throws Exception
*/
public static String encrypt(String sPubKey, String pladat, String charset) throws Exception {
if (null == charset || !"gbk".equals(charset.toLowerCase())) {
charset = "UTF-8";
}
sPubKey = removePubKeyDefine(sPubKey);
byte[] pubKeys = Base64.decode(sPubKey);
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeys);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = kf.generatePublic(pubKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] baDate = pladat.getBytes(charset);
final int MAX_ENCRYPT_BLOCK = ((RSAKey) pubKey).getModulus().bitLength() / 8 - 11;
int inputLen = baDate.length;
int offSet = 0;
byte[] cache;
int i = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(baDate, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(baDate, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return Base64.encode(decryptedData);
}
/**
* RSA签名
*
* @param sPrvKey:私钥字符串(BASE64)
* @param strToSign:待验签数据
* @param charset:字符编码
* @return 签名结果
* @throws Exception
*/
public static String sign(String sPrvKey, String strToSign,
String charset) throws Exception {
if (null == charset || !"gbk".equals(charset.toLowerCase())) {
charset = "UTF-8";
}
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(strToSign.getBytes(charset));
byte byteBuffer[] = messageDigest.digest();
sPrvKey = removePrvKeyDefine(sPrvKey);
byte[] privateKeys = Base64.decode(sPrvKey);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeys);
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
PrivateKey prvkey = mykeyFactory.generatePrivate(privateKeySpec);
Signature sig = Signature.getInstance("SHA256WithRSA");
sig.initSign(prvkey);
sig.update(byteBuffer);
byte[] bResult = sig.sign();
return Base64.encode(bResult);
}
/**
* RSA解密
*
* @param sPrvKey RSA私钥(BASE64字符串)
* @param strData 待解密数据
* @return 加密结果
* @throws Exception
*/
public static String decrypt(String sPrvKey, String strData) throws Exception {
sPrvKey = removePrvKeyDefine(sPrvKey);
byte[] privateKeys = Base64.decode(sPrvKey);
java.security.Security.addProvider(
new org.bouncycastle.jce.provider.BouncyCastleProvider()
);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeys);
KeyFactory mykeyFactory = KeyFactory.getInstance("RSA");
PrivateKey prvkey = mykeyFactory.generatePrivate(privateKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, prvkey);
byte[] baDate = Base64.decode(strData);
final int MAX_DECRYPT_BLOCK = ((RSAKey) prvkey).getModulus().bitLength() / 8;
int inputLen = baDate.length;
int offSet = 0;
byte[] cache;
int i = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
// ???????????
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(baDate, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(baDate, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return new String(decryptedData);
}
/**
* RSA验签
*
* @param sPubKey:公钥字符串(BASE64)
* @param strToSign:待验签数据
* @param strSign:签名数据
* @return 验签结果
* @throws Exception
*/
public static boolean verify(String sPubKey, String strToSign, String strSign) throws Exception {
sPubKey = removePubKeyDefine(sPubKey);
byte[] pubKeys = Base64.decode(sPubKey);
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pubKeys);
KeyFactory kf = KeyFactory.getInstance("RSA");
PublicKey pubKey = kf.generatePublic(pubKeySpec);
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(strToSign.toString().getBytes());
byte byteBuffer[] = messageDigest.digest();
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initVerify(pubKey);
signature.update(byteBuffer);
return signature.verify(Base64.decode(strSign));
}
/**
* 去掉PEM公钥文件的声明部分,以用于BASE64解码
*
* @param pubkey
* @return
*/
private static String removePubKeyDefine(String pubkey) {
pubkey = pubkey.replace("-----BEGIN PUBLIC KEY-----", "");
pubkey = pubkey.replace("-----END PUBLIC KEY-----", "");
pubkey = pubkey.replace("\n", "");
return pubkey;
}
/**
* 去掉PEM私钥文件的声明部分,以用于BASE64解码
*
* @param prvkey
* @return
*/
private static String removePrvKeyDefine(String prvkey) {
prvkey = prvkey.replace("-----BEGIN RSA PRIVATE KEY-----", "");
prvkey = prvkey.replace("-----END RSA PRIVATE KEY-----", "");
prvkey = prvkey.replace("\n", "");
return prvkey;
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet;
import cn.wise.sc.consume.business.entity.SysMember;
import cn.wise.sc.consume.business.entity.cmbnoenet.model.BaseResponse;
import cn.wise.sc.consume.business.entity.cmbnoenet.model.TokenInfoQuery;
import cn.wise.sc.consume.business.model.SysEnterpriseDto;
import cn.wise.sc.consume.business.service.impl.CMBOneNetPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @description: 招行一卡通
* @author: qh
* @create: 2020-04-09 17:05
*/
@Api(tags = "企业app接口")
@CrossOrigin
@RestController
@RequestMapping("/cmbOneNet")
public class CMBOneNetController {
private static final Logger log = LoggerFactory.getLogger("CMBOneNetController");
final CMBOneNetPayService CMBOneNetPayService;
public CMBOneNetController(CMBOneNetPayService CMBOneNetPayService) {
this.CMBOneNetPayService = CMBOneNetPayService;
}
@ApiOperation("获取招行app支付订单信息")
@PostMapping("/fmordsubOrderInfo")
public BaseResponse fmordsubOrderInfo(
String orderNo, String txnAmt, String receAccount, String receName, String receBank)
throws Exception {
return CMBOneNetPayService.oneNetOrderInfo(orderNo, txnAmt, receAccount, receName, receBank);
}
@ApiOperation("订单支付回调")
@PostMapping("/payNotice")
public BaseResponse payNotice(HttpServletRequest request) {
return BaseResponse.okMsg("招行一卡通支付回调!", CMBOneNetPayService.getClass());
}
//****************************************************************
@ApiOperation("申请Api访问令牌")
@PostMapping("/applyInfo")
public BaseResponse getApplyInfo(@RequestBody String authCode){
return CMBOneNetPayService.getApplyInfo(authCode);
}
@ApiOperation("续费Api访问令牌")
@PutMapping("/reNewApplyInfo")
public BaseResponse reNewApplyInfo(@RequestBody String token){
return CMBOneNetPayService.renewApplyInfo(token);
}
@ApiOperation("查询企业信息")
@GetMapping("/getEnterprise")
public BaseResponse getEnterprise(String coridc, String token){
return CMBOneNetPayService.getEnterprise(coridc, token);
}
@ApiOperation("查询企业用户信息")
@GetMapping("/getEnterpriseUser")
public BaseResponse getEnterpriseUser(String usridc, String token){
return CMBOneNetPayService.getEnterpriseUser(usridc, token);
}
@ApiOperation("查询企业用户证件信息")
@GetMapping("/getEnterpriseUserCard")
public BaseResponse getEnterpriseUserCard(String usridc, String token){
return CMBOneNetPayService.getEnterpriseUserCard(usridc, token);
}
@ApiOperation("查询企业核心客户号")
@GetMapping("/getEnterpriseClientId")
public BaseResponse getEnterpriseClientId(String coridc, String token){
return CMBOneNetPayService.getEnterpriseClientId(coridc, token);
}
@ApiOperation("查询自然人用户信息")
@GetMapping("/getNatural")
public BaseResponse getNatural(String glbuid, String token){
return CMBOneNetPayService.getNatural(glbuid, token);
}
@ApiOperation("解析握手令牌token,获取招行App用户信息")
@PostMapping("/getUserInforMation")
public BaseResponse getUserInforMation(@RequestBody TokenInfoQuery tokenInfoQuery) {
return CMBOneNetPayService.getUserInforMation(tokenInfoQuery.getSignature(), tokenInfoQuery.getData());
}
@ApiOperation("判断企业申请状态")
@PostMapping("/getUserInfo")
public BaseResponse getUserInfo(@RequestBody String coridc) {
return CMBOneNetPayService.getUserInfo(coridc);
}
@ApiOperation(value = "申请发券")
@PostMapping("/applyEnterprise")
public BaseResponse applyEnterprise(@RequestBody SysEnterpriseDto enterpriseDto) {
return CMBOneNetPayService.applyEnterprise(enterpriseDto);
}
@ApiOperation(value = "票券列表(企业列表)")
@GetMapping("/getEnterpriseList")
public BaseResponse getEnterpriseList(String usridc) {
return CMBOneNetPayService.getEnterpriseList(usridc);
}
@ApiOperation(value = "会员申请")
@PostMapping("/applyMember")
public BaseResponse applyMember(@RequestBody SysMember sysMember) {
return CMBOneNetPayService.applyMember(sysMember);
}
@ApiOperation(value = "领券列表")
@GetMapping("/getCouponAppList")
public BaseResponse getCouponAppList(String coridc, String usridc) {
return CMBOneNetPayService.getCouponAppList(coridc, usridc);
}
@ApiOperation(value = "领取")
@GetMapping("/receive")
public BaseResponse receive(String couponId, String usridc) {
return CMBOneNetPayService.receive(couponId, usridc);
}
@ApiOperation(value = "已领取优惠券列表")
@GetMapping("/getReceivedList")
public BaseResponse getReceivedList(String coridc, String usridc) {
return CMBOneNetPayService.getReceivedList(coridc, usridc);
}
@ApiOperation(value = "使用优惠券")
@GetMapping("/useCoupon")
public BaseResponse useCoupon(Long couponDetailId) {
return CMBOneNetPayService.useCoupon(couponDetailId);
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import java.io.Serializable;
import java.util.List;
/**
* @description: 响应封装
* @author: qh
* @create: 2019-12-12 15:04
**/
public class BaseResponse<T> implements Serializable {
private static final long serialVersionUID = 2739858008722562194L;
public String msg;
public int code;
public T data;
public String className;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
private static <T> BaseResponse<T> createBaseResponse(T t) {
return new BaseResponse<T>();
}
public static <T> BaseResponse<T> ok() {
BaseResponse<T> baseResponse = new BaseResponse<>();
baseResponse.setCode(200);
baseResponse.setMsg("操作成功");
return baseResponse;
}
public static <T> BaseResponse<T> ok(T data) {
BaseResponse<T> baseResponse = createBaseResponse(data);
baseResponse.setCode(200);
baseResponse.setData(data);
baseResponse.setClassName(data.getClass().getName());
baseResponse.setMsg("操作成功");
return baseResponse;
}
public static <T> BaseResponse<T> ok(T data, Class clazz) {
BaseResponse<T> baseResponse = createBaseResponse(data);
baseResponse.setCode(200);
baseResponse.setData(data);
baseResponse.setClassName(clazz.getName());
baseResponse.setMsg("操作成功");
return baseResponse;
}
public static <T> BaseResponse<T> okMsg(String msg, Class clazz) {
BaseResponse<T> baseResponse = createBaseResponse(null);
baseResponse.setCode(200);
baseResponse.setData(null);
baseResponse.setClassName(clazz.getName());
baseResponse.setMsg(msg);
return baseResponse;
}
public static <T> BaseResponse<T> ok(List<T> list, Class clazz) {
BaseResponse<T> baseResponse = createBaseResponse(null);
baseResponse.setCode(200);
baseResponse.setData(null);
baseResponse.setClassName(clazz.getName());
baseResponse.setMsg("操作成功");
return baseResponse;
}
public static <T> BaseResponse<T> ok(String msg, T data) {
BaseResponse<T> baseResponse = createBaseResponse(data);
baseResponse.setCode(200);
baseResponse.setData(data);
baseResponse.setClassName(data.getClass().getName());
baseResponse.setMsg(msg);
return baseResponse;
}
public static <T> BaseResponse<T> error(String msg, T data) {
BaseResponse<T> baseResponse = createBaseResponse(data);
baseResponse.setCode(400);
baseResponse.setData(data);
baseResponse.setClassName(data.getClass().getName());
baseResponse.setMsg(msg);
return baseResponse;
}
public static <T> BaseResponse<T> error(String msg, String clazz) {
BaseResponse<T> baseResponse = createBaseResponse(null);
baseResponse.setCode(400);
baseResponse.setData(null);
baseResponse.setClassName(clazz);
baseResponse.setMsg(msg);
return baseResponse;
}
public static BaseResponse<String> hystrixError(String author) {
BaseResponse<String> baseResponse = createBaseResponse(null);
baseResponse.setCode(666666);
baseResponse.setData(null);
baseResponse.setClassName("熔断器");
baseResponse.setMsg("它又触发熔断了! 太难了! /(ㄒoㄒ)/~~ 问问是不是在调试 ___*(  ̄皿 ̄)/#____" + "author:" + author);
return baseResponse;
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
import java.io.Serializable;
/**
* @description: 招行一卡通 响应对象
* @author: qh
* @create: 2020-04-09 14:12
**/
@Data
public class CMBONeNetResponse implements Serializable {
private static final long serialVersionUID = -1L;
public CMBResponse response;
public String signature;
@Data
public class CMBResponse {
private String body;
private ResponseHead head;
@Data
public class ResponseHead {
private String vernbr;
private String tppidc;
private String FMORDSUB;
private String msgidc;
private String sigalg;
private String retcod;
private String retmsg;
private String rsptim;
}
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
/**
* @description: 招商银行 一网通
* @author: qh
* @create: 2020-04-08 14:53
**/
@Data
public class CMBOneNetOrderParams {
/**
* 订单号
*/
private String reford;
/**
* 商户类型
*/
private String mchtyp;
/**
* 币种 人民币
*/
private String ccynbr = "10";
/**
* 金额 最大15位包含2小数位
*/
private String trsamt;
/**
* 收方账号
*/
private String rcveac;
/**
* 收方账户名
*/
private String rcvean;
/**
* 收方开户账号
*/
private String rcvbbk;
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
/**
* @description: 招行一卡通 请求数据域
* @author: qh
* @create: 2020-04-09 09:57
**/
@Data
public class CMBOneNetRequestDataModel {
@JSONField(ordinal = 1)
private Header head;
/**
* 业务具体参数 要求加密RSA
*/
@JSONField(ordinal = 2)
private String body;
/**
* 请求头部
*/
@Data
public class Header {
/**
* 接口版本号 固定为1.0
*/
public String vernbr = "1.0";
/**
* 商户号 由招行分配
*/
public String tppidc;
/**
* 交易码 请求功能码,用以区分所进行的交易。区分大小写
*/
public String trscod = "FMORDSUB";
/**
* 请求时间 格式:yyyyMMddHHmmss精确到秒
*/
public String reqtim;
/**
* 报文ID 用以标明报文的唯一性,返回报文原样返回
*/
public String msgidc;
/**
* 签名算法 固定为“SHA256WithRSA
*/
public String sigalg = "SHA256WithRSA";
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
/**
* @description: 招行一卡通 请求对象
* @author: qh
* @create: 2020-04-09 10:01
**/
@Data
public class CMBOneNetRequestModel {
/**
* 数据域
*/
private CMBOneNetRequestDataModel request;
/**
* 签名域
*/
private String signature;
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
/**
* @description: 招行一卡通请求地址 维护对象
* @author: qh
* @create: 2020-04-09 15:20
*/
public class CMBOneNetRequestUrl {
//http://121.15.180.84/
//https://gtb.cmbchina.com/
/** FMORDSUB 订单数据提交 */
public static final String ORDERINFO_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/orderinfo";
/** 获取Api访问令牌的接口 */
public static final String APPLYINFO_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/applyinfo";
/** 续费Api访问令牌的接口 */
public static final String RENEWINFO_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/renewinfo";
/*查询企业信息*/
public static final String CORQRYITF_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/corqryitf";
/*查询企业用户信息*/
public static final String USRQRYITF_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/usrqryitf";
/*查询企业用户证件信息*/
public static final String USRCTFITF_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/usrctfitf";
/*查询企业核心客户号*/
public static final String CLTQRYITF_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/cltqryitf";
/*查询自然人用户信息*/
public static final String GLBQRYITF_URL = "https://gtb.cmbchina.com/CmbBank_GTB/API/glbqryitf";
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
/**
* @description: 招行一卡通 获取到得流程号
* @author: qh
* @create: 2020-04-09 15:06
**/
@Data
public class CMBOneNetResponseFlow {
private FlowResult subresult;
@Data
public class FlowResult {
/**
* 流程号
*/
private String seqnbr;
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
/**
* @description: 握手令牌对象
* @author: qh
* @create: 2020-05-19 11:39
*/
@Data
public class CMBOneNetTokenInfo {
/** 接口版本号 */
private String vernbr;
/** 签名算法 */
private String sigalg;
/** 请求时间 */
private String reqtim;
/** 企业 ID */
private String coridc;
/** 用户 ID */
private String usridc;
/** 手机号 */
private String usrmob;
/** 授权码 */
private String autcod;
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
/**
*
* <p>商户平台模式</p>
*
* @author Corpier
*/
public enum PayModel {
/**
* 商户模式
*/
BUSINESS_MODEL("BUSINESS_MODEL"),
/**
* 服务商模式
*/
SERVICE_MODE("SERVICE_MODE");
PayModel(String payModel) {
this.payModel = payModel;
}
/**
* 商户模式
*/
private final String payModel;
public String getPayModel() {
return payModel;
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
/**
*
* <p>签名方式</p>
*
* @author Corpier
*/
public enum SignType {
/**
* HMAC-SHA256 加密
*/
HMACSHA256("HMAC-SHA256"),
/**
* MD5 加密
*/
MD5("MD5");
SignType(String type) {
this.type = type;
}
private final String type;
public String getType() {
return type;
}
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
import lombok.Data;
/**
* @description:
* @author: qh
* @create: 2020-06-10 13:59
**/
@Data
public class TokenInfoQuery {
String signature;
String data;
}
package cn.wise.sc.consume.business.entity.cmbnoenet.model;
/**
*
* <p>支付方式</p>
*
* @author Corpier
*/
public enum TradeType {
/**
* 微信公众号支付或者小程序支付
*/
JSAPI("JSAPI"),
/**
* 微信扫码支付
*/
NATIVE("NATIVE"),
/**
* 微信APP支付
*/
APP("APP"),
/**
* 付款码支付
*/
MICROPAY("MICROPAY"),
/**
* H5支付
*/
MWEB("MWEB");
TradeType(String tradeType) {
this.tradeType = tradeType;
}
/**
* 交易类型
*/
private final String tradeType;
public String getTradeType() {
return tradeType;
}
}
package cn.wise.sc.consume.business.enumation;
import com.alibaba.fastjson.annotation.JSONType;
import com.baomidou.mybatisplus.annotation.EnumValue;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* @author neo.shu
* @since 2020/4/22 17:40
*/
@JSONType(serializeEnumAsJavaBean = true)
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
@AllArgsConstructor
@Getter
public enum ProjectRole {
PM("PM","项目经理", true),
PD("PD","产品设计", false),
UD("UD","UI设计", false),
FD("FD","前端开发", false),
BD("BD","后端开发", false),
TD("TD","测试经理", false),
QA("QA","质量管理", true),
;
@EnumValue
private String dbName;
private String label;
private boolean isManage;
public int getValue() {
return this.ordinal();
}
}
package cn.wise.sc.consume.business.exception;
/**
* 根据业务定制的具体异常类
* @author shulidong
* @since 2019/2/19/0019 16:45
*/
public class BizException extends BusinessException {
public BizException(String message) {
super(message);
}
}
package cn.wise.sc.consume.business.exception;
import org.springframework.http.HttpStatus;
/**
* @author shulidong
* @since 2019/2/19/0019 16:48
**/
public abstract class BusinessException extends RuntimeException {
protected HttpStatus statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
private String errorCode;
public HttpStatus getStatusCode() {
return statusCode;
}
public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}
public BusinessException(String errorCode, String message) {
super(message);
this.errorCode = errorCode;
}
public BusinessException(String message, Throwable e) {
super(message,e);
}
public BusinessException(String message) {
super(message);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
package cn.wise.sc.consume.business.exception;
/**
* 封装fastdfs的异常,使用运行时异常
*
* @author yuqih
* @author tobato
*
*/
public abstract class FdfsException extends RuntimeException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
protected FdfsException(String message) {
super(message);
}
/**
* @param message
* @param cause
*/
protected FdfsException(String message, Throwable cause) {
super(message, cause);
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.exception;
/**
* 从Url解析StorePath文件路径对象错误
*
* @author wuyf
*
*/
public class FdfsUnsupportStorePathException extends FdfsException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8116336411011152869L;
public FdfsUnsupportStorePathException(String message) {
super(message);
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.exception;
/**
* redis 操作异常
*/
public class RedisHandleException extends RuntimeException{
public RedisHandleException(String msg) {
super(msg);
}
public RedisHandleException(String message, Throwable throwable) {
super(message, throwable);
}
public RedisHandleException(Throwable throwable) {
super(throwable);
}
}
package cn.wise.sc.consume.business.filter;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sun.misc.BASE64Decoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class SwaggerInterceptor extends HandlerInterceptorAdapter {
private String username;
private String password;
public SwaggerInterceptor(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String authorization = request.getHeader("Authorization");
boolean isAuthSuccess = httpBasicAuth(authorization);
if (!isAuthSuccess) {
response.setCharacterEncoding("utf-8");
response.setStatus(401);
// response.setStatus(401,"Unauthorized");
response.setHeader("WWW-authenticate", "Basic realm=\"Realm\"");
try (PrintWriter writer = response.getWriter()) {
writer.print("Forbidden, unauthorized user");
}
}
return isAuthSuccess;
}
public boolean httpBasicAuth(String authorization) throws IOException {
if (authorization != null && authorization.split(" ").length == 2) {
String userAndPass = new String(new BASE64Decoder().decodeBuffer(authorization.split(" ")[1]));
String username = userAndPass.split(":").length == 2 ? userAndPass.split(":")[0] : null;
String password = userAndPass.split(":").length == 2 ? userAndPass.split(":")[1] : null;
if (this.username.equals(username) && this.password.equals(password)) {
return true;
}
}
return false;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
String uri = request.getRequestURI();
AntPathMatcher pathMatcher = new AntPathMatcher();
if (!pathMatcher.match("/swagger-ui.html", uri) && !pathMatcher.match("/webjars/**", uri)) {
response.setStatus(404);
return;
}
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:/META-INF/resources" + uri);
if (resources != null && resources.length > 0) {
FileCopyUtils.copy(resources[0].getInputStream(), response.getOutputStream());
} else {
response.setStatus(404);
}
}
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.RefEntityEnclosure;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-03
*/
public interface RefEntityEnclosureMapper extends BaseMapper<RefEntityEnclosure> {
int deleteByPrimaryKey(Long id);
int insert(RefEntityEnclosure record);
int insertSelective(RefEntityEnclosure record);
RefEntityEnclosure selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(RefEntityEnclosure record);
int updateByPrimaryKey(RefEntityEnclosure record);
@Select("select * from ref_entity_enclosure ree\n" +
"where ree.is_deleted=1 and ree.entity_type=#{entityType} and ree.entity_id=#{entityId}")
List<RefEntityEnclosure> getList(@Param("entityType")Integer entityType, @Param("entityId")Long entityId);
@Delete("delete from ref_entity_enclosure where enclosure_url = #{enclosureUrl} ")
int deleteByUrl(String enclosureUrl);
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SmsAuth;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import java.util.Date;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-30
*/
public interface SmsAuthMapper extends BaseMapper<SmsAuth> {
@Options(useGeneratedKeys = true, keyProperty = "id")
@Insert("insert into sms_auth(iphone, code, type, remark, create_time) values(#{iphone}, #{code}, #{type}, #{remark} ,now())")
Boolean save(SmsAuth smsAuth);
@Select("select * from sms_auth login_lable where login_lable.iphone = #{iphone} and login_lable.type = #{type} and login_lable.create_time > #{endDate} ")
List<SmsAuth> selectList(String iphone, String type, Date endDate);
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.model.ReceivedAppListVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface SysCouponDetailMapper extends BaseMapper<SysCouponDetail> {
@Select("select count(*) from sys_coupon_detail where to_days(create_time) = to_days(now())")
int createNo();
List<ReceivedAppListVO> getReceivedList(@Param("coridc") String coridc, @Param("usridc") String usridc );
@Select("select * from sys_coupon_detail scd where scd.is_receive=0 and to_days(now()) - to_days(scd.end_date) >0")
List<SysCouponDetail> getVerdueList();
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysCoupon;
import cn.wise.sc.consume.business.model.CouponAppListVO;
import cn.wise.sc.consume.business.model.CouponDetailVO;
import cn.wise.sc.consume.business.model.CouponListVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface SysCouponMapper extends BaseMapper<SysCoupon> {
List<CouponListVO> getCouponPage(@Param("map") Map<String,Object> map);
CouponDetailVO getCouponDetail(Long id);
List<CouponAppListVO> getCouponAppList(@Param("coridc") String coridc, @Param("usridc") String usridc );
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.model.EnterpriseAppListVO;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-06-17
*/
public interface SysEnterpriseMapper extends BaseMapper<SysEnterprise> {
List<SysEnterprise> getPage(@Param("map") Map<String,Object> map);
List<EnterpriseAppListVO> getEnterpriseList(String usridc);
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysLogs;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-29
*/
public interface SysLogsMapper extends BaseMapper<SysLogs> {
@Insert("insert into sys_logs(userId, module, flag, remark, createTime, tenant_id) " +
"values(#{userId}, #{module}, #{flag}, #{remark}, now(), #{tenantId} )")
int save(SysLogs sysLogs);
@Delete("delete from sys_logs where createTime <= #{time}")
int deleteLogs(String time);
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysMember;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-08-03
*/
public interface SysMemberMapper extends BaseMapper<SysMember> {
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysPermission;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface SysPermissionMapper extends BaseMapper<SysPermission> {
@Select("select distinct login_lable.* from sys_permission login_lable " +
"inner join sys_role_permission rp on login_lable.id = rp.permissionId " +
"inner join sys_role_user ru on ru.roleId = rp.roleId " +
"where ru.userId = #{userId} order by login_lable.parentId,login_lable.sort")
List<SysPermission> listByUserId(Long userId);
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysRole;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface SysRoleMapper extends BaseMapper<SysRole> {
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.entity.SysUserCoupon;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface SysUserCouponMapper extends BaseMapper<SysUserCoupon> {
@Select("select suc.* from sys_user_coupon suc " +
"left join sys_coupon_detail scd on scd.id = suc.coupon_detail_id " +
"where scd.is_receive=1 and suc.is_use=0 and to_days(now()) - to_days(scd.end_date) >0")
List<SysUserCoupon> getVerdueList();
}
package cn.wise.sc.consume.business.mapper;
import cn.wise.sc.consume.business.entity.SysUser;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
/**
* <p>
* Mapper 接口
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface SysUserMapper extends BaseMapper<SysUser> {
@Select("select login_lable.* from sys_user login_lable where login_lable.username = #{username}")
SysUser getUser(String username);
}
<?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="cn.wise.sc.consume.business.mapper.RefEntityEnclosureMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SmsAuthMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysCouponDetailMapper">
<select id="getReceivedList" resultType="cn.wise.sc.consume.business.model.ReceivedAppListVO">
select
scd.id as id, scd.coupon_code as couponCode,
sc.coupon_logo as couponLogo
from sys_coupon_detail scd
left join sys_user_coupon suc on suc.coupon_detail_id = scd.id
left join sys_coupon sc on sc.id = scd.coupon_id
where sc.enterprise_id = #{coridc} and sc.is_delete=1 and sc.status=1
and scd.is_delete=1 and scd.is_receive=1
and suc.user_id=#{usridc} and suc.is_use=0
</select>
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysCouponMapper">
<sql id="where">
<where>
and sc.is_delete=1
<if test="map.couponName != null and map.couponName != ''">
and sc.coupon_name like concat('%', #{map.couponName}, '%')
</if>
<if test="map.enterpriseId != null and map.enterpriseId != ''">
and sc.enterprise_id = #{map.enterpriseId}
</if>
<if test="map.status != null">
and sc.status = #{map.status}
</if>
</where>
</sql>
<select id="getCouponPage" resultType="cn.wise.sc.consume.business.model.CouponListVO">
select sc.*,se.enterprise_name as enterpriseName,
(select count(*) from sys_coupon_detail scd where scd.coupon_id =sc.id and scd.is_delete = 1) as couponNum
from sys_coupon sc
left join sys_enterprise se on se.id = sc.enterprise_id
<include refid="where" />
order by sc.create_time desc
</select>
<select id="getCouponDetail" resultType="cn.wise.sc.consume.business.model.CouponDetailVO">
select sc.*,se.enterprise_name as enterpriseName from sys_coupon sc
left join sys_enterprise se on se.id = sc.enterprise_id
where sc.id = #{id}
</select>
<select id="getCouponAppList" resultType="cn.wise.sc.consume.business.model.CouponAppListVO">
select sc.*,
EXISTS(select * from sys_user_coupon suc
left join sys_coupon_detail scd on scd.id = suc.coupon_detail_id
where scd.coupon_id = sc.id and suc.user_id = #{usridc} ) as isReceive
from sys_coupon sc
left join sys_enterprise se on se.id = sc.enterprise_id
where se.coridc = #{coridc}
</select>
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysEnterpriseMapper">
<sql id="where">
<where>
<if test="map.enterpriseName != null and map.enterpriseName != ''">
and t.enterprise_name like concat('%', #{map.enterpriseName}, '%')
</if>
<if test="map.status != null">
and t.status = #{map.status}
</if>
</where>
</sql>
<select id="getPage" resultType="cn.wise.sc.consume.business.entity.SysEnterprise">
select t.* from sys_enterprise t
<include refid="where" />
order by t.create_time desc
</select>
<select id="getEnterpriseList" resultType="cn.wise.sc.consume.business.model.EnterpriseAppListVO">
select t.*,
EXISTS(select * from sys_member sm where sm.enterprise_id=t.id and sm.usridc = #{usridc}) as isBinding
from sys_enterprise t
where t.status=1
</select>
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysLogsMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysMemberMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysPermissionMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysRoleMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysUserCouponMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.SysUserMapper">
</mapper>
<?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="cn.wise.sc.consume.business.mapper.TokenModelMapper">
</mapper>
package cn.wise.sc.consume.business.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class CouponAppListVO {
private Long id;
@ApiModelProperty("优惠券名称")
private String couponName;
@ApiModelProperty("企业表id")
private Long enterpriseId;
@ApiModelProperty("优惠券图片")
private String couponLogo;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("企业名称")
private String enterpriseName;
@ApiModelProperty("优惠券数量")
private Integer couponNum;
@ApiModelProperty("领取状态:0未领取,1已领取,2已过期")
private Integer isReceive;
}
package cn.wise.sc.consume.business.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class CouponDetailDTO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("优惠券表id")
private Long couponId;
@ApiModelProperty("券码(第三方生成)")
private String couponCode;
@ApiModelProperty("活动开始时间")
private LocalDate startDate;
@ApiModelProperty("活动结束时间")
private LocalDate endDate;
@ApiModelProperty("备注")
private String remark;
}
package cn.wise.sc.consume.business.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class CouponDetailVO {
private Long id;
@ApiModelProperty("优惠券名称")
private String couponName;
@ApiModelProperty("企业表id")
private Long enterpriseId;
@ApiModelProperty("优惠券图片")
private String couponLogo;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("企业名称")
private String enterpriseName;
}
package cn.wise.sc.consume.business.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class CouponListVO {
private Long id;
@ApiModelProperty("优惠券名称")
private String couponName;
@ApiModelProperty("企业表id")
private Long enterpriseId;
@ApiModelProperty("优惠券图片")
private String couponLogo;
@ApiModelProperty("状态(0禁用,1启用)")
private Integer status;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ApiModelProperty("是否删除(0删除,1存在)")
private Integer isDelete;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("企业名称")
private String enterpriseName;
@ApiModelProperty("优惠券数量")
private Integer couponNum;
}
package cn.wise.sc.consume.business.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class EnterpriseAppListVO {
@TableId(value = "id", type = IdType.AUTO)
private Long id;
@ApiModelProperty("企业名称-客户名称")
private String enterpriseName;
@ApiModelProperty("租户logo")
private String logo;
@ApiModelProperty("企业app企业ID-客户号")
private String coridc;
@ApiModelProperty("是否申请会员")
private Boolean isBinding;
@ApiModelProperty("推荐理由-公司简介")
private String recommendReason;
@ApiModelProperty("券使用链接")
private String couponLink;
}
package cn.wise.sc.consume.business.model;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import cn.wise.sc.consume.business.entity.SysPermission;
import cn.wise.sc.consume.business.entity.SysRole;
import cn.wise.sc.consume.business.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class LoginUser extends SysUser implements UserDetails {
private static final long serialVersionUID = -1379274258881257107L;
private List<SysPermission> permissions;
private String token;
/** 登陆时间戳(毫秒) */
private Long loginTime;
/** 过期时间戳 */
private Long expireTime;
private String postName;
private Long deptId;
private String deptName;
private Long parentId;
private String tenantName;
SysRole roleList;
/**
* 超级管理员访问某个特定租户
*/
private String subTenantId;
public String getPostName() {
return postName;
}
public void setPostName(String postName) {
this.postName = postName;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public SysRole getRoleList() {
return roleList;
}
public void setRoleList(SysRole roleList) {
this.roleList = roleList;
}
public List<SysPermission> getPermissions() {
return permissions;
}
public void setPermissions(List<SysPermission> permissions) {
this.permissions = permissions;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getSubTenantId() {
return subTenantId;
}
public void setSubTenantId(String subTenantId) {
this.subTenantId = subTenantId;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@Override
@JsonIgnore
public Collection<? extends GrantedAuthority> getAuthorities() {
return permissions.parallelStream().filter(p -> !StringUtils.isEmpty(p.getPermission()))
.map(p -> new SimpleGrantedAuthority(p.getPermission())).collect(Collectors.toSet());
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
// do nothing
}
// 账户是否未过期
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
// 账户是否未锁定
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return getStatus() != Status.LOCKED;
}
// 密码是否未过期
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
// 账户是否激活
@JsonIgnore
@Override
public boolean isEnabled() {
return true;
}
public Long getLoginTime() {
return loginTime;
}
public void setLoginTime(Long loginTime) {
this.loginTime = loginTime;
}
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
public String getTenantName() {
return tenantName;
}
public void setTenantName(String tenantName) {
this.tenantName = tenantName;
}
}
package cn.wise.sc.consume.business.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Map;
/**
* 分页查询参数
*
* @author zhutianwei
*
* 说明: 页码start 每页返回数量 length 其他筛选字段按照对象传入 sql:limit start*length length
* 时间筛选 beginTime endTime
* 排序 orderBy 例如order by payTime desc
*
*/
public class PageTableRequest implements Serializable {
private static final long serialVersionUID = 7328071045193618467L;
@ApiModelProperty("当前页数(从1开始)")
private Long current;
@ApiModelProperty("当前每页显示数")
private Long size;
public Long getCurrent() {
return current;
}
public void setCurrent(Long current) {
this.current = current;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
}
package cn.wise.sc.consume.business.model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Data
public class ReceivedAppListVO {
private Long id;
@ApiModelProperty("优惠券码")
private String couponCode;
@ApiModelProperty("优惠券logo")
private String couponLogo;
}
package cn.wise.sc.consume.business.model;
import java.io.Serializable;
public class ResponseInfo implements Serializable {
private static final long serialVersionUID = -4417715614021482064L;
private String code;
private String message;
public ResponseInfo(String code, String message) {
super();
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package cn.wise.sc.consume.business.model;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* <p>
*
* </p>
*
* @author ztw
* @since 2020-06-17
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class SysEnterpriseDto extends SysEnterprise {
private static final long serialVersionUID=1L;
}
package cn.wise.sc.consume.business.model;
import java.io.Serializable;
/**
* Restful方式登陆token
*
* @author 小威老师 xiaoweijiagou@163.com
*
* 2017年8月4日
*/
public class Token implements Serializable {
private static final long serialVersionUID = 6314027741784310221L;
private String token;
/** 登陆时间戳(毫秒) */
private Long loginTime;
public Token(String token, Long loginTime) {
super();
this.token = token;
this.loginTime = loginTime;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Long getLoginTime() {
return loginTime;
}
public void setLoginTime(Long loginTime) {
this.loginTime = loginTime;
}
}
/**
* @author neo.shu
* @since 2020/6/12 13:48
*/
package cn.wise.sc.consume.business;
\ No newline at end of file
package cn.wise.sc.consume.business.security;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HttpStatusLoginFailureHandler implements AuthenticationFailureHandler {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType("text/html;charset=utf-8");
Wrapper wrapper = null;
if(exception.getMessage().equals("Bad credentials")){
wrapper = WrapMapper.error("密码错误");
}else{
wrapper = WrapMapper.error(exception.getMessage());
}
response.getWriter().write(objectMapper.writeValueAsString(wrapper));
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.security;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
public class JsonLoginConfigurer<T extends JsonLoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B> {
private MyUsernamePasswordAuthenticationFilter authFilter;
public JsonLoginConfigurer() {
this.authFilter = new MyUsernamePasswordAuthenticationFilter();
}
@Override
public void configure(B http) throws Exception {
//设置Filter使用的AuthenticationManager,这里取公共的即可
authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
//设置失败的Handler
authFilter.setAuthenticationFailureHandler(new HttpStatusLoginFailureHandler());
//不将认证后的context放入session
authFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
MyUsernamePasswordAuthenticationFilter filter = postProcess(authFilter);
//指定Filter的位置
http.addFilterAfter(filter, LogoutFilter.class);
}
//设置成功的Handler,这个handler定义成Bean,所以从外面set进来
public JsonLoginConfigurer<T,B> loginSuccessHandler(AuthenticationSuccessHandler authSuccessHandler){
authFilter.setAuthenticationSuccessHandler(authSuccessHandler);
return this;
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.security;
import cn.wise.sc.consume.business.entity.SysUser;
import cn.wise.sc.consume.business.security.jwt.JwtUserService;
import cn.wise.sc.consume.business.service.SmsAuthService;
import cn.wise.sc.consume.business.service.impl.SmsAuthServiceImpl;
import cn.wise.sc.consume.business.wrapper.WrapMapper;
import cn.wise.sc.consume.business.wrapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {
private JwtUserService jwtUserService;
public JsonLoginSuccessHandler(JwtUserService jwtUserService) {
this.jwtUserService = jwtUserService;
}
private ObjectMapper objectMapper = new ObjectMapper();
private static final String ADMIN_LOGIN_TOKEN = "shiro:token:tmp:admin";
@Autowired
private SmsAuthService smsAuthService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
//生成token,并把token加密相关信息缓存,具体请看实现类
String token = jwtUserService.saveUserLoginInfo((UserDetails)authentication.getPrincipal());
response.setHeader("Authorization", token);
response.setContentType("text/html;charset=utf-8");
SysUser sysUser = (SysUser) authentication.getPrincipal();
sysUser.setPassword(null);
Wrapper wrapper = WrapMapper.wrap(200,"登陆成功",sysUser);
/*if(sysUser.getIsAdmin() != 0){
response.setHeader("Authorization", "");
stringRedisTemplate.opsForValue().set(ADMIN_LOGIN_TOKEN + sysUser.getPhone(), token, 10, TimeUnit.MINUTES);
if (StringUtils.isNoneBlank(sysUser.getPhone()) && smsAuthService.getSendDate(sysUser.getPhone(), SmsAuthServiceImpl.LOGIN)) {
smsAuthService.sendMesModel(sysUser.getPhone(), SmsAuthServiceImpl.LOGIN);
*//* if (ret) {
wrapper = WrapMapper.wrap(200,"发送验证码成功");
}*//*
}else{
wrapper = WrapMapper.wrap(400,"发送验证码失败");
}
}*/
response.getWriter().write(objectMapper.writeValueAsString(wrapper));
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.security;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.consume.business.model.LoginUser;
import cn.wise.sc.consume.business.service.TokenService;
import cn.wise.sc.consume.business.util.JwtUtil;
import cn.wise.sc.consume.business.util.UserUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private RequestMatcher requiresAuthenticationRequestMatcher;
private List<RequestMatcher> permissiveRequestMatchers;
private AuthenticationManager authenticationManager;
@Autowired
private TokenService tokenService;
@Autowired
private UserDetailsService userDetailsService;
private static final Long MINUTES_10 = 10 * 60 * 1000L;
public static final String TOKEN_KEY = "token";
private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
private AuthenticationFailureHandler failureHandler = new HttpStatusLoginFailureHandler();
public JwtAuthenticationFilter() {
this.requiresAuthenticationRequestMatcher = new RequestHeaderRequestMatcher("Authorization");
}
@Override
public void afterPropertiesSet() {
Assert.notNull(authenticationManager, "authenticationManager must be specified");
Assert.notNull(successHandler, "AuthenticationSuccessHandler must be specified");
Assert.notNull(failureHandler, "AuthenticationFailureHandler must be specified");
}
protected String getJwtToken(HttpServletRequest request) {
String authInfo = request.getHeader("Authorization");
return StringUtils.removeStart(authInfo, "Bearer ");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String pf = request.getHeader("platform");
if(StringUtils.isEmpty(pf)){
if (!requiresAuthentication(request, response)) {
filterChain.doFilter(request, response);
return;
}
Authentication authResult = null;
AuthenticationException failed = null;
try {
String token = getJwtToken(request);
if (StringUtils.isNotBlank(token)) {
JwtAuthenticationToken authToken = new JwtAuthenticationToken(JWT.decode(token));
authResult = this.getAuthenticationManager().authenticate(authToken);
} else {
failed = new InsufficientAuthenticationException("JWT is Empty");
}
} catch (JWTDecodeException e) {
logger.error("JWT format error", e);
failed = new InsufficientAuthenticationException("JWT format error", failed);
} catch (InternalAuthenticationServiceException e) {
logger.error(
"An internal error occurred while trying to authenticate the user.",
failed);
failed = e;
} catch (AuthenticationException e) {
// Authentication failed
failed = e;
}
if (authResult != null) {
successfulAuthentication(request, response, filterChain, authResult);
} else if (!permissiveRequest(request)) {
unsuccessfulAuthentication(request, response, failed);
return;
}
setHeaderSubTenant(request);
}else{
String token = request.getHeader("Authorization");
Authentication authResult = null;
AuthenticationException failed = null;
if (StringUtils.isNotBlank(token)) {
LoginUser loginUser = null;
try {
loginUser = JwtUtil.parserToken(token);
} catch (Exception e) {
e.printStackTrace();
}
if (loginUser != null) {
loginUser = checkLoginTime(loginUser);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser,
null,null);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
// LoginUser loginUser = tokenService.getLoginUser(token);
}
}
//判断添加subTenantId
filterChain.doFilter(request, response);
}
/**
* 校验时间<br>
* 过期时间与当前时间对比,临近过期10分钟内的话,自动刷新缓存
*
* @param loginUser
* @return
*/
private LoginUser checkLoginTime(LoginUser loginUser) {
long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MINUTES_10) {
String token = loginUser.getToken();
loginUser = (LoginUser) userDetailsService.loadUserByUsername(loginUser.getUsername()+"&app");
loginUser.setToken(token);
tokenService.refresh(loginUser);
}
return loginUser;
}
/**
* 如果从请求头中获取到了Sub-Tenant-Id标签 说明是超级管理员访问租户
*
* @param request
*/
private void setHeaderSubTenant(HttpServletRequest request) {
String authInfo = request.getHeader("Sub-Tenant-Id");
if (StrUtil.isNotEmpty(authInfo)) {
//向SecurityContextHolder中的用户信息,添加SubTenantId
LoginUser loginUser = UserUtil.getLoginUser();
loginUser.setSubTenantId(authInfo);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
loginUser, null, loginUser.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
}
}
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
SecurityContextHolder.clearContext();
failureHandler.onAuthenticationFailure(request, response, failed);
}
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain, Authentication authResult)
throws IOException, ServletException {
SecurityContextHolder.getContext().setAuthentication(authResult);
successHandler.onAuthenticationSuccess(request, response, authResult);
}
protected AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
protected boolean requiresAuthentication(HttpServletRequest request,
HttpServletResponse response) {
return requiresAuthenticationRequestMatcher.matches(request);
}
protected boolean permissiveRequest(HttpServletRequest request) {
if (permissiveRequestMatchers == null)
return false;
for (RequestMatcher permissiveMatcher : permissiveRequestMatchers) {
if (permissiveMatcher.matches(request))
return true;
}
return false;
}
public void setPermissiveUrl(String... urls) {
if (permissiveRequestMatchers == null)
permissiveRequestMatchers = new ArrayList<>();
for (String url : urls)
permissiveRequestMatchers.add(new AntPathRequestMatcher(url));
}
public void setAuthenticationSuccessHandler(
AuthenticationSuccessHandler successHandler) {
Assert.notNull(successHandler, "successHandler cannot be null");
this.successHandler = successHandler;
}
public void setAuthenticationFailureHandler(
AuthenticationFailureHandler failureHandler) {
Assert.notNull(failureHandler, "failureHandler cannot be null");
this.failureHandler = failureHandler;
}
protected AuthenticationSuccessHandler getSuccessHandler() {
return successHandler;
}
protected AuthenticationFailureHandler getFailureHandler() {
return failureHandler;
}
}
package cn.wise.sc.consume.business.security;
import java.util.Collection;
import java.util.Collections;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JwtAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = 3981518947978158945L;
private UserDetails principal;
private String credentials;
private DecodedJWT token;
public JwtAuthenticationToken(DecodedJWT token) {
super(Collections.emptyList());
this.token = token;
}
public JwtAuthenticationToken(UserDetails principal, DecodedJWT token, Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.token = token;
}
@Override
public void setDetails(Object details) {
super.setDetails(details);
this.setAuthenticated(true);
}
@Override
public Object getCredentials() {
return credentials;
}
@Override
public Object getPrincipal() {
return principal;
}
public DecodedJWT getToken() {
return token;
}
}
package cn.wise.sc.consume.business.security;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
public class JwtLoginConfigurer<T extends JwtLoginConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B> {
private JwtAuthenticationFilter authFilter;
public JwtLoginConfigurer() {
this.authFilter = new JwtAuthenticationFilter();
}
@Override
public void configure(B http) throws Exception {
authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
authFilter.setAuthenticationFailureHandler(new HttpStatusLoginFailureHandler());
JwtAuthenticationFilter filter = postProcess(authFilter);
http.addFilterBefore(filter, LogoutFilter.class);
}
public JwtLoginConfigurer<T, B> permissiveRequestUrls(String ... urls){
authFilter.setPermissiveUrl(urls);
return this;
}
public JwtLoginConfigurer<T, B> tokenValidSuccessHandler(AuthenticationSuccessHandler successHandler){
authFilter.setAuthenticationSuccessHandler(successHandler);
return this;
}
}
package cn.wise.sc.consume.business.security;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.wise.sc.consume.business.security.jwt.JwtUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JwtRefreshSuccessHandler implements AuthenticationSuccessHandler{
private static final int tokenRefreshInterval = 10000; //刷新间隔5分钟
private JwtUserService jwtUserService;
public JwtRefreshSuccessHandler(JwtUserService jwtUserService) {
this.jwtUserService = jwtUserService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
DecodedJWT jwt = ((JwtAuthenticationToken)authentication).getToken();
boolean shouldRefresh = shouldTokenRefresh(jwt.getIssuedAt());
if(shouldRefresh) {
String newToken = jwtUserService.saveUserLoginInfo((UserDetails)authentication.getPrincipal());
response.setHeader("Authorization", newToken);
}
}
protected boolean shouldTokenRefresh(Date issueAt){
LocalDateTime issueTime = LocalDateTime.ofInstant(issueAt.toInstant(), ZoneId.systemDefault());
return LocalDateTime.now().minusSeconds(tokenRefreshInterval).isAfter(issueTime);
}
}
package cn.wise.sc.consume.business.security;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.www.NonceExpiredException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
public class MyUsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private static final String SHIRO_TOKEN_SMSCODE = "shiro:token:smscode";
public static final String VERIFY_CODE= "RANDOMVALIDATECODEKEY";//放到session中的key
public MyUsernamePasswordAuthenticationFilter() {
//拦截url为 "/login" 的POST请求
super(new AntPathRequestMatcher("/login", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
//从json中获取username和password
String body = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
String username = null, password = null, verifyInput = null;
if(StringUtils.hasText(body)) {
JSONObject jsonObj = JSON.parseObject(body);
username = jsonObj.getString("username");
password = jsonObj.getString("password");
verifyInput = jsonObj.getString("verifyInput");
}
if (username == null)
username = "";
if (password == null)
password = "";
username = username.trim();
/* if(StringUtils.isEmpty(verifyInput)){
throw new NonceExpiredException("请输入验证码");
}
String verifyRedis = stringRedisTemplate.opsForValue().get(VERIFY_CODE + username);
if (verifyInput == null || verifyRedis==null) {
throw new NonceExpiredException("验证码失效");
}
if (verifyInput.equals(verifyRedis)) {
stringRedisTemplate.delete(VERIFY_CODE + username);
} else {
throw new NonceExpiredException("验证码错误");
}*/
//封装到token中提交
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
return super.getAuthenticationManager().authenticate(authRequest);
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.security;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;
public class OptionsRequestFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if(request.getMethod().equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,HEAD");
response.setHeader("Access-Control-Allow-Headers", response.getHeader("Access-Control-Request-Headers"));
return;
}
filterChain.doFilter(request, response);
}
}
package cn.wise.sc.consume.business.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.wise.sc.consume.business.security.jwt.JwtUserService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.LogoutHandler;
public class TokenClearLogoutHandler implements LogoutHandler {
private JwtUserService jwtUserService;
public TokenClearLogoutHandler(JwtUserService jwtUserService) {
this.jwtUserService = jwtUserService;
}
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
clearToken(authentication);
}
protected void clearToken(Authentication authentication) {
if(authentication == null)
return;
UserDetails user = (UserDetails)authentication.getPrincipal();
if(user!=null && user.getUsername()!=null)
jwtUserService.deleteUserLoginInfo(user.getUsername());
}
}
package cn.wise.sc.consume.business.security.jwt;
import java.util.Calendar;
import cn.wise.sc.consume.business.model.LoginUser;
import cn.wise.sc.consume.business.security.JwtAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.NonceExpiredException;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
public class JwtAuthenticationProvider implements AuthenticationProvider{
private JwtUserService userService;
public JwtAuthenticationProvider(JwtUserService userService) {
this.userService = userService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
DecodedJWT jwt = ((JwtAuthenticationToken)authentication).getToken();
if(jwt.getExpiresAt().before(Calendar.getInstance().getTime())) {
throw new NonceExpiredException("账号登陆时效已过请重新登陆");
}
String username = jwt.getSubject();
LoginUser user = userService.getUserLoginInfo(username);
/*if(!user.getTenantId().equals("0")){
SysTenant tenant = tenantDao.getByTenantId(user.getTenantId());
if(null == tenant || tenant.getIsDelete() == 0 ){
throw new NonceExpiredException("租户信息已删除");
}
if(tenant.getStatus() == 0){
throw new NonceExpiredException("企业申请已通过,请联系管理员审核");
}
}*/
if(user == null || user.getPassword()==null) {
throw new NonceExpiredException("账号登陆时效已过请重新登陆");
}
String encryptSalt = user.getPassword();
try {
Algorithm algorithm = Algorithm.HMAC256(encryptSalt);
JWTVerifier verifier = JWT.require(algorithm)
.withSubject(username)
.build();
verifier.verify(jwt.getToken());
} catch (Exception e) {
throw new BadCredentialsException("JWT token认证失败", e);
}
JwtAuthenticationToken token = new JwtAuthenticationToken(user, jwt, user.getAuthorities());
return token;
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.isAssignableFrom(JwtAuthenticationToken.class);
}
}
package cn.wise.sc.consume.business.security.jwt;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import cn.wise.sc.consume.business.entity.SysPermission;
import cn.wise.sc.consume.business.entity.SysUser;
import cn.wise.sc.consume.business.mapper.SysPermissionMapper;
import cn.wise.sc.consume.business.mapper.SysUserMapper;
import cn.wise.sc.consume.business.model.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCrypt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Service;
@Service
public class JwtUserService implements UserDetailsService {
// @Autowired
// private PasswordEncoder passwordEncoder;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private SysUserMapper userMapper;
@Autowired
private SysPermissionMapper permissionDao;
/* public JwtUserService() {
//默认使用 bcrypt, strength=10
this.passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
}*/
public LoginUser getUserLoginInfo(String username) {
/**
* 从数据库或者缓存中取出jwt token生成时用的salt
*/
String salt = (String) redisTemplate.opsForValue().get("token:" + username);
LoginUser user = (LoginUser) loadUserByUsername(username);
//将salt放到password字段返回
user.setPassword(salt);
return user;
}
public String saveUserLoginInfo(UserDetails user) {
String salt = BCrypt.gensalt();
/**
* 将salt保存到数据库或者缓存中
*/
redisTemplate.opsForValue().set("token:" + user.getUsername(), salt, 3600, TimeUnit.SECONDS);
Algorithm algorithm = Algorithm.HMAC256(salt);
Date date = new Date(System.currentTimeMillis() + 3600 * 1000); //设置1小时后过期
return JWT.create()
.withNotBefore(new Date(System.currentTimeMillis()))
.withSubject(user.getUsername())
.withExpiresAt(date)
.withIssuedAt(new Date(System.currentTimeMillis()))
.sign(algorithm);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = userMapper.getUser(username.split("&")[0]);
if (sysUser == null) {
throw new AuthenticationCredentialsNotFoundException("用户名不存在");
} else if (sysUser.getStatus() == SysUser.Status.LOCKED) {
throw new LockedException("用户被锁定,请联系管理员");
} else if (sysUser.getStatus() == SysUser.Status.DISABLED) {
throw new DisabledException("用户已作废");
}
LoginUser loginUser = new LoginUser();
BeanUtils.copyProperties(sysUser, loginUser);
if(username!=null && username.split("&").length==1){
List<SysPermission> permissions = permissionDao.listByUserId(sysUser.getId());
loginUser.setPermissions(permissions);
}
return loginUser;
}
public void deleteUserLoginInfo(String username) {
/**
* 清除数据库或者缓存中登录salt
*/
redisTemplate.delete("token:" + username);
}
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.RefEntityEnclosure;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-03
*/
public interface IRefEntityEnclosureService extends IService<RefEntityEnclosure> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.model.ReceivedAppListVO;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface ISysCouponDetailService extends IService<SysCouponDetail> {
List<ReceivedAppListVO> getReceivedList(String coridc, String usridc );
void beVerdue();
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysCoupon;
import cn.wise.sc.consume.business.model.CouponAppListVO;
import cn.wise.sc.consume.business.model.CouponDetailVO;
import cn.wise.sc.consume.business.model.CouponListVO;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface ISysCouponService extends IService<SysCoupon> {
List<CouponListVO> getPage(Map<String,Object> map);
CouponDetailVO getCouponDetail(Long id);
List<CouponAppListVO> getCouponAppList(String coridc, String usridc);
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.model.EnterpriseAppListVO;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-06-17
*/
public interface ISysEnterpriseService extends IService<SysEnterprise> {
List<SysEnterprise> getPage(Map<String,Object> map);
List<EnterpriseAppListVO> getEnterpriseList(String usridc);
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysMember;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-08-03
*/
public interface ISysMemberService extends IService<SysMember> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysPermission;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface ISysPermissionService extends IService<SysPermission> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysRole;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface ISysRoleService extends IService<SysRole> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysUserCoupon;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
public interface ISysUserCouponService extends IService<SysUserCoupon> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysUser;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
public interface ISysUserService extends IService<SysUser> {
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SmsAuth;
public interface SmsAuthService {
void save(SmsAuth smsAuth);
Boolean getSendDate(String phone, String type);
Boolean sendMesModel(String phone, String type);
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.entity.SysLogs;
/**
* 日志service
*
* @author 小威老师 xiaoweijiagou@163.com
*
* 2017年8月19日
*/
public interface SysLogService {
void save(SysLogs sysLogs);
void save(String userId, String module, Integer flag, String remark);
void deleteLogs();
}
package cn.wise.sc.consume.business.service;
import cn.wise.sc.consume.business.model.LoginUser;
import cn.wise.sc.consume.business.model.Token;
/**
* Token管理器<br>
* 可存储到redis或者数据库<br>
* 具体可看实现类<br>
* 默认基于redis,实现类为 TokenServiceJWTImpl<br>
* 如要换成数据库存储,将TokenServiceImpl类上的注解@Primary挪到com.boot.security.server.service.impl.TokenServiceDbImpl
*
*
* @author zhutianwei
*
*/
public interface TokenService {
Token saveToken(LoginUser loginUser);
void refresh(LoginUser loginUser);
LoginUser getLoginUser(String token);
boolean deleteToken(String token);
}
package cn.wise.sc.consume.business.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.entity.SysMember;
import cn.wise.sc.consume.business.entity.SysUserCoupon;
import cn.wise.sc.consume.business.entity.cmbnoenet.AllInOneNetUtil;
import cn.wise.sc.consume.business.entity.cmbnoenet.model.*;
import cn.wise.sc.consume.business.mapper.SysEnterpriseMapper;
import cn.wise.sc.consume.business.model.CouponAppListVO;
import cn.wise.sc.consume.business.model.EnterpriseAppListVO;
import cn.wise.sc.consume.business.model.ReceivedAppListVO;
import cn.wise.sc.consume.business.model.SysEnterpriseDto;
import cn.wise.sc.consume.business.service.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 招行一卡通 支付
*/
@Slf4j
@Service
@PropertySource("classpath:wechat.properties")
@ConfigurationProperties(prefix = "wechat.mp")
public class CMBOneNetPayService {
private static final Logger log = LoggerFactory.getLogger("CMBOneNetPayService");
@Value("${wechat.oneNet.merId}")
private String merId;
@Value("${wechat.oneNet.tppidc}")
private String tppidc;
@Autowired
private ISysEnterpriseService enterpriseService;
@Autowired
private ISysMemberService memberService;
@Autowired
private ISysCouponService couponService;
@Autowired
private ISysCouponDetailService couponDetailService;
@Autowired
private ISysUserCouponService userCouponService;
/**
* 解析app端授权信息
*
* @param signature Token 报文签名信息,使用开放平台私钥对加密后的数据的哈希值进 行签名。采用 2048 位 RSA 密钥签名时,其长度固定为 344 字节
* @param data 采用分行小程序公钥进行 RSA 加密后的 Token 报文
* @return
*/
public BaseResponse getUserInforMation(String signature, String data) {
if (StrUtil.isEmpty(data) || StrUtil.isEmpty(signature)) {
return BaseResponse.error("signature和data为必填项!", this.getClass().getName());
}
// signature和 data转码 signature和目前用不上
signature = transcoding(signature);
data = transcoding(data);
System.out.println("==================data===================");
System.out.println(data);
try {
String token = AllInOneNetUtil.decrypt(AllInOneNetUtil.priKey, data);
CMBOneNetTokenInfo cmbOneNetTokenInfo = JSON.parseObject(token, CMBOneNetTokenInfo.class);
return BaseResponse.ok(cmbOneNetTokenInfo);
} catch (Exception e) {
log.error("招行一卡通手令牌解析异常! 参数:{}", data);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 判断企业申请状态
*
* @param coridc 企业id
* @return
*/
public BaseResponse getUserInfo(String coridc) {
if (StrUtil.isEmpty(coridc) ) {
return BaseResponse.error("coridc为必填项!", this.getClass().getName());
}
try {
QueryWrapper<SysEnterprise> wrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(coridc)) {
wrapper.eq("coridc", coridc);
}
SysEnterprise e = enterpriseService.getOne(wrapper);
if (e == null || e.getId() == null) {
return BaseResponse.ok("register Enterprise");
}else{
return BaseResponse.ok(e);
}
} catch (Exception e) {
log.error("判断企业申请状态异常! 参数:{}", coridc);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 企业入驻申请
*
* @param enterpriseDto 申请企业类
* @return
*/
public BaseResponse applyEnterprise(SysEnterpriseDto enterpriseDto) {
try {
QueryWrapper<SysEnterprise> wrapper = new QueryWrapper<>();
if (StringUtils.isNotBlank(enterpriseDto.getCoridc())) {
wrapper.eq("coridc", enterpriseDto.getCoridc());
}
SysEnterprise e = enterpriseService.getOne(wrapper);
if (e != null) {
return BaseResponse.error("企业信息已存在!", this.getClass().getName());
}
//保存企业表信息
SysEnterprise enterprise = enterpriseDto;
enterprise.setStatus(2);//app端申请的企业为待审批状态,需要管理员在管理端审批后才能正常使用
enterprise.setIsDelete(1);
enterprise.setCreateTime(LocalDateTime.now());
enterpriseService.save(enterprise);
return BaseResponse.ok("成功");
} catch (Exception e) {
log.error("企业入驻申请异常! 参数:{}", enterpriseDto.getEnterpriseName());
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 企业列表 (展示审批通过的企业信息,和当前app的用户id是否已经绑定会员信息)
* @return
*/
public BaseResponse getEnterpriseList(String usridc) {
try {
List<EnterpriseAppListVO> enterpriseAppListVOS = enterpriseService.getEnterpriseList(usridc);
return BaseResponse.ok(enterpriseAppListVOS);
} catch (Exception e) {
log.error("企业列表异常! 参数:{}", usridc);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 会员申请
* @return
*/
public BaseResponse applyMember(SysMember sysMember) {
try {
sysMember.setCreateTime(LocalDateTime.now());
memberService.save(sysMember);
return BaseResponse.ok("成功");
} catch (Exception e) {
log.error("会员申请异常! 参数:{}", sysMember);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 企业优惠券列表 领券列表
* @return
*/
public BaseResponse getCouponAppList(String coridc, String usridc) {
try {
couponDetailService.beVerdue();
List<CouponAppListVO> list = couponService.getCouponAppList(coridc, usridc);
return BaseResponse.ok(list);
} catch (Exception e) {
log.error("企业优惠券列表异常! 参数:{}", coridc+","+usridc);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**领取优惠券
*
* @param couponId 优惠券表id
* @param usridc 企业用户id
* @return
*/
public BaseResponse receive(String couponId, String usridc) {
try {
QueryWrapper<SysCouponDetail> couponDetailWrapper = new QueryWrapper<>();
couponDetailWrapper.eq("coupon_id", couponId);
couponDetailWrapper.eq("is_delete",1);
couponDetailWrapper.eq("is_receive",0);
List<SysCouponDetail> list = couponDetailService.list(couponDetailWrapper);
if(list == null || list.size()<=0){
return BaseResponse.error("无可用优惠券!", this.getClass().getName());
}
SysCouponDetail couponDetail = list.get(0);
SysUserCoupon userCoupon = new SysUserCoupon();
userCoupon.setUserId(usridc);
userCoupon.setCouponDetailId(couponDetail.getId());
userCoupon.setIsUse(0);
userCoupon.setCreateTime(LocalDateTime.now());
userCouponService.save(userCoupon);
couponDetail.setIsReceive(1);
couponDetailService.save(couponDetail);
return BaseResponse.ok("成功");
} catch (Exception e) {
log.error("领取优惠券异常! 参数:{}", couponId+","+usridc);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**已领取优惠券列表
*
* @param coridc 企业编号
* @param usridc 企业用户id
* @return
*/
public BaseResponse getReceivedList(String coridc, String usridc) {
try {
List<ReceivedAppListVO> list = couponDetailService.getReceivedList(coridc, usridc);
return BaseResponse.ok(list);
} catch (Exception e) {
log.error("领取优惠券异常异常! 参数:{}", coridc+","+usridc);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
//复制券码即可在链接中使用 不用接口
//根据第三方接口查询券码是否使用,如果使用改变用户优惠券表的使用状态。
public BaseResponse useCoupon(Long couponDetailId) {
try {
QueryWrapper<SysUserCoupon> userCouponWrapper = new QueryWrapper<>();
userCouponWrapper.eq("coupon_detail_id", couponDetailId);
SysUserCoupon userCoupon = userCouponService.getOne(userCouponWrapper);
if(userCoupon == null){
return BaseResponse.error("优惠券信息错误!", this.getClass().getName());
}
if(userCoupon.getIsUse() != 0 ){
return BaseResponse.error("优惠券已使用或一过期!", this.getClass().getName());
}
userCoupon.setIsUse(1);
userCoupon.setUseTime(LocalDateTime.now());
userCouponService.updateById(userCoupon);
return BaseResponse.ok("成功");
} catch (Exception e) {
log.error("领取优惠券异常异常! 参数:{}", couponDetailId);
return BaseResponse.error(e.getMessage(), this.getClass().getName());
}
}
/**
* 将参数中的 +换成- ,/替换成_
*
* @param waitTransStr 带处理字符串
* @return String
*/
private String transcoding(String waitTransStr) {
return waitTransStr.replace("\\+", "-").replace("\\/", "_");
}
/**
* 招行一卡通 推送订单信息
*
* @param orderNo 订单号
* @param txnAmt 金额
* @param receAccount 接收方账户
* @param receName 接收方账户名
* @param receBank 接收方开户银行
* @return
*/
public BaseResponse oneNetOrderInfo(
String orderNo, String txnAmt, String receAccount, String receName, String receBank)
throws Exception {
// 封装业务参数
CMBOneNetOrderParams params = new CMBOneNetOrderParams();
params.setCcynbr("10");
params.setMchtyp("MCHTYP004");
params.setRcvbbk("313234001089");
params.setRcveac(receAccount);
params.setReford(orderNo);
params.setTrsamt(txnAmt);
params.setRcvean(receName);
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("orderinfo", JSON.toJSONString(params));
// 请求订单信息
CMBONeNetResponse cmboNeNetResponse =
postCMBApi("", CMBOneNetRequestUrl.ORDERINFO_URL, "");
// 处理响应结果
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
Map<String, String> result = new HashMap(3);
// 解密实例流程号
CMBOneNetResponseFlow cmbOneNetResponseFlow =
decodeFlowNo(cmboNeNetResponse.getResponse().getBody());
String flow = cmbOneNetResponseFlow.getSubresult().getSeqnbr();
String merId = cmboNeNetResponse.getResponse().getHead().getTppidc();
String time = cmboNeNetResponse.getResponse().getHead().getRsptim();
String sigdat = sigdat(flow, time, time);
String srcdat = srcdat(flow, merId, time);
result.put("sigdat", sigdat);
result.put("srcdat", srcdat);
result.put("merId", merId);
return BaseResponse.ok(result);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), "招行一卡通支付");
} else {
return BaseResponse.error("唤起招行一卡通失败", "招行一卡通支付");
}
}
/**
* 获取Api访问令牌
*
* @param authCode 授权码
* @return acctkn
*/
public BaseResponse getApplyInfo(String authCode) {
if (StrUtil.isEmpty(authCode)) {
return BaseResponse.error("授权码是必填项", this.getClass().getName());
}
String body = "{\"applyinfo\":{\"autcod\":\"" + authCode + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.APPLYINFO_URL, "FOATKAPL");
} catch (Exception e) {
log.error("发起获取Api访问令牌的请求失败! 参数:{}", body);
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("解析获取访问令牌响应失败!参数:{}", response);
return BaseResponse.error("获取访问令牌失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("获取访问令牌失败!", this.getClass().getName());
}
}
/**
* 续费访问token
* 1.过期2h不得续费
* 2.续费次数超过4次 不得续费
*
* @param token 带续费的token
* @return BaseResponse
*/
public BaseResponse renewApplyInfo(String token) {
if (StrUtil.isEmpty(token)) {
return BaseResponse.error("token参数是必填的!", this.getClass().getName());
}
String body = "{\"renewinfo\":{\"acctkn\":\"" + token + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.RENEWINFO_URL, "FOATKNEW");
} catch (Exception e) {
log.error("续费Api访问令牌的请求失败! 参数:{}", body);
}
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("续费Api访问令牌的请求失败!参数:{}", response);
return BaseResponse.error("续费Api访问令牌的请求失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("续费Api访问令牌的请求失败!", this.getClass().getName());
}
}
/**
* 查询企业信息
*
* @param coridc 企业 ID
* @param acctkn 访问令牌值
* @return acctkn
*/
public BaseResponse getEnterprise(String coridc, String acctkn) {
if (StrUtil.isEmpty(coridc) || StrUtil.isEmpty(acctkn)) {
return BaseResponse.error("企业ID访问令牌值是必填项", this.getClass().getName());
}
String body = "{\"corqryitf\":{\"coridc\":\"" + coridc + "\",\"acctkn\":\"" + acctkn + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.CORQRYITF_URL, "FOCORQRY");
} catch (Exception e) {
log.error("查询企业信息请求失败! 参数:{}", JSON.toJSONString(body));
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("查询企业信息响应失败!参数:{}", response);
return BaseResponse.error("查询企业信息失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("查询企业信息失败!", this.getClass().getName());
}
}
/**
* 查询企业用户信息
*
* @param usridc 用户 ID
* @param acctkn 访问令牌值
* @return acctkn
*/
public BaseResponse getEnterpriseUser(String usridc, String acctkn) {
if (StrUtil.isEmpty(usridc) || StrUtil.isEmpty(acctkn)) {
return BaseResponse.error("用户ID访问令牌值是必填项", this.getClass().getName());
}
String body = "{\"usrqryitf\":{\"usridc\":\"" + usridc + "\",\"acctkn\":\"" + acctkn + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.USRQRYITF_URL, "FOUSRINF");
} catch (Exception e) {
log.error("查询企业用户信息请求失败! 参数:{}", JSON.toJSONString(body));
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("查询企业用户信息响应失败!参数:{}", response);
return BaseResponse.error("查询企业用户信息失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("查询企业用户信息失败!", this.getClass().getName());
}
}
/**
* 查询企业用户证件信息
*
* @param usridc 用户 ID
* @param acctkn 访问令牌值
* @return acctkn
*/
public BaseResponse getEnterpriseUserCard(String usridc, String acctkn) {
if (StrUtil.isEmpty(usridc) || StrUtil.isEmpty(acctkn)) {
return BaseResponse.error("用户ID访问令牌值是必填项", this.getClass().getName());
}
String body = "{\"usrctfitf\":{\"usridc\":\"" + usridc + "\",\"acctkn\":\"" + acctkn + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.USRCTFITF_URL, "FOUSRCTF");
} catch (Exception e) {
log.error("查询企业用户证件信息请求失败! 参数:{}", JSON.toJSONString(body));
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("查询企业用户证件信息响应失败!参数:{}", response);
return BaseResponse.error("查询企业用户证件信息失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("查询企业用户证件信息失败!", this.getClass().getName());
}
}
/**
* 查询企业核心客户号
*
* @param coridc 企业 ID
* @param acctkn 访问令牌值
* @return acctkn
*/
public BaseResponse getEnterpriseClientId(String coridc, String acctkn) {
if (StrUtil.isEmpty(coridc) || StrUtil.isEmpty(acctkn)) {
return BaseResponse.error("企业ID访问令牌值是必填项", this.getClass().getName());
}
String body = "{\"cltqryitf\":{\"coridc\":\"" + coridc + "\",\"acctkn\":\"" + acctkn + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.CLTQRYITF_URL, "FOCLTNRB");
} catch (Exception e) {
log.error("查询企业核心客户号信息请求失败! 参数:{}", JSON.toJSONString(body));
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("查询企业核心客户号信息响应失败!参数:{}", response);
return BaseResponse.error("查询企业核心客户号信息失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("查询企业核心客户号信息失败!", this.getClass().getName());
}
}
/**
* 查询自然人用户信息
*
* @param glbuid 自然人编号
* @param acctkn 访问令牌值
* @return acctkn
*/
public BaseResponse getNatural(String glbuid, String acctkn) {
if (StrUtil.isEmpty(glbuid) || StrUtil.isEmpty(acctkn)) {
return BaseResponse.error("自然人编号访问令牌值是必填项", this.getClass().getName());
}
String body = "{\"glbqryitf\":{\"glbuid\":\"" + glbuid + "\",\"acctkn\":\"" + acctkn + "\"}}";
CMBONeNetResponse cmboNeNetResponse = null;
try {
cmboNeNetResponse = postCMBApi(body, CMBOneNetRequestUrl.GLBQRYITF_URL, "FOGLBINF");
} catch (Exception e) {
log.error("查询自然人用户信息请求失败! 参数:{}", JSON.toJSONString(body));
}
String rest = JSON.toJSONString(cmboNeNetResponse);
System.out.println(rest);
// 处理响应
if (cmboNeNetResponse != null) {
if ("SUC0000".equals(cmboNeNetResponse.getResponse().getHead().getRetcod())) {
String response = null;
try {
response =
AllInOneNetUtil.decrypt(
AllInOneNetUtil.priKey, cmboNeNetResponse.getResponse().getBody());
} catch (Exception e) {
log.error("查询自然人用户信息响应失败!参数:{}", response);
return BaseResponse.error("查询自然人用户信息信息失败!", this.getClass().getName());
}
return BaseResponse.ok(response);
}
return BaseResponse.error(cmboNeNetResponse.getResponse().getHead().getRetmsg(), this.getClass().getName());
} else {
return BaseResponse.error("查询自然人用户信息失败!", this.getClass().getName());
}
}
/**
* 解密流程号
*
* @param flow 流程加密字段
* @return
*/
private CMBOneNetResponseFlow decodeFlowNo(String flow) {
if (StrUtil.isEmpty(flow)) {
throw new IllegalArgumentException("招行一卡通----流程号为空!");
}
try {
String decryptFlow = AllInOneNetUtil.decrypt(AllInOneNetUtil.priKey, flow);
return JSON.parseObject(decryptFlow, CMBOneNetResponseFlow.class);
} catch (Exception e) {
throw new RuntimeException("招行一卡通支付----解密实例流程号,异常!");
}
}
/**
* 获取唯一标识
*
* @return
*/
private String getNewMsgidc() {
Snowflake snowflake = IdUtil.createSnowflake(1, 1);
return snowflake.nextIdStr();
}
/**
* 逗号分隔,需要先加密、后签名。 流程实例号用于查订单
*
* @param seqnbr 流程实例号
* @param merId 商户编号
* @param time 时间 戳(格式为 yyyyMMddHHmmss
* @return
*/
private String sigdat(String seqnbr, String merId, String time) {
return null;
}
/**
* 逗号分隔,需要加密。流程实例号 用于查订单
*
* @param seqnbr 流程实例号
* @param merId 商户编号
* @param time 时间 戳(格式为 yyyyMMddHHmmss
* @return
*/
private String srcdat(String seqnbr, String merId, String time) {
return null;
}
/**
* 请求招行api
*
* @param body 请求体
* @param url api路径
* @param trscod 类型 招行的trscod
* @return ResponseEntity的body
*/
private CMBONeNetResponse postCMBApi(String body, String url, String trscod)
throws Exception {
System.out.println("==================body===================");
System.out.println(body);
// 加密业务参数
String bodyEncrypt = AllInOneNetUtil.encrypt(AllInOneNetUtil.pubKey, body, "utf-8");
// 设置请求体中得head字段
CMBOneNetRequestDataModel requestDataModel = new CMBOneNetRequestDataModel();
requestDataModel.setBody(bodyEncrypt);
CMBOneNetRequestDataModel.Header header = requestDataModel.new Header();
// 商户号(分行应用id)
header.setTppidc(tppidc);
// 设置请求类型
if (StrUtil.isNotEmpty(trscod)) {
header.setTrscod(trscod);
} else {
header.setTrscod("FMORDSUB");
}
// 报文唯一标识
header.setMsgidc(getNewMsgidc());
String now = DateUtil.format(new Date(), "yyyyMMddHHmmss");
header.setReqtim(now);
requestDataModel.setHead(header);
System.out.println("=====================数据域========================");
System.out.println(JSON.toJSONString(requestDataModel));
String sign = AllInOneNetUtil.sign(AllInOneNetUtil.priKey, JSON.toJSONString(requestDataModel), "utf-8");
CMBOneNetRequestModel requestModel = new CMBOneNetRequestModel();
requestModel.setRequest(requestDataModel);
requestModel.setSignature(sign);
HttpEntity<String> requestEntity =
new HttpEntity<String>(JSON.toJSONString(requestModel), new HttpHeaders());
RestTemplate template = new RestTemplate();
ResponseEntity<String> response =
template.exchange(url, HttpMethod.POST, requestEntity, String.class);
if (response.getStatusCode().value() == 200) {
String rst = response.getBody();
return JSON.parseObject(rst, CMBONeNetResponse.class);
}
return null;
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.entity.cmbnoenet.AllInOneNetUtil;
import cn.wise.sc.consume.business.entity.cmbnoenet.model.*;
import cn.wise.sc.consume.business.model.SysEnterpriseDto;
import cn.wise.sc.consume.business.service.ISysEnterpriseService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* 招行一卡通 支付
*/
@Service
public class CommonService {
private static final Logger log = LoggerFactory.getLogger("CommonService");
/**
* 生成编号
* @param prefix 编号前缀: 申请编号SQ
* @param counts 当天申请数量 生成的编号+1
* @return
*/
public String createNo(String prefix, int counts){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//注意月份是MM
String date = sdf.format(new Date());
int nextNo = counts+1;
String tailNo = counts==0?"00"+nextNo:(counts<10?"00"+nextNo:(counts<100?"0"+nextNo:String.valueOf(nextNo)));
String applyNo = prefix+date+tailNo;
return applyNo;
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.RefEntityEnclosure;
import cn.wise.sc.consume.business.mapper.RefEntityEnclosureMapper;
import cn.wise.sc.consume.business.service.IRefEntityEnclosureService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-03
*/
@Service
public class RefEntityEnclosureServiceImpl extends ServiceImpl<RefEntityEnclosureMapper, RefEntityEnclosure> implements IRefEntityEnclosureService {
}
package cn.wise.sc.consume.business.service.impl;
import cn.hutool.json.JSONException;
import cn.wise.sc.consume.business.entity.SmsAuth;
import cn.wise.sc.consume.business.mapper.SmsAuthMapper;
import cn.wise.sc.consume.business.service.SmsAuthService;
import cn.wise.sc.consume.business.util.SMSUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Service
public class SmsAuthServiceImpl implements SmsAuthService {
private static final Logger log = LoggerFactory.getLogger("adminLogger");
@Resource
private StringRedisTemplate stringRedisTemplate;
@Autowired
private SmsAuthMapper smsAuthDao;
private static final String SHIRO_TOKEN_SMSCODE = "shiro:token:smscode";
public final static String FORGET_PASSWORD = "2";//忘记密码
public final static String LOGIN = "1";//登录
//短信应用SDK AppID
private static final int appid = 1400313569; //140开头
//短信应用SDK AppKey
private static final String appkey = "e3baf74f68aebb837fe9263a3cd4c821";
//短信模板ID, 需要在短信应用中申请
private static final int TTEMPLATEID = 532621;
//签名
private static final String SMSSING = "腾闻";
@Override
public void save(SmsAuth smsAuth) {
smsAuthDao.save(smsAuth);
}
/**
* 验证短信发送时间 一分钟之内一个手机号只能发送一条
*
* @param phone
*/
@Override
public Boolean getSendDate(String phone, String type) {
try {
if (StringUtils.isNoneBlank(phone)) {
//当前时间
Date d1 = new Date();
Date endDate = new Date(d1.getTime() - 60 * 1000);//查看六十秒钱的数据
List<SmsAuth> smsAuthList = smsAuthDao.selectList(phone, type, endDate);
if (smsAuthList.size() > 0) {
//说明60秒内已经发送过短信
return false;
}
return true;
}
return false;
} catch (Exception e) {
log.error("获取验证码异常:" + e.getMessage());
}
return false;
}
/*
生成6位验证码
*/
private int random() {
Random r = new Random();
StringBuffer sb = new StringBuffer();
int[] c = new int[6];
for (int i = 0; i < 6; i++) {
c[i] = r.nextInt(9) + 1;
sb.append(c[i]);
}
return Integer.parseInt(sb.toString());
}
/**
     * 指定模板ID发送短信
     * @param number 用户手机号
     * @return OK 成功  null 失败
     */
@Override
public Boolean sendMesModel(String phone, String type){
try {
int yzm = random();
String code = Integer.toString(yzm);
Boolean result = SMSUtil.sendCode(phone, code);
if (result) {
stringRedisTemplate.delete(SHIRO_TOKEN_SMSCODE + phone.trim());
stringRedisTemplate.opsForValue().set(SHIRO_TOKEN_SMSCODE + phone.trim()+type, code, 3, TimeUnit.MINUTES);
SmsAuth smsAuth = new SmsAuth();
// smsAuth.setCreateTime(new Date());
smsAuth.setIphone(phone);
smsAuth.setCode(code);
smsAuth.setType(type);
smsAuth.setRemark(null);
return smsAuthDao.save(smsAuth);
}else{
return false;
}
} catch (HTTPException e) {
// HTTP响应码错误
e.printStackTrace();
} catch (JSONException e) {
// json解析错误
e.printStackTrace();
}
return false;
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysCouponDetail;
import cn.wise.sc.consume.business.entity.SysUserCoupon;
import cn.wise.sc.consume.business.mapper.SysCouponDetailMapper;
import cn.wise.sc.consume.business.mapper.SysUserCouponMapper;
import cn.wise.sc.consume.business.model.ReceivedAppListVO;
import cn.wise.sc.consume.business.service.ISysCouponDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Service
public class SysCouponDetailServiceImpl extends ServiceImpl<SysCouponDetailMapper, SysCouponDetail> implements ISysCouponDetailService {
@Autowired
private SysCouponDetailMapper couponDetailMapper;
@Autowired
private SysUserCouponMapper userCouponMapper;
@Override
public List<ReceivedAppListVO> getReceivedList(String coridc, String usridc) {
List<ReceivedAppListVO> list = couponDetailMapper.getReceivedList(coridc, usridc);
return list;
}
/**
* 筛选过期优惠券,将优惠券详情表:未领取的状态改成已过期。
* 优惠券领取表-未使用的状态改为已过期
*/
@Async
@Override
public void beVerdue(){
List<SysCouponDetail> verdueList = couponDetailMapper.getVerdueList();
if(verdueList!= null && verdueList.size()>0){
for(SysCouponDetail couponDetail : verdueList){
couponDetail.setIsReceive(2);
couponDetailMapper.updateById(couponDetail);
}
}
List<SysUserCoupon> verdueList2 = userCouponMapper.getVerdueList();
if(verdueList2!= null && verdueList2.size()>0){
for(SysUserCoupon userCoupon : verdueList2){
userCoupon.setIsUse(2);
userCouponMapper.updateById(userCoupon);
}
}
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysCoupon;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.mapper.SysCouponMapper;
import cn.wise.sc.consume.business.model.CouponAppListVO;
import cn.wise.sc.consume.business.model.CouponDetailVO;
import cn.wise.sc.consume.business.model.CouponListVO;
import cn.wise.sc.consume.business.service.ISysCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Service
public class SysCouponServiceImpl extends ServiceImpl<SysCouponMapper, SysCoupon> implements ISysCouponService {
private static final Logger log = LoggerFactory.getLogger("SysCouponServiceImpl");
@Autowired
private SysCouponMapper couponMapper;
@Override
public List<CouponListVO> getPage(Map<String, Object> map) {
List<CouponListVO> couponListVOS = couponMapper.getCouponPage(map);
log.debug("优惠券列表{}");
return couponListVOS;
}
@Override
public CouponDetailVO getCouponDetail(Long id) {
return couponMapper.getCouponDetail(id);
}
@Override
public List<CouponAppListVO> getCouponAppList(String coridc, String usridc) {
List<CouponAppListVO> list = couponMapper.getCouponAppList(coridc, usridc);
return list;
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysEnterprise;
import cn.wise.sc.consume.business.mapper.SysEnterpriseMapper;
import cn.wise.sc.consume.business.model.EnterpriseAppListVO;
import cn.wise.sc.consume.business.service.ISysEnterpriseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-06-17
*/
@Service
public class SysEnterpriseServiceImpl extends ServiceImpl<SysEnterpriseMapper, SysEnterprise> implements ISysEnterpriseService {
private static final Logger log = LoggerFactory.getLogger("SysEnterpriseServiceImpl");
@Resource
private SysEnterpriseMapper enterpriseMapper;
@Override
public List<SysEnterprise> getPage(Map<String,Object> map) {
List<SysEnterprise> enterprise = enterpriseMapper.getPage(map);
log.debug("企业列表{}");
return enterprise;
}
@Override
public List<EnterpriseAppListVO> getEnterpriseList(String usridc) {
List<EnterpriseAppListVO> enterpriseAppListVOS = enterpriseMapper.getEnterpriseList(usridc);
return enterpriseAppListVOS;
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysLogs;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.Map;
import java.util.function.Function;
@Service
public class SysLogServiceImpl implements IService<SysLogs> {
private static final Logger log = LoggerFactory.getLogger("SysLogServiceImpl");
@Override
public boolean saveBatch(Collection<SysLogs> entityList, int batchSize) {
return false;
}
@Override
public boolean saveOrUpdateBatch(Collection<SysLogs> entityList, int batchSize) {
return false;
}
@Override
public boolean updateBatchById(Collection<SysLogs> entityList, int batchSize) {
return false;
}
@Override
public boolean saveOrUpdate(SysLogs entity) {
return false;
}
@Override
public SysLogs getOne(Wrapper<SysLogs> queryWrapper, boolean throwEx) {
return null;
}
@Override
public Map<String, Object> getMap(Wrapper<SysLogs> queryWrapper) {
return null;
}
@Override
public <V> V getObj(Wrapper<SysLogs> queryWrapper, Function<? super Object, V> mapper) {
return null;
}
@Override
public BaseMapper<SysLogs> getBaseMapper() {
return null;
}
/* @Autowired
private SysLogsMapper sysLogsDao;
*//**
* 2018.05.12将该方法改为异步,用户由调用者设置
*
* @param sysLogs
* @see com.boot.security.server.advice.LogAdvice
*//*
@Async
@Override
public void save(SysLogs sysLogs) {
// SysUser user = UserUtil.getLoginUser();
if (sysLogs == null || sysLogs.getUser() == null || sysLogs.getUser().getId() == null) {
return;
}
// sysLogs.setUser(user);
sysLogsDao.save(sysLogs);
}
@Async
@Override
public void save(Long userId, String module, Boolean flag, String remark) {
SysLogs sysLogs = new SysLogs();
sysLogs.setFlag(flag);
sysLogs.setModule(module);
sysLogs.setRemark(remark);
SysUser user = new SysUser();
user.setId(userId);
sysLogs.setUser(user);
sysLogsDao.save(sysLogs);
}
@Override
public void deleteLogs() {
Date date = DateUtils.addMonths(new Date(), -3);
String time = DateFormatUtils.format(date, DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
int n = sysLogsDao.deleteLogs(time);
log.info("删除{}之前日志{}条", time, n);
}*/
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysLogs;
import cn.wise.sc.consume.business.mapper.SysLogsMapper;
import cn.wise.sc.consume.business.service.SysLogService;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-29
*/
@Service
public class SysLogsServiceImpl implements SysLogService {
private static final Logger log = LoggerFactory.getLogger("SysLogsServiceImpl");
@Autowired
private SysLogsMapper sysLogsDao;
/**
* 2018.05.12将该方法改为异步,用户由调用者设置
*
* @param sysLogs
*/
@Async
@Override
public void save(SysLogs sysLogs) {
// SysUser user = UserUtil.getLoginUser();
if (sysLogs == null || sysLogs.getUserId()==null ) {
return;
}
// sysLogs.setUser(user);
sysLogsDao.save(sysLogs);
}
@Async
@Override
public void save(String userId, String module, Integer flag, String remark) {
SysLogs sysLogs = new SysLogs();
sysLogs.setModule(module);
sysLogs.setFlag(flag);
sysLogs.setRemark(remark);
sysLogs.setUserId(userId);
sysLogsDao.save(sysLogs);
}
@Override
public void deleteLogs() {
Date date = DateUtils.addMonths(new Date(), -3);
String time = DateFormatUtils.format(date, DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.getPattern());
int n = sysLogsDao.deleteLogs(time);
log.info("删除{}之前日志{}条", time, n);
}
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysMember;
import cn.wise.sc.consume.business.mapper.SysMemberMapper;
import cn.wise.sc.consume.business.service.ISysMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-08-03
*/
@Service
public class SysMemberServiceImpl extends ServiceImpl<SysMemberMapper, SysMember> implements ISysMemberService {
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysPermission;
import cn.wise.sc.consume.business.mapper.SysPermissionMapper;
import cn.wise.sc.consume.business.service.ISysPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysRole;
import cn.wise.sc.consume.business.mapper.SysRoleMapper;
import cn.wise.sc.consume.business.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysUserCoupon;
import cn.wise.sc.consume.business.mapper.SysUserCouponMapper;
import cn.wise.sc.consume.business.service.ISysUserCouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-31
*/
@Service
public class SysUserCouponServiceImpl extends ServiceImpl<SysUserCouponMapper, SysUserCoupon> implements ISysUserCouponService {
}
package cn.wise.sc.consume.business.service.impl;
import cn.wise.sc.consume.business.entity.SysUser;
import cn.wise.sc.consume.business.mapper.SysUserMapper;
import cn.wise.sc.consume.business.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author ztw
* @since 2020-07-27
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
}
package cn.wise.sc.consume.business.service.impl;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import cn.wise.sc.consume.business.model.LoginUser;
import cn.wise.sc.consume.business.model.Token;
import cn.wise.sc.consume.business.service.SysLogService;
import cn.wise.sc.consume.business.service.TokenService;
import cn.wise.sc.consume.business.util.RedisUtil;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
/**
* token存到redis的实现类<br>
* jwt实现的token
*
* @author zhutianwei
*
*/
@Primary
@Service
public class TokenServiceJWTImpl implements TokenService {
private static final Logger log = LoggerFactory.getLogger("adminLogger");
/**
* token过期秒数
*/
@Value("${token.expire.seconds}")
private Integer expireSeconds;
@Autowired
private SysLogService logService;
@Autowired
RedisUtil redisUtil;
/**
* 私钥
*/
@Value("${token.jwtSecret}")
private String jwtSecret;
private static Key KEY = null;
private static final String LOGIN_USER_KEY = "LOGIN_USER_KEY";
@Override
public Token saveToken(LoginUser loginUser) {
loginUser.setToken(UUID.randomUUID().toString());
cacheLoginUser(loginUser);
// 登陆日志
logService.save(loginUser.getId().toString(), "登陆", 1, null);
String jwtToken = createJWTToken(loginUser);
return new Token(jwtToken, loginUser.getLoginTime());
}
/**
* 生成jwt
*
* @param loginUser
* @return
*/
private String createJWTToken(LoginUser loginUser) {
Map<String, Object> claims = new HashMap<>();
claims.put(LOGIN_USER_KEY, loginUser.getToken());// 放入一个随机字符串,通过该串可找到登陆用户
String jwtToken = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance())
.compact();
return jwtToken;
}
private void cacheLoginUser(LoginUser loginUser) {
loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireSeconds * 1000);
// 根据uuid将loginUser缓存
redisUtil.setString("token:"+loginUser.getUsername(),loginUser,expireSeconds);
}
/**
* 更新缓存的用户信息
*/
@Override
public void refresh(LoginUser loginUser) {
cacheLoginUser(loginUser);
}
@Override
public LoginUser getLoginUser(String jwtToken) {
String uuid = getUUIDFromJWT(jwtToken);
if (uuid != null) {
LoginUser loginUser = (LoginUser)redisUtil.getString(getTokenKey(uuid));
return loginUser;
}
return null;
}
@Override
public boolean deleteToken(String jwtToken) {
String uuid = getUUIDFromJWT(jwtToken);
if (uuid != null) {
String key = getTokenKey(uuid);
LoginUser loginUser = (LoginUser)redisUtil.getString(key);
if (loginUser != null) {
redisUtil.deleteKey(key);
// 退出日志
logService.save(loginUser.getId().toString(), "退出", 1, null);
return true;
}
}
return false;
}
private String getTokenKey(String uuid) {
return "tokens:" + uuid;
}
private Key getKeyInstance() {
if (KEY == null) {
synchronized (TokenServiceJWTImpl.class) {
if (KEY == null) {// 双重锁
byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(jwtSecret);
KEY = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());
}
}
}
return KEY;
}
private String getUUIDFromJWT(String jwtToken) {
if ("null".equals(jwtToken) || StringUtils.isBlank(jwtToken)) {
return null;
}
try {
Map<String, Object> jwtClaims = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken).getBody();
return MapUtils.getString(jwtClaims, LOGIN_USER_KEY);
} catch (ExpiredJwtException e) {
log.error("{}已过期", jwtToken);
} catch (Exception e) {
log.error("{}", e);
}
return null;
}
}
package cn.wise.sc.consume.business.util;
import java.time.LocalDateTime;
import java.time.temporal.WeekFields;
/**
* @author neo.shu
* @since 2020/4/5 22:26
*/
public class DateUtil {
/**
* 获取自然周数
* @param localDateTime
* @return
*/
public static int getWeek(LocalDateTime localDateTime) {
WeekFields weekFields = WeekFields.ISO;
return localDateTime.get(weekFields.weekOfWeekBasedYear());
}
}
package cn.wise.sc.consume.business.util;
import java.io.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.Resource;
/**
* excel工具类
*
* @author zhutianwei
*
*/
public class ExcelUtil {
public static void excelLocal(String path, String fileName, String[] headers, List<Object[]> datas) {
Workbook workbook = getWorkbook(headers, datas);
if (workbook != null) {
ByteArrayOutputStream byteArrayOutputStream = null;
FileOutputStream fileOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
String suffix = ".xls";
File file = new File(path + File.separator + fileName + suffix);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(byteArrayOutputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 导出excel
*
* @param fileName
* @param headers
* @param datas
* @param response
*/
public static void excelExport(String fileName, String[] headers, List<Object[]> datas,
HttpServletResponse response) {
Workbook workbook = getWorkbook(headers, datas);
if (workbook != null) {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
workbook.write(byteArrayOutputStream);
String suffix = ".xls";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-Disposition",
"attachment;filename=" + new String((fileName + suffix).getBytes(), "iso-8859-1"));
OutputStream outputStream = response.getOutputStream();
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* @param headers
* 列头
* @param datas
* 数据
* @return
*/
public static Workbook getWorkbook(String[] headers, List<Object[]> datas) {
Workbook workbook = new HSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = null;
Cell cell = null;
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
Font font = workbook.createFont();
int line = 0, maxColumn = 0;
if (headers != null && headers.length > 0) {// 设置列头
row = sheet.createRow(line++);
row.setHeightInPoints(23);
font.setBold(true);
font.setFontHeightInPoints((short) 13);
style.setFont(font);
maxColumn = headers.length;
for (int i = 0; i < maxColumn; i++) {
cell = row.createCell(i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
}
}
if (datas != null && datas.size() > 0) {// 渲染数据
for (int index = 0, size = datas.size(); index < size; index++) {
Object[] data = datas.get(index);
if (data != null && data.length > 0) {
row = sheet.createRow(line++);
row.setHeightInPoints(20);
int length = data.length;
if (length > maxColumn) {
maxColumn = length;
}
for (int i = 0; i < length; i++) {
cell = row.createCell(i);
cell.setCellValue(data[i] == null ? null : data[i].toString());
}
}
}
}
for (int i = 0; i < maxColumn; i++) {
sheet.autoSizeColumn(i);
}
return workbook;
}
@SuppressWarnings("resource")
public static List<Map<Integer, String>> readData(FileInputStream fis) throws Exception {
XSSFWorkbook hwb = new XSSFWorkbook(fis);
List<Map<Integer, String>> usermap = new ArrayList<>();
// 获取第一个sheet页
XSSFSheet sheetAt = hwb.getSheetAt(0);
if (sheetAt == null) {
return usermap;
}
// 遍历行里面的单元格内容.
for (int i = 1; i <= sheetAt.getLastRowNum(); i++) {
// User user = new User();
Map<Integer, String> map = new HashMap<Integer, String>();
// 得到每一行
XSSFRow row = sheetAt.getRow(i);
// 如果为空就跳出
if (row == null) {
continue;
}
// 遍历列
for (int j = 0; j < row.getLastCellNum(); j++) {
// 遍历列里面的内容
XSSFCell cell = row.getCell(j);
if (cell == null) {
map.put(j, null);
}
try {
map.put(j, cell.getStringCellValue());
} catch (Exception e) {
map.put(j, new DecimalFormat("#0").format( cell.getNumericCellValue()).toString());
}
}
usermap.add(map);
}
return usermap;
}
}
package cn.wise.sc.consume.business.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.util.TextUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 使用磁盘文件模拟accessToken和jsTicket的数据持久化
* 正式项目请是写入到Mysql等持久化存储
*
* @author openapi@dingtalk
* @date 2020/2/4
*/
public class FileUtil {
private static final String FILEPATH = "Permanent_Data";
/**
* 将json写入文件
*
* @param json 需要写入的json对象
* @param fileName 文件名称
*/
public synchronized static void write2File(Object json, String fileName) {
BufferedWriter writer = null;
File filePath = new File(FILEPATH);
JSONObject eJson = null;
if (!filePath.exists() && !filePath.isDirectory()) {
filePath.mkdirs();
}
File file = new File(FILEPATH + File.separator + fileName + ".xml");
System.out.println("path:" + file.getPath() + " abs path:" + file.getAbsolutePath());
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
System.out.println("createNewFile,出现异常:");
e.printStackTrace();
}
} else {
eJson = read2JSON(fileName);
}
try {
writer = new BufferedWriter(new FileWriter(file));
if (eJson == null) {
writer.write(json.toString());
} else {
Object[] array = ((JSONObject)json).keySet().toArray();
for (Object o : array) {
eJson.put(o.toString(), ((JSONObject)json).get(o.toString()));
}
writer.write(eJson.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读文件到json
*
* @param fileName 文件名称
* @return 文件内容Json对象
*/
public static JSONObject read2JSON(String fileName) {
File file = new File(FILEPATH + File.separator + fileName + ".xml");
if (!file.exists()) {
return null;
}
BufferedReader reader = null;
String laststr = "";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
while ((tempString = reader.readLine()) != null) {
laststr += tempString;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return (JSONObject)JSON.parse(laststr);
}
/**
* 通过key值获取文件中的value
*
* @param fileName 文件名称
* @param key key值
* @return key对应的value
*/
public static Object getValue(String fileName, String key) {
JSONObject eJSON = null;
eJSON = read2JSON(fileName);
if (null != eJSON && eJSON.containsKey(key)) {
@SuppressWarnings("unchecked")
Map<String, Object> values = JSON.parseObject(eJSON.toString(), Map.class);
return values.get(key);
} else {
return null;
}
}
public static HashMap<Long, Long> toHashMap(JSONObject js) {
if (js == null) {
return null;
}
HashMap<Long, Long> data = new HashMap<Long, Long>();
// 将json字符串转换成jsonObject
Set<String> set = js.keySet();
// 遍历jsonObject数据,添加到Map对象
for (String s : set) {
String key = String.valueOf(s);
Long keyLong = Long.valueOf(key);
String value = js.getString(key);
Long valueLong;
if (TextUtils.isEmpty(value)) {
valueLong = js.getLong(key);
} else {
valueLong = Long.valueOf(value);
}
data.put(keyLong, valueLong);
}
return data;
}
}
package cn.wise.sc.consume.business.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 用ThreadLocal来存储resquest
*/
public class GlobalHolder {
private static ThreadLocal<HttpServletRequest> requestThreadLocalHolder = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseThreadLocalHolder = new ThreadLocal<HttpServletResponse>();
public static void setHttpRequest(HttpServletRequest request){
requestThreadLocalHolder.set(request);
}
public static void setHttpResponse(HttpServletResponse response){
responseThreadLocalHolder.set(response);
}
public static void remove(){
requestThreadLocalHolder.remove();
responseThreadLocalHolder.remove();
}
public static HttpServletResponse getHttpResponse(){
return responseThreadLocalHolder.get();
}
public static HttpServletRequest getHttpRequest(){
return requestThreadLocalHolder.get();
}
public static String corpId(){
HttpServletRequest request = requestThreadLocalHolder.get();
//前台传递值
return request.getHeader("corpId");
}
}
package cn.wise.sc.consume.business.util;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
/**
* 带参数的get请求
* @param url
* @param param
* @return String
*/
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = 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 httpGet = new HttpGet(uri);
// 执行请求
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();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
/**
* 不带参数的get请求
* @param url
* @return String
*/
public static String doGet(String url) {
return doGet(url, null);
}
/**
* 带参数的post请求
* @param url
* @param param
* @return String
*/
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;
}
/**
* 不带参数的post请求
* @param url
* @return String
*/
public static String doPost(String url) {
return doPost(url, null);
}
/**
* 传送json类型的post请求
* @param url
* @param json
* @return String
*/
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;
}
}
package cn.wise.sc.consume.business.util;
import java.security.Key;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import cn.wise.sc.consume.business.model.LoginUser;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClaims;
/**
* 通过 jwt 生成token 及 验证
*
* @author wangchuang
*/
public class JwtUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtUtil.class);
private static final String SECRET_KEY = "_MeD5CiNov0_TecH";
//private static final String SECRET_KEY = "XYfbeae_A81cY3eR";
/**
* 签名算法
*/
private static final SignatureAlgorithm DEFAULTSIGN = SignatureAlgorithm.HS256;
/**
* 根据 userId 生成 token
*
* @param loginUser
* @return
*/
public static String createToken(LoginUser loginUser) {
Claims claim = new DefaultClaims();
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer(loginUser.getTenantId());
claim.put("id", loginUser.getId());
claim.put("username", loginUser.getUsername());
claim.put("nickName", loginUser.getNickName());
claim.put("phone", loginUser.getPhone());
// claim.put("bankName", loginUser.getBankName());
// claim.put("accountNo", loginUser.getAccountNo());
claim.put("timeStamp", timeStamp);
claim.putIfAbsent("isAdmin", loginUser.getIsAdmin());
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 根据 params 生成 token
*
* @return
*/
public static String createToken(JSONObject params) {
Claims claim = new DefaultClaims();
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer("goldfoam2");
Set<String> keys = params.keySet();
for (String key : keys) {
claim.put(key, params.getString(key));
}
claim.put("timeStamp", timeStamp);
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 根据 userId 生成 token
* @param userId
* @return
*/
public static String createToken(String userId) {
Claims claim = new DefaultClaims();
// claim.setAudience("www.bizconf.cn");// 设置接收方
// 设置 签发人
long timeStamp = (new Date()).getTime();
claim.setIssuer("goldwind");
claim.put("userId", userId);
claim.put("timeStamp",timeStamp);
Key signingKey = getKey(SECRET_KEY, DEFAULTSIGN.getJcaName());
JwtBuilder builder = Jwts.builder().setClaims(claim).signWith(DEFAULTSIGN, signingKey);
return builder.compact();
}
/**
* 该方法使用 HS256 算法和 Secret: 生成signKey
*
* @param key
* @param jcaName
* @return
*/
private static Key getKey(String key, String jcaName) {
byte[] keyb = null;
if ("".equals(key) || key == null) {
keyb = DatatypeConverter.parseBase64Binary(SECRET_KEY);
} else {
keyb = DatatypeConverter.parseBase64Binary(key);
}
String jcaName1 = null;
if ("".equals(jcaName) || jcaName == null) {
jcaName1 = DEFAULTSIGN.getJcaName();
} else {
jcaName1 = jcaName;
}
Key signKey = new SecretKeySpec(keyb, jcaName1);
return signKey;
}
/**
* 解析 token
*
* @param token
* @return
*/
public static LoginUser parserToken(String token) throws Exception {
Claims claims = null;
// String userid = "-1";
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
LoginUser loginUser = new LoginUser();
loginUser.setId(Long.valueOf(claims.get("id").toString()));
loginUser.setUsername(claims.get("username").toString());
loginUser.setNickName(claims.get("nickName").toString());
loginUser.setPhone(claims.get("phone").toString());
// loginUser.setBankName(claims.get("bankName").toString());
// loginUser.setAccountNo(claims.get("accountNo").toString());
loginUser.setExpireTime(Long.valueOf(claims.get("timeStamp").toString()));
loginUser.setIsAdmin(Integer.valueOf(claims.get("isAdmin").toString()));
loginUser.setTenantId(claims.getIssuer());
loginUser.setToken(token);
return loginUser;
}
/**
* 获得userId 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getUserIdByToken(String token) {
Claims claims = null;
String userid = "-1";
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
userid = (String) claims.get("id");
} catch (Exception e) {
LOGGER.info("解密userId失败:" + token);
return userid;
}
return userid;
}
/**
* 获得username 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getUserNameByToken(String token) {
Claims claims = null;
String username = "-1";
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
username = (String) claims.get("username");
} catch (Exception e) {
LOGGER.info("解密userId失败:" + token);
return username;
}
return username;
}
/**
* 获得userId 如果解析错误返回 -1
*
* @param token
* @return
*/
public static String getValueByToken(String token, String value) {
Claims claims = null;
try {
claims = Jwts.parser().setSigningKey(getKey(SECRET_KEY, DEFAULTSIGN.getJcaName())).parseClaimsJws(token)
.getBody();
value = String.valueOf(claims.get(value));
if (value == null || "".equals(value)) {
value = "-1";
return value;
}
} catch (Exception e) {
e.printStackTrace();
value = "-1";
return value;
}
return value;
}
public static void main(String[] args) throws Exception {
LoginUser loginUser = new LoginUser();
// String token = createToken(loginUser);
String token = "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJDTUJfMTI3MDMxMjQ4NjI0NzIwNjkxMiIsImlkIjozLCJ1c2VybmFtZSI6MTU5MTc1MzQ2NDAwMCwibmlja05hbWUiOiLnjovkvJ_mtpsiLCJwaG9uZSI6IjEzMDUxOTAxMTExIiwiYmFua05hbWUiOiLmtablj5Hpk7booYwiLCJhY2NvdW50Tm8iOiI2MjI4NDgxMTExMTExMTExMTEiLCJ0aW1lU3RhbXAiOjE1OTE4NDI3MzcyMTksImlzQWRtaW4iOjB9.toDSZUDj_QNafa8LO5c7Z_yanexFSa8QmrSVwvJqghs";
//eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJndyIsInVzZXJJZCI6IuW8oOS4iSJ9.M94aWta78LxBlGrWtErQfebwns9ZOobdrtz6qZUg-28
System.out.println(token);
LoginUser llll = parserToken(token);
System.out.println(llll);
// System.out.println(getValueByToken(token, "enterpriseId"));
// System.out.println(getUserIdByToken(token));
Long timeStamp = (Long) parserToken(token).getLoginTime();
long ts = System.currentTimeMillis();
if (ts - timeStamp > 1000 * 120) {
System.out.println("token超时");
} else {
System.out.println("token有效");
}
//System.out.println(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
}
}
package cn.wise.sc.consume.business.util;
import cn.wise.sc.consume.business.exception.RedisHandleException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @description:用途: redis 缓存集合
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
//---------------------- common --------------------------
/**
* 指定缓存失效时间
*
* @param key key值
* @param time 缓存时间
*/
public void expire(String key, long time) {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
} else {
throw new RedisHandleException("设置的时间不能为0或者小于0!!");
}
}
/**
* 判断key是否存在
*
* @param key 传入ke值
* @return true 存在 false 不存在
*/
public Boolean existsKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 判断key存储的值类型
*
* @param key key值
* @return DataType[string、list、set、zset、hash]
*/
public DataType typeKey(String key) {
return redisTemplate.type(key);
}
/**
* 删除指定的一个数据
*
* @param key key值
* @return true 删除成功,否则返回异常信息
*/
public Boolean deleteKey(String key) {
try {
return redisTemplate.delete(key);
} catch (Exception ex) {
throw new RedisHandleException("删除失败!", ex);
}
}
/**
* 删除多个数据
*
* @param keys key的集合
* @return true删除成功,false删除失败
*/
public Boolean deleteKey(Collection<String> keys) {
return redisTemplate.delete(keys) != 0;
}
//-------------------- String ----------------------------
/**
* 普通缓存放入
*
* @param key 键值
* @param value 值
* @return true成功 要么异常
*/
public Boolean setString(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入缓存失败!", ex);
}
}
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object getString(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 设置缓存存在时间
*
* @param key key值
* @param value value值
* @param time 时间 秒为单位
* @return 成功返回true,失败返回异常信息
*/
public boolean setString(String key, Object value, long time) {
try {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入缓存失败!", ex);
}
}
//----------------------------- list ------------------------------
/**
* 将list放入缓存
*
* @param key key的值
* @param value 放入缓存的数据
* @return true 代表成功,否则返回异常信息
*/
public Boolean setList(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 将Object数据放入List缓存,并设置时间
*
* @param key key值
* @param value 数据的值
* @param time 缓存的时间
* @return true插入成功,否则返回异常信息
*/
public Boolean setList(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForList().rightPush(key, value);
expire(key, time);
return true;
}
return false;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 将list集合放入List缓存,并设置时间
*
* @param key key值
* @param value 数据的值
* @param time 缓存的时间
* @return true插入成功,否则返回异常信息
*/
public Boolean setListAll(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForList().rightPushAll(key, value);
this.expire(key, time);
return true;
}
return false;
} catch (Exception ex) {
throw new RedisHandleException("插入List缓存失败!", ex);
}
}
/**
* 根据索引获取缓存List中的内容
*
* @param key key的值
* @param start 索引开始
* @param end 索引结束 0 到 -1代表所有值
* @return 返回数据
*/
public List<Object> getList(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception ex) {
throw new RedisHandleException("获取缓存List中的内容失败了!", ex);
}
}
/**
* 删除List缓存中多个list数据
*
* @param key key值
* @param count 移除多少个
* @param value 可以传null 或者传入存入的Value的值
* @return 返回删除了多少个
*/
public long deleteListIndex(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception ex) {
throw new RedisHandleException("删除List中的内容失败了!", ex);
}
}
/**
* 获取List缓存的数据
*
* @param key key值
* @return 返回长度
*/
public long getListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception ex) {
throw new RedisHandleException("获取List长度失败", ex);
}
}
}
package cn.wise.sc.consume.business.util;
import cn.hutool.json.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.ws.http.HTTPException;
import java.io.*;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Random;
/**
* 短信服务类
* 2020-02-10
*/
public class SMSUtil {
private static final Logger log = LoggerFactory.getLogger("adminLogger");
//短信平台参考短信平台接口文档
private static final String MESSAGE = "6db696baa08d11ea9ec30050569875ce";
private static final String PASSWORD = "123123123123123121";
private static final String UAT = "https://publicnoteserver.bcs.cmbchina.com";
private static final String URL = "/publicNoteServer/decrypt";
//短信应用SDK AppID
private static final int appid = 1400313569; //140开头
//短信应用SDK AppKey
private static final String appkey = "e3baf74f68aebb837fe9263a3cd4c821";
//短信模板ID, 需要在短信应用中申请
private static final int TTEMPLATEID = 532621;
//签名
private static final String SMSSING = "腾闻";
/**
     * 自定义短信内容发送
     * @param msg 短信内容
     * @param number 用户手机号
     * @return OK 成功  null 失败
     */
public static String sendMess(String msg , String number){
try {
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
SmsSingleSenderResult result = ssender.send(0, "86", number,msg, "", "");
System.out.print(result);
return result.errMsg;
} catch (HTTPException e) {
// HTTP响应码错误
e.printStackTrace();
} catch (JSONException e) {
// json解析错误
e.printStackTrace();
} catch (IOException e) {
// 网络IO错误
e.printStackTrace();
} catch (com.github.qcloudsms.httpclient.HTTPException e) {
e.printStackTrace();
}
return null;
}
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
     * 指定模板ID发送短信
     * @param number 用户手机号
     * @return OK 成功  null 失败
     */
public static String sendMesModel(String number){
try {
int yzm = random();
String code = Integer.toString(yzm);
String[] params = {code};;//{参数}
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
SmsSingleSenderResult result = ssender.sendWithParam("86", number,TTEMPLATEID, params, SMSSING, "", ""); // 签名参数未提供或者为空时,会使用默认签名发送短信
if (result.result == 0) {
//发送成功返回验证码
return code;
}
System.out.print(result);
return result.errMsg;//OK
} catch (HTTPException e) {
// HTTP响应码错误
e.printStackTrace();
} catch (JSONException e) {
// json解析错误
e.printStackTrace();
} catch (IOException e) {
// 网络IO错误
e.printStackTrace();
} catch (com.github.qcloudsms.httpclient.HTTPException e) {
e.printStackTrace();
}
return null;
}
//自定义方式发送短信,(不用模板和签名)
public static String send(String phoneNumbers) {
int yzm = random();
String num = Integer.toString(yzm);
SmsSingleSenderResult result = null;
try {
String smsSign = "" + yzm + "为您的登录验证码,请于2分钟内填写。如非本人操作,请忽略本短信。"; // NOTE: 这里的签名"腾讯云"只是一个示例,真实的签名需要在短信控制台中申请,另外签名参数使用的是`签名内容`,而不是`签名ID
SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
result = ssender.send(0, "86", phoneNumbers, smsSign, "", "");
if (result.result == 0) {
//发送成功返回验证码
return num;
}
} catch (HTTPException e) {
//System.out.println("HTTP响应码错误");
return result.toString();
} catch (JSONException e) {
//System.out.println("json解析错误");
return result.toString();
} catch (IOException e) {
//System.out.println(" 网络IO错误");
return result.toString();
} catch (com.github.qcloudsms.httpclient.HTTPException e) {
e.printStackTrace();
}
return result.toString();
}
/*
生成6位验证码
*/
private static int random() {
Random r = new Random();
StringBuffer sb = new StringBuffer();
int[] c = new int[6];
for (int i = 0; i < 6; i++) {
c[i] = r.nextInt(9) + 1;
sb.append(c[i]);
}
return Integer.parseInt(sb.toString());
}
public static void main(String[] args) {
// String send = SMSUtil.send("15010051933");
// String send2 = SMSUtil.sendMess("okokok", "15010051933");
try {
String message = "6db696baa08d11ea9ec30050569875ce";
String password = "123123123123123121";
String aaa = SMSUtil.enCode(message, password);
JSONObject jsonObject = new JSONObject();
jsonObject.put("enMsg",aaa);
jsonObject.put("password", password);
jsonObject.put("phoneReal", "15010051933");
jsonObject.put("keyValue1", "1234");
String jsonString = jsonObject.toJSONString();
String url = "https://publicnoteserver.bcs.cmbchina.com/publicNoteServer/decrypt";
String end = HttpClientUtil.doPostJson(url, jsonString);
System.out.println(end);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Boolean sendCode(String phone,String code){
try {
String message = MESSAGE;
String password = PASSWORD;
String aaa = SMSUtil.enCode(message, password);
JSONObject jsonObject = new JSONObject();
jsonObject.put("enMsg",aaa);
jsonObject.put("password", password);
jsonObject.put("phoneReal", phone);
jsonObject.put("keyValue1", code);
String jsonString = jsonObject.toJSONString();
String url = UAT+URL;
String end = HttpClientUtil.doPostJson(url, jsonString);
JSONObject jsonObject1 = JSONObject.parseObject(end);
return jsonObject1.getBoolean("success");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 加密方式:AES加密
* @param message
* @param password
* @return
* @throws Exception
*/
private static String enCode(String message,String password) throws Exception {
//加密
KeyGenerator generator;
generator = KeyGenerator.getInstance("AES");
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
generator.init(128,random);
SecretKey secretKey = generator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
Key key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encodeResult = cipher.doFinal(message.getBytes());
//byte[]转化为16进制字符串
StringBuffer sBuffer = new StringBuffer();
for(int i=0;i< encodeResult.length;i++) {
String hexString = Integer.toHexString(encodeResult [i] & 0xFF);
if(hexString.length() ==1) {
hexString = '0' + hexString;
}
sBuffer.append(hexString.toUpperCase());
}
String enMsg = sBuffer.toString();
return enMsg;
}
}
package cn.wise.sc.consume.business.util;
import cn.wise.sc.consume.business.model.LoginUser;
import cn.wise.sc.consume.business.security.JwtAuthenticationToken;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
public class UserUtil {
/*public static LoginUser getLoginUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
if (authentication instanceof AnonymousAuthenticationToken) {
return null;
}
if (authentication instanceof UsernamePasswordAuthenticationToken) {
return (LoginUser) authentication.getPrincipal();
}
}
return null;
}*/
public static LoginUser getLoginUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
if (authentication instanceof AnonymousAuthenticationToken) {
return null;
}
if (authentication instanceof JwtAuthenticationToken) {
JwtAuthenticationToken sysUser = (JwtAuthenticationToken) authentication;
return (LoginUser)sysUser.getPrincipal();
}
if (authentication instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken sysUser = (UsernamePasswordAuthenticationToken) authentication;
return (LoginUser)sysUser.getPrincipal();
}
}
return null;
}
}
package cn.wise.sc.consume.business.util.dfs;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import java.io.*;
/**
* 上传图片到FastDFS
*/
public class FastDFSUtils {
static {
try {
// ClientGlobal.initByProperties(FastDFSUtils.class.getClassLoader().getResource("fastdfs-client.properties").getPath());
ClientGlobal.initByProperties("fastdfs-client.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
public static String[] uploadPic(String path, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(path, extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static String[] uploadPic(InputStream inStream, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(null, size, new UploadFileSender(inStream), extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static byte[] fileDownload(String fileUrl) {
byte[] by = null;
TrackerClient trackerClient = null;
TrackerServer trackerServer = null;
StorageClient1 storageClient1 = null;
StorageServer storageServer = null;
try {
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient1 = new StorageClient1(trackerServer, storageServer);
// 根据文件标识下载文件
by = storageClient1.download_file1(fileUrl);
// 将数据写入输出流
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
return by;
}
public static String uploadPic(byte[] pic, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
// 设置图片meta信息
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// 上传且返回path
fileIds = storageClient.upload_file(pic, extName, meta_list);
return fileIds[0] + "/" + fileIds[1];
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean deletePic(String fileUrl) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
StorePath storePath = StorePath.praseFromUrl(fileUrl);
int i = storageClient.delete_file(storePath.getGroup(), storePath.getPath());
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
return i == 0;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static String deletePic(String[] fileIds) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(fileIds[0], fileIds[1]);
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds[1];
}
private static class UploadFileSender implements UploadCallback {
private InputStream inStream;
public UploadFileSender(InputStream inStream) {
this.inStream = inStream;
}
@Override
public int send(OutputStream out) throws IOException {
int readBytes;
while ((readBytes = inStream.read()) > 0) {
out.write(readBytes);
}
return 0;
}
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.util.dfs;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
public class FileTypeUtil {
private final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
private final static List<String> imageAllowFiles = Arrays
.asList(new String[] { "png", "jpg", "jpeg", "gif", "bmp" });/* 允许上传的图片格式 */
static {
getAllFileType(); // 初始化文件类型信息
}
/**
* <p>
* Discription:[getAllFileType,常见文件头信息] 注:TXT文件没有文件头
* </p>
*/
private static void getAllFileType() {
FILE_TYPE_MAP.put("jpg", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("png", "89504E47"); // PNG (png)
FILE_TYPE_MAP.put("gif", "47494638"); // GIF (gif)
FILE_TYPE_MAP.put("tif", "49492A00"); // TIFF (tif)
FILE_TYPE_MAP.put("bmp", "424D"); // Windows Bitmap (bmp)
FILE_TYPE_MAP.put("dwg", "41433130"); // CAD (dwg)
FILE_TYPE_MAP.put("html", "68746D6C3E"); // HTML (html)
FILE_TYPE_MAP.put("rtf", "7B5C727466"); // Rich Text Format (rtf)
FILE_TYPE_MAP.put("xml", "3C3F786D6C");
FILE_TYPE_MAP.put("zip", "504B0304");
FILE_TYPE_MAP.put("rar", "52617221");
FILE_TYPE_MAP.put("psd", "38425053"); // Photoshop (psd)
FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A"); // Email
// [thorough
// only]
// (eml)
FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F"); // Outlook Express (dbx)
FILE_TYPE_MAP.put("pst", "2142444E"); // Outlook (pst)
FILE_TYPE_MAP.put("xls", "D0CF11E0"); // MS Word
FILE_TYPE_MAP.put("doc", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样
FILE_TYPE_MAP.put("mdb", "5374616E64617264204A"); // MS Access (mdb)
FILE_TYPE_MAP.put("wpd", "FF575043"); // WordPerfect (wpd)
FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
FILE_TYPE_MAP.put("pdf", "255044462D312E"); // Adobe Acrobat (pdf)
FILE_TYPE_MAP.put("qdf", "AC9EBD8F"); // Quicken (qdf)
FILE_TYPE_MAP.put("pwl", "E3828596"); // Windows Password (pwl)
FILE_TYPE_MAP.put("wav", "57415645"); // Wave (wav)
FILE_TYPE_MAP.put("avi", "41564920");
FILE_TYPE_MAP.put("ram", "2E7261FD"); // Real Audio (ram)
FILE_TYPE_MAP.put("rm", "2E524D46"); // Real Media (rm)
FILE_TYPE_MAP.put("mpg", "000001BA"); //
FILE_TYPE_MAP.put("mov", "6D6F6F76"); // Quicktime (mov)
FILE_TYPE_MAP.put("asf", "3026B2758E66CF11"); // Windows Media (asf)
FILE_TYPE_MAP.put("mid", "4D546864"); // MIDI (mid)
}
/**
* <p>
* Discription:[getFileTypeByStream]
* </p>
*/
public final static String getFileTypeByStream(byte[] b) {
String filetypeHex = String.valueOf(getFileHexString(b));
Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator();
while (entryiterator.hasNext()) {
Entry<String, String> entry = entryiterator.next();
String fileTypeHexValue = entry.getValue();
if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
return entry.getKey();
}
}
return null;
}
/**
* <p>
* Discription:[getFileByFile,获取文件类型,包括图片,若格式不是已配置的,则返回null]
* </p>
*/
public final static String getFileTypeByFile(File file) {
String fileType = null;
byte[] b = new byte[50];
try {
InputStream is = new FileInputStream(file);
is.read(b);
fileType = getFileTypeByStream(b);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileType;
}
/**
* <p>
* Discription:[getFileHexString]
* </p>
*/
public final static String getFileHexString(byte[] b) {
StringBuilder stringBuilder = new StringBuilder();
if (b == null || b.length <= 0) {
return null;
}
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* <p>
* Discription:[getImageFileType,获取图片文件实际类型,若不是图片则返回null]
* </p>
*/
public final static String getImageFileType(File f) {
if (isImage(f)) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(f);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
* 只根据后缀名判断是否为图片
*
* @param file
* @return
*/
public static final boolean isImage(File file) {
return isImage(file, true);
}
/**
* <p>
* Discription:[isImage,判断文件是否为图片]
* </p>
*
* @param file
* 源文件
* @param onlyByExtension
* 是否值验证后缀名
* @return true 是 | false 否
*/
public static final boolean isImage(File file, boolean onlyByExtension) {
boolean flag = false;
try {
boolean allowFile = isImageByExtension(file.getName());
if (onlyByExtension) {
flag = allowFile;
} else {
if (allowFile) {
BufferedImage bufreader = ImageIO.read(file);
int width = bufreader.getWidth();
int height = bufreader.getHeight();
if (width == 0 || height == 0) {
flag = false;
} else {
flag = true;
}
}
}
} catch (IOException e) {
flag = false;
e.printStackTrace();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
/**
* 只通过后缀名判断是否为图片
*
* @param fileName
* @return
*/
public static final boolean isImageByExtension(String fileName) {
boolean flag = false;
String fileExtName = FilenameUtils.getExtension(fileName);
if (StringUtils.isNotBlank(fileExtName)) {
flag = imageAllowFiles.contains(fileExtName.toLowerCase());
}
return flag;
}
}
package cn.wise.sc.consume.business.util.dfs;
import cn.wise.sc.consume.business.exception.FdfsUnsupportStorePathException;
import org.apache.commons.lang3.Validate;
/**
* 存储文件的路径信息
*
* @author yuqih
*
*/
public class StorePath {
private String group;
private String path;
/** 解析路径 */
private static final String SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR = "/";
/** group */
private static final String SPLIT_GROUP_NAME = "group";
/**
* 存储文件路径
*/
public StorePath() {
}
/**
* 存储文件路径
*
* @param group
* @param path
*/
public StorePath(String group, String path) {
super();
this.group = group;
this.path = path;
}
/**
* @return the group
*/
public String getGroup() {
return group;
}
/**
* @param group
* the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path
* the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* 获取文件全路径
*
* @return
*/
public String getFullPath() {
return this.group.concat(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR).concat(this.path);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "StorePath [group=" + group + ", path=" + path + "]";
}
/**
* 从Url当中解析存储路径对象
*
* @param filePath
* 有效的路径样式为(group/path) 或者 (http://ip/group/path),路径地址必须包含group
* @return
*/
public static StorePath praseFromUrl(String filePath) {
Validate.notNull(filePath, "解析文件路径不能为空");
// 获取group起始位置
int groupStartPos = getGroupStartPos(filePath);
String groupAndPath = filePath.substring(groupStartPos);
int pos = groupAndPath.indexOf(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR);
if ((pos <= 0) || (pos == groupAndPath.length() - 1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,有效的路径样式为(group/path) 而当前解析路径为".concat(filePath));
}
String group = groupAndPath.substring(0, pos);
String path = groupAndPath.substring(pos + 1);
return new StorePath(group, path);
}
/**
* 获得group起始位置
*
* @param filePath
*/
private static int getGroupStartPos(String filePath) {
int pos = filePath.indexOf(SPLIT_GROUP_NAME);
if ((pos == -1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,被解析路径url没有group,当前解析路径为".concat(filePath));
}
return pos;
}
}
\ No newline at end of file
package cn.wise.sc.consume.business.wrapper;
import cn.wise.sc.consume.business.wrapper.page.PageUtil;
/**
* The class Page wrap mapper.
*
* @author paascloud.net@gmail.com
*/
public class PageWrapMapper {
/**
* Instantiates a new page wrap mapper.
*/
private PageWrapMapper() {
}
private static <E> PageWrapper<E> wrap(int code, String message, E o, PageUtil pageUtil) {
return new PageWrapper<E>(code, message, o, pageUtil);
}
/**
* Wrap data with default code=200.
*
* @param <E> the type parameter
* @param o the o
* @param pageUtil the page util
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(E o, PageUtil pageUtil) {
return wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o, pageUtil);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param code the code
* @param message the message
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(int code, String message) {
return wrap(code, message, null, null);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param code the code
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(int code) {
return wrap(code, null, null, null);
}
/**
* Wrap.
*
* @param <E> the type parameter
* @param e the e
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> wrap(Exception e) {
return new PageWrapper<E>(Wrapper.ERROR_CODE, e.getMessage(), null, null);
}
/**
* Un wrapper.
*
* @param <E> the type parameter
* @param wrapper the wrapper
*
* @return the e
*/
public static <E> E unWrap(PageWrapper<E> wrapper) {
return wrapper.getData();
}
/**
* Wrap ERROR. code=100
*
* @param <E> the type parameter
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> illegalArgument() {
return wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE, null, null);
}
/**
* Wrap ERROR. code=500
*
* @param <E> the type parameter
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> error() {
return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE, null, null);
}
/**
* Wrap SUCCESS. code=200
*
* @param <E> the type parameter
*
* @return the page wrapper
*/
public static <E> PageWrapper<E> ok() {
return new PageWrapper<E>();
}
}
package cn.wise.sc.consume.business.wrapper;
import cn.wise.sc.consume.business.wrapper.page.PageUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* The class Page wrapper.
*
* @param <T> the type parameter @author paascloud.net@gmail.com
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class PageWrapper<T> extends Wrapper<T> {
private static final long serialVersionUID = 666985064788933395L;
private PageUtil pageUtil;
/**
* Instantiates a new Page wrapper.
*/
PageWrapper() {
super();
}
/**
* Instantiates a new Page wrapper.
*
* @param code the code
* @param message the message
*/
public PageWrapper(int code, String message) {
super(code, message);
}
/**
* Instantiates a new pageWrapper default code=200
*
* @param result the result
* @param pageUtil the page util
*/
public PageWrapper(T result, PageUtil pageUtil) {
super();
this.setData(result);
this.setPageUtil(pageUtil);
}
/**
* Instantiates a new Page wrapper.
*
* @param code the code
* @param message the message
* @param result the result
* @param pageUtil the page util
*/
PageWrapper(int code, String message, T result, PageUtil pageUtil) {
super(code, message, result);
this.pageUtil = pageUtil;
}
/**
* Sets the 分页数据 , 返回自身的引用.
*
* @param pageUtil the page util
*
* @return the page wrapper
*/
public PageWrapper<T> pageUtil(PageUtil pageUtil) {
this.setPageUtil(pageUtil);
return this;
}
/**
* Sets the 结果数据 , 返回自身的引用.
*
* @param result the result
*
* @return the page wrapper
*/
@Override
public PageWrapper<T> data(T result) {
super.setData(result);
return this;
}
}
package cn.wise.sc.consume.business.wrapper;
import org.apache.commons.lang3.StringUtils;
/**
* The class Wrap mapper.
*/
public class WrapMapper {
/**
* Instantiates a new wrap mapper.
*/
private WrapMapper() {
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
* @param message the message
* @param o the o
*
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code, String message, E o) {
return new Wrapper<>(code, message, o);
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
* @param message the message
*
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code, String message) {
return wrap(code, message, null);
}
/**
* Wrap.
*
* @param <E> the element type
* @param code the code
*
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(int code) {
return wrap(code, null);
}
/**
* Wrap.
*
* @param <E> the element type
* @param e the e
*
* @return the wrapper
*/
public static <E> Wrapper<E> wrap(Exception e) {
return new Wrapper<>(Wrapper.ERROR_CODE, e.getMessage());
}
/**
* Un wrapper.
*
* @param <E> the element type
* @param wrapper the wrapper
*
* @return the e
*/
public static <E> E unWrap(Wrapper<E> wrapper) {
return wrapper.getData();
}
/**
* Wrap ERROR. code=100
*
* @param <E> the element type
*
* @return the wrapper
*/
public static <E> Wrapper<E> illegalArgument() {
return wrap(Wrapper.ILLEGAL_ARGUMENT_CODE_, Wrapper.ILLEGAL_ARGUMENT_MESSAGE);
}
/**
* Wrap ERROR. code=500
*
* @param <E> the element type
*
* @return the wrapper
*/
public static <E> Wrapper<E> error() {
return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE);
}
/**
* Error wrapper.
*
* @param <E> the type parameter
* @param message the message
*
* @return the wrapper
*/
public static <E> Wrapper<E> error(String message) {
return wrap(Wrapper.ERROR_CODE, StringUtils.isBlank(message) ? Wrapper.ERROR_MESSAGE : message);
}
/**
* Wrap SUCCESS. code=200
*
* @param <E> the element type
*
* @return the wrapper
*/
public static <E> Wrapper<E> ok() {
return new Wrapper<>();
}
/**
* Ok wrapper.
*
* @param <E> the type parameter
* @param o the o
*
* @return the wrapper
*/
public static <E> Wrapper<E> ok(E o) {
return new Wrapper<>(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o);
}
}
package cn.wise.sc.consume.business.wrapper;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.Data;
import java.io.Serializable;
/**
* The class Wrapper.
*/
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Wrapper<T> implements Serializable {
/**
* 序列化标识
*/
/**
* 成功码.
*/
public static final int SUCCESS_CODE = 200;
/**
* 成功信息.
*/
public static final String SUCCESS_MESSAGE = "操作成功";
/**
* 错误码.
*/
public static final int ERROR_CODE = 500;
/**
* 错误信息.
*/
public static final String ERROR_MESSAGE = "内部异常";
/**
* 错误码:参数非法
*/
public static final int ILLEGAL_ARGUMENT_CODE_ = 100;
/**
* 错误信息:参数非法
*/
public static final String ILLEGAL_ARGUMENT_MESSAGE = "参数非法";
private static final long serialVersionUID = 3271183695751869867L;
/**
* 编号.
*/
private int code;
/**
* 信息.
*/
private String message;
/**
* 结果数据
*/
private T data;
/**
* Instantiates a new wrapper. default code=200
*/
Wrapper() {
this(SUCCESS_CODE, SUCCESS_MESSAGE);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
*/
Wrapper(int code, String message) {
this(code, message, null);
}
/**
* Instantiates a new wrapper.
*
* @param code the code
* @param message the message
* @param result the result
*/
Wrapper(int code, String message, T result) {
super();
this.code(code).message(message).data(result);
}
/**
* Sets the 编号 , 返回自身的引用.
*
* @param code the new 编号
*
* @return the wrapper
*/
private Wrapper<T> code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 , 返回自身的引用.
*
* @param message the new 信息
*
* @return the wrapper
*/
private Wrapper<T> message(String message) {
this.setMessage(message);
return this;
}
/**
* Sets the 结果数据 , 返回自身的引用.
*
* @param data the new 结果数据
*
* @return the wrapper
*/
public Wrapper<T> data(T data) {
this.setData(data);
return this;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE == this.code
*
* @return code =200,true;否则 false.
*/
@JsonIgnore
public boolean success() {
return Wrapper.SUCCESS_CODE == this.code;
}
/**
* 判断是否成功: 依据 Wrapper.SUCCESS_CODE != this.code
*
* @return code !=200,true;否则 false.
*/
@JsonIgnore
public boolean error() {
return !success();
}
}
package cn.wise.sc.consume.business.wrapper.page;
import lombok.Data;
/**
* 分页请求包装类
*/
@Data
public class PageUtil {
/**
* The cur page.当前页
*/
private int currentPage = 1;
/**
* The next page.下一页
*/
private int nextPage;
/**
* The pre page. 上一页
*/
private int prePage;
/**
* The total row. 总条数
*/
private int totalRow;
/**
* The page size.每页条数
*/
private int pageSize = 10;
/**
* The total page.总页数
*/
private int totalPage;
/**
* The start. 开始条数
*/
private int start;
/**
* The buttons.
*/
private int[] buttons;
/**
* 当前页条数
*/
private int curPageSize;
/**
* Instantiates a new page util.
*/
public PageUtil() {
}
/**
* Instantiates a new page util.
*
* @param currentPage the current page
*/
public PageUtil(int currentPage) {
this.currentPage = currentPage;
}
/**
* Instantiates a new page util.
*
* @param currentPage the current page
* @param pageSize the page size
*/
public PageUtil(int currentPage, int pageSize) {
this.currentPage = currentPage;
this.pageSize = pageSize;
}
}
package cn.wise.sc.consume.business.wrapper.page;
import lombok.Data;
import java.io.Serializable;
/**
*/
@Data
public class Query implements Serializable {
private static final long serialVersionUID = 8933019121780323520L;
/**
* 当前页
*/
private int pageNum = 1;
/**
* 每页的数量
*/
private int pageSize = 20;
}
server:
port: 7006
spring:
application: card-consume
profiles:
active: dev
datasource:
# 192.168.110.84 admin!@#123
url: jdbc:mysql://localhost:3306/cmb_consumption?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: admin!@#123
driverClassName: com.mysql.jdbc.Driver
hikari:
minimum-idle: 3
maximum-pool-size: 10
max-lifetime: 30000 #不能小于30秒,否则默认回到1800秒
connection-test-query: SELECT 1
redis:
port: 6379
host: localhost
# password: Wise_@123456
# 设置swagger用户名密码
swagger:
basic:
enable: false
username: admin
password: admin
mybatis-plus:
# 启动时是否检查MyBatis XML文件是否存在
check-config-location: true
type-aliases-package: cn.wise.sc.consume.business.entity.**
mapper-locations: classpath:/cn/wise/sc/consume/business/mapper/xml/*Mapper.xml
wechat:
oneNet:
merId: 308999179220002 #微信支付用的商户号id
tppidc: B000000168 #分行小程序id
token:
expire:
seconds: 7200
jwtSecret: (XIAO:)_$^11244^%$_(WEI:)_@@++--(LAO:)_++++_.sds_(SHI:)
\ No newline at end of file
fastdfs.connect_timeout=2000
fastdfs.network_timeout=1501
fastdfs.charset=UTF-8
fastdfs.http.tracker_http_port=8888
fastdfs.http.anti_steal_token=no
fastdfs.http.secret_key=FastDFS1234567890
fastdfs.tracker_servers=localhost:22122
#fastdfs.tracker_servers=localhost:22122
<?xml version="1.0" encoding="UTF-8"?>
<!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 -->
<!-- scan:当此属性设置为true时,配置文档如果发生改变,将会被重新加载,默认值为true -->
<!-- scanPeriod:设置监测配置文档是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。
当scan为true时,此属性生效。默认的时间间隔为1分钟。 -->
<!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 -->
<configuration scan="true" scanPeriod="10 seconds">
<contextName>logback-spring</contextName>
<!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义后,可以使“${}”来使用变量。 -->
<property name="logging.path" value="./../wise-came/logs" />
<!--0. 日志格式和颜色渲染 -->
<!-- 彩色日志依赖的渲染类 -->
<conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
<conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
<conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />
<!-- 彩色日志格式 -->
<property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/>
<!--1. 输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>debug</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--2. 输出到文档-->
<!-- 2.1 level为 DEBUG 日志,时间滚动输出 -->
<appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/debug.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志归档 -->
<fileNamePattern>${logging.path}/debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录debug级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>debug</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.2 level为 INFO 日志,时间滚动输出 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/info.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset>
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 每天日志归档路径以及格式 -->
<fileNamePattern>${logging.path}/info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>info</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.3 level为 WARN 日志,时间滚动输出 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/warn.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 2.4 level为 ERROR 日志,时间滚动输出 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文档的路径及文档名 -->
<file>${logging.path}/error.log</file>
<!--日志文档输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
<!-- 日志记录器的滚动策略,按日期,按大小记录 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${logging.path}/error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文档保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文档只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、
以及指定<appender>。<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
还有一个特俗值INHERITED或者同义词NULL,代表强制执行上级的级别。
如果未设置此属性,那么当前logger将会继承上级的级别。
addtivity:是否向上级logger传递打印信息。默认是true。
<logger name="org.springframework.web" level="info"/>
<logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/>
-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="info">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给dao下目录配置debug模式,代码如下,这样配置sql语句会打印,其他还是正常info级别:
【logging.level.org.mybatis=debug logging.level.dao=debug】
-->
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
不能设置为INHERITED或者同义词NULL。默认是DEBUG
可以包含零个或多个元素,标识这个appender将会添加到这个logger。
-->
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.springframework" level="WARN"></logger>
<logger name="org.springframework.web.servlet.mvc.method.annotation" level="WARN"></logger>
<logger name="org.mybatis" level="WARN"></logger>
<logger name="com.zaxxer.hikari" level="ERROR"></logger>
<logger name="com.baomidou" level="WARN"></logger>
<logger name="io.netty" level="WARN"></logger>
<!--<logger name="org.apache.zookeeper" level="INFO"></logger>-->
<!-- 4. 最终的策略 -->
<!-- 4.1 开发环境:打印控制台-->
<springProfile name="dev">
<logger name="cn.wise.sc.consume.business.controller" level="debug"/><!-- 修改此处扫描包名 -->
</springProfile>
<root level="debug">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="WARN_FILE" />
<appender-ref ref="ERROR_FILE" />
</root>
<!--4.2 生产环境:输出到文档-->
<springProfile name="pro">
<root level="info">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
</configuration>
\ No newline at end of file
##############################
# \u516c\u4f17\u53f7\u53c2\u6570\u914d\u7f6e #
##############################
wechat.mp.appId=wx3a6168d5668b917e
wechat.mp.secret=e0f585488a8ed2dd1b7547272645e247
wechat.mp.token=BJMS
wechat.mp.aesKey=ylAPggKwE2y2A7RFd8TKOoZnahuICCoMsPXkpnLJedD
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>consume-common</artifactId>
<groupId>cn.wise.sc.cmbapp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>common-swagger</artifactId>
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.4.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.1</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.wise.sc.consume.common.swagger;
/**
* @Auther: yangjing
* @Date: 2020/3/29 12:17
* @ClassName: PACKAGE_NAME
* @Description: TODO
*/
public class PackageInfo {
}
package cn.wise.sc.consume.common.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Auther: yangjing
* @Date: 2020/3/29 12:17
* @ClassName: PACKAGE_NAME
* @Description: TODO
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
@Bean
public Docket createRestApi() {// 创建API基本信息
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.wise.sc.consume"))// 扫描该包下的所有需要在Swagger中展示的API,@ApiIgnore注解标注的除外
.paths(PathSelectors.any())//egex("/api/.*") 拦截的接口路径
.build();
}
private ApiInfo apiInfo() {// 创建API的基本信息,这些信息会在Swagger UI中进行显示
return new ApiInfoBuilder()
.title("swagger-api")// API 标题
.description("系统接口测试对接api")// API描述
.contact("杨**")// 联系人
// .license("Apache License Version 2.0")// 开源协议
.version("1.0")// 版本号
.build();
}
/**
* 重定向静态资源的路径,千万不要注释 不然 你们在访问api的时候会404的
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/");
// //下面是图片的虚拟路径配置
// registry.addResourceHandler(fileVirtualPath+"**").
// addResourceLocations("file:"+fileRealPath);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>card-consume</artifactId>
<groupId>cn.wise.sc.cmbapp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>consume-common</artifactId>
<packaging>pom</packaging>
<modules>
<module>common-swagger</module>
</modules>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>card-consume</artifactId>
<groupId>cn.wise.sc.cmbapp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatis-generator</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 模板引擎 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package cn.wise.sc.consume.mg;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.Scanner;
/**
* @author neo.shu
* @since 2020/3/28 15:31
* 使用方式:
* 1.配置数据源 line50-54
* 2.配置文件路径 line60
* 3.运行main方法
* 4.根据控制台打印的填写模块名和要生成的table名
*/
public class GeneratorApplication {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://192.168.110.84:3306/cmb_consumption?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("admin!@#123");
mpg.setDataSource(dsc);
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/consume-business/src/main/java");
gc.setAuthor("ztw");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("cn.wise.sc.consume");
mpg.setPackageInfo(pc);
// 自定义配置
//InjectionConfig cfg = new InjectionConfig() {
// @Override
// public void initMap() {
// to do nothing
// }
// };
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
//List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
//focList.add(new FileOutConfig(templatePath) {
// @Override
// public String outputFile(TableInfo tableInfo) {
// // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
// return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
// + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
// }
//});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录");
return false;
}
});
*/
//cfg.setFileOutConfigList(focList);
//mpg.setCfg(cfg);
// 配置模板
//TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
//templateConfig.setXml(null);
//mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
//mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.wise.sc.cmbapp</groupId>
<artifactId>card-consume</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>consume-common</module>
<module>consume-business</module>
<module>mybatis-generator</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.5</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
<!--日志-->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.10.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.5.22</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.5.22</version>
</dependency>
<!--**************************************-->
</dependencies>
</dependencyManagement>
</project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment