diff --git a/.gitignore b/.gitignore index 1a0d65b..452d367 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,25 @@ -# Created by .ignore support plugin (hsz.mobi) -### 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* +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ +logs/** +*/logs/** -### Example user template template -### Example user template +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache -# IntelliJ project files +### IntelliJ IDEA ### .idea +*.iws *.iml + out gen @@ -45,3 +35,16 @@ uploads/** .project .settings +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### diff --git a/open-api/pom.xml b/open-api/pom.xml new file mode 100644 index 0000000..902a766 --- /dev/null +++ b/open-api/pom.xml @@ -0,0 +1,31 @@ + + + + suimang + com.iformall + 1.0 + + 4.0.0 + + open-api + + + + + com.iformall + suimangService + 1.0 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/open-api/src/main/java/com/iformall/OpenApiApplication.java b/open-api/src/main/java/com/iformall/OpenApiApplication.java new file mode 100644 index 0000000..0cae084 --- /dev/null +++ b/open-api/src/main/java/com/iformall/OpenApiApplication.java @@ -0,0 +1,63 @@ +package com.iformall; + +import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; +import org.mybatis.spring.annotation.MapperScan; +import org.rocketmq.starter.annotation.EnableRocketMQ; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.EnableAspectJAutoProxy; + +@SpringBootApplication +@MapperScan(basePackages = {"com.iformall.mapper"}) +@EnableEncryptableProperties +@EnableRocketMQ +@EnableAspectJAutoProxy(exposeProxy = true) +public class OpenApiApplication { + + @Value("${fm.exception}") + private boolean fmException; + + @Value("${fm.exception_emails}") + private String fmExceptionEmails; + + @Value("${fm.open}") + private boolean fmOpen; + + @Value("${fm.upload_dir}") + private String uploadDir; + + @Value("${fm.videoType}") + private String videoType; + + @Bean + public boolean isFmException() { + return fmException; + } + + @Bean + public String fmExceptionEmails() { + return fmExceptionEmails; + } + + @Bean + public boolean isFmOpen() { + return fmOpen; + } + + @Bean + public String fmUploadDir() { + return uploadDir; + } + + @Bean + public String videoType() { + return videoType; + } + + + public static void main(String[] args) { + SpringApplication.run(OpenApiApplication.class, args); + } +} diff --git a/open-api/src/main/java/com/iformall/annotation/RedisCache.java b/open-api/src/main/java/com/iformall/annotation/RedisCache.java new file mode 100644 index 0000000..1857366 --- /dev/null +++ b/open-api/src/main/java/com/iformall/annotation/RedisCache.java @@ -0,0 +1,53 @@ +package com.iformall.annotation; + + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.util.concurrent.TimeUnit; + + +/** + * - /api/wxCouponChannel/change + * - /api/user/userinfo + * - /api/wxBusiness/listAll + * - /api/wxCampaign/list + * - /api/mall/mallInfo + * - /api/mall/getAppIcon + * - /api/mall/getWeapNote + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface RedisCache { + + /** + * 缓存key的名称 + * @return + */ + String key() default ""; + + /** + * 自动生成key + * @return + */ + boolean autoKey() default true; + + /** + * 参数md5,解决key过长问题 + * @return + */ + boolean md5() default true ; + + /** + * key 过期日期默认60秒 + * @return + */ + int expireTime() default 60; + + /** + * 时间单位默认为秒 + * @return + */ + TimeUnit dateUnit() default TimeUnit.SECONDS; +} diff --git a/open-api/src/main/java/com/iformall/aop/RedisCacheAspect.java b/open-api/src/main/java/com/iformall/aop/RedisCacheAspect.java new file mode 100644 index 0000000..c5bd5b2 --- /dev/null +++ b/open-api/src/main/java/com/iformall/aop/RedisCacheAspect.java @@ -0,0 +1,158 @@ +package com.iformall.aop; + + +import com.alibaba.fastjson.JSONObject; +import com.iformall.annotation.RedisCache; +import com.iformall.domain.po.base.BaseCUserEntity; +import com.iformall.service.CUserTokenService; +import com.iformall.utils.HashUtil; +import com.iformall.utils.RedisLock; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Objects; + +@Slf4j +@Aspect +@Component +public class RedisCacheAspect { + + /** + * 参数分隔符 param1|param2|param3 + **/ + private static final String DELIMITER_PARAMS = "|"; + + /** + * key 分隔符 + */ + private static final String DELIMITER_KEY = ":"; + + @Autowired + private StringRedisTemplate stringRedisTemplate; + + @Autowired + RedisLock redisLock; + + @Autowired + private CUserTokenService cUserTokenService; + + @Pointcut("@annotation(com.iformall.annotation.RedisCache)") + public void cacheAspect() { + } + + @Around("cacheAspect()") + public Object round(ProceedingJoinPoint jp) throws Throwable { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + // 查询token信息 + //从header中获取token + String token = request.getHeader("token"); + //如果header中不存在token,则从参数中获取token + if (StringUtils.isBlank(token)) { + token = request.getParameter("token"); + } + if(StringUtils.isBlank(token) || "null".equals(token) || "undefined".equals(token)){ + token=""; + //throw new MallinkException(ErrorCode.NET_TOKEN_EMPTY.getCode(),"token为空["+token+"]"); + } + log.info("token>>>>>>>>>>>>>>>"+token); + String tenantId; + BaseCUserEntity cUser = null ; + if(StringUtils.isNotBlank(token)) { + cUser = cUserTokenService.getByToken(token); + } + if (Objects.isNull(cUser) || cUser.getExpireTime().getTime() < System.currentTimeMillis()) { + tenantId = "0"; + } else { + tenantId = cUser.getTenantId(); + } + + // 请求参数 + Object[] args = jp.getArgs(); + // 接口 返回结果 + Object result; + String redisKey; + + //得到注释的名称 + MethodSignature signature = (MethodSignature) jp.getSignature(); + //判断tag是否在用户权限中 如果存在加入参数查询 + Method method = signature.getMethod(); + RedisCache cache = method.getAnnotation(RedisCache.class) ; + if (cache.autoKey()) { + // 构建 redisKey => reqPath:tenantId:md5(param1_param2_param3) + String requestUrl = request.getRequestURI(); + // 接口路径 reqPath => /api/xxx + String reqPath = requestUrl.substring(requestUrl.indexOf("/api/")); + if (cache.md5()) { + String md5Before = StringUtils.join(args, DELIMITER_PARAMS); + redisKey = StringUtils.join(reqPath, DELIMITER_KEY, tenantId, DELIMITER_KEY, HashUtil.md5(StringUtils.join(token, md5Before, DELIMITER_PARAMS))); + } else { + redisKey = StringUtils.join(reqPath, DELIMITER_KEY, tenantId, DELIMITER_KEY, StringUtils.join(token,args, DELIMITER_PARAMS)); + } + } else { + redisKey = cache.key(); + } + + // redisKey 不存在,获取接口数据并返回 + if (StringUtils.isBlank(redisKey)) { + result = jp.proceed(args); + } else { + ValueOperations valueOperations = stringRedisTemplate.opsForValue(); + String value = valueOperations.get(redisKey); + if (value == null) { + String lockKey = StringUtils.join(redisKey, ":", "lock"); + long time = System.currentTimeMillis() + 2000; + String timeStr = String.valueOf(time); + try { + //分布式锁,保证一个线程读DB,其它线程排队 + if (redisLock.lock2(lockKey, timeStr)) { + log.debug("CacheAspect 读库中, key:{}: " + lockKey); + result = jp.proceed(args); + String json_data = JSONObject.toJSONString(result); + valueOperations.set(redisKey, json_data, cache.expireTime(), cache.dateUnit()); + log.debug("CacheAspect 缓存不存在,获取接口数据并放入缓存,key:{}, expire:{}", redisKey, cache.expireTime()); + } else { + log.debug("CacheAspect 读库等待中, key:{}: " + lockKey); + Thread.sleep(2000); + value = valueOperations.get(redisKey); + result = parseCache(jp, redisKey, value); + } + } catch (Throwable throwable) { + log.error("CacheAspect proceed error , Illegal argument: {} in {}.{}()", Arrays.toString(jp.getArgs()), + jp.getSignature().getDeclaringTypeName(), jp.getSignature().getName(), throwable); + throw throwable; + } finally { + redisLock.unlock(lockKey, timeStr); + } + } else { + result = parseCache(jp, redisKey, value); + } + // 计数器 + stringRedisTemplate.opsForHash().increment("hotapi", redisKey, 1); + } + return result; + } + + private Object parseCache(ProceedingJoinPoint jp, String redisKey, String value) { + if (StringUtils.isBlank(value)) { + log.debug("CacheAspect 缓存不存在,解析缓存数据为空:{},key:{}", value, redisKey); + return null; + } + Class returnType = ((MethodSignature) jp.getSignature()).getReturnType(); + log.debug("CacheAspect 缓存存在,解析缓存并返回,key:{}", redisKey); + return JSONObject.parseObject(value, returnType); + } +} diff --git a/open-api/src/main/java/com/iformall/config/MyBatisConfiguration.java b/open-api/src/main/java/com/iformall/config/MyBatisConfiguration.java new file mode 100644 index 0000000..7b21584 --- /dev/null +++ b/open-api/src/main/java/com/iformall/config/MyBatisConfiguration.java @@ -0,0 +1,23 @@ +package com.iformall.config; + +import com.iformall.plugin.MyBatisItercepters; +import com.iformall.plugin.MyBatisPlus; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +@Configuration +public class MyBatisConfiguration extends BaseMyBatisConfiguration { + + @Bean + public MyBatisItercepters intercepters() { + MyBatisItercepters intercepters = new MyBatisItercepters(); + List plugins = new ArrayList(); + plugins.add(baseShardingSpherePlugin()); + + intercepters.setPlugins(plugins); + return intercepters; + } +} diff --git a/open-api/src/main/java/com/iformall/config/RedisConfig.java b/open-api/src/main/java/com/iformall/config/RedisConfig.java new file mode 100644 index 0000000..3266ae2 --- /dev/null +++ b/open-api/src/main/java/com/iformall/config/RedisConfig.java @@ -0,0 +1,334 @@ +package com.iformall.config; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.*; +import com.iformall.domain.po.base.BaseCUserEntity; +import com.iformall.domain.vo.WxCouponCVo; +import com.iformall.domain.vo.WxCouponChannelVo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.CacheManager; +import org.springframework.cache.annotation.CachingConfigurerSupport; +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.cache.RedisCacheWriter; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by Stormeye on 2018/10/1. + */ +@Configuration +@EnableCaching +public class RedisConfig extends CachingConfigurerSupport { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + //缓存管理器 + @Bean + public CacheManager cacheManager(RedisConnectionFactory connectionFactory) { + //user信息缓存配置 + RedisCacheConfiguration userCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(10)).disableCachingNullValues().prefixKeysWith("user"); + Map redisCacheConfigurationMap = new HashMap<>(); + redisCacheConfigurationMap.put("user", userCacheConfiguration); + //初始化一个RedisCacheWriter + RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory); + // 设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现 + // ClassLoader loader = this.getClass().getClassLoader(); + // JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader); + // RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair.fromSerializer(jdkSerializer); + // RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); + RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig(); + //设置默认超过期时间是30秒 + defaultCacheConfig.entryTtl(Duration.ofSeconds(30)); + //初始化RedisCacheManager + RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig, redisCacheConfigurationMap); + return cacheManager; + } + + @Bean("pushLimitRedisTemplate") + public RedisTemplate getPushLimitRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(PushLimit.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("scoreRuleRedisTemplate") + public RedisTemplate getScoreRuleRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxScoreRules.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("cuserTokenRedisTemplate") + public RedisTemplate getCUserTokenRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxCUser.class); + + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("baseCUserTokenRedisTemplate") + public RedisTemplate getBaseCUserTokenRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(BaseCUserEntity.class); + + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("cUserBasicInfoRedisTemplate") + public RedisTemplate getCUserBasicInfoRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxCUserBasicInfo.class); + + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("mallRedisTemplate") + public RedisTemplate getMallRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxMall.class); + + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("subMallListRedisTemplate") + public RedisTemplate> getSubMallListRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate> template = new RedisTemplate>(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(List.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("couponDetailRedisTemplate") + public RedisTemplate getCouponDetailRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxCouponCVo.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("couponChannelRedisTemplate") + public RedisTemplate> getCouponChannelRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate> template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(PageInfo.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("buserTokenRedisTemplate") + public RedisTemplate getBuserTokenRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxBuser.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("pressOrderRedisTemplate") + public RedisTemplate getPressOrderRedisTemplate(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(WxOrder.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + + return template; + } + + @Bean("stringValueOperations") + public ValueOperations getStringValueOperations(RedisConnectionFactory connectionFactory) { + StringRedisTemplate template = new StringRedisTemplate(); + template.setConnectionFactory(connectionFactory); + template.afterPropertiesSet(); + return template.opsForValue(); + } + + @Bean("objectCommonRedisTemplate") + public RedisTemplate getObjectValueOperations(RedisConnectionFactory connectionFactory) { + RedisTemplate template = new RedisTemplate<>(); + template.setConnectionFactory(connectionFactory); + Jackson2JsonRedisSerializer j = new Jackson2JsonRedisSerializer(Object.class); + ObjectMapper om = new ObjectMapper(); + om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); + om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + j.setObjectMapper(om); + + // value值的序列化 + template.setValueSerializer(j); + template.setHashValueSerializer(j); + + // key的序列化 + template.setKeySerializer(new StringRedisSerializer()); + template.setHashKeySerializer(new StringRedisSerializer()); + template.afterPropertiesSet(); + return template; + } +} diff --git a/open-api/src/main/java/com/iformall/config/Swagger2Config.java b/open-api/src/main/java/com/iformall/config/Swagger2Config.java new file mode 100644 index 0000000..6d22331 --- /dev/null +++ b/open-api/src/main/java/com/iformall/config/Swagger2Config.java @@ -0,0 +1,61 @@ +//package com.iformall.config; +// +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import springfox.documentation.builders.ApiInfoBuilder; +//import springfox.documentation.builders.ParameterBuilder; +//import springfox.documentation.builders.PathSelectors; +//import springfox.documentation.builders.RequestHandlerSelectors; +//import springfox.documentation.schema.ModelRef; +//import springfox.documentation.service.ApiInfo; +//import springfox.documentation.service.Parameter; +//import springfox.documentation.spi.DocumentationType; +//import springfox.documentation.spring.web.paths.RelativePathProvider; +//import springfox.documentation.spring.web.plugins.Docket; +//import springfox.documentation.swagger2.annotations.EnableSwagger2; +// +//import javax.servlet.ServletContext; +//import java.util.ArrayList; +//import java.util.List; +// +////参考:http://blog.csdn.net/catoop/article/details/50668896 +//@Configuration +//@EnableSwagger2 +//public class Swagger2Config { +// +// @Autowired +// private ServletContext servletContext; +// +// @Bean +// public Docket createRestApi() { +// ParameterBuilder tokenPar = new ParameterBuilder(); +// List pars = new ArrayList(); +// //增加一个request的header参数 +// tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); +// pars.add(tokenPar.build()); +// return new Docket(DocumentationType.SWAGGER_2) +// .apiInfo(apiInfo()) +// .select() +// .apis(RequestHandlerSelectors.basePackage("com.iformall.controller")) +// .paths(PathSelectors.any()) +// .build() +// .globalOperationParameters(pars) +// .pathProvider(new RelativePathProvider(servletContext) { +// @Override +// public String getApplicationBasePath() { +// return "/api"; +// } +// }); +// } +// +// private ApiInfo apiInfo() { +// return new ApiInfoBuilder() +// .title("c端 api") +// .description("c api") +// .termsOfServiceUrl("http://localhost:7000") +// .version("2.0") +// .build(); +// } +// +//} \ No newline at end of file diff --git a/open-api/src/main/java/com/iformall/config/WebMvcConfig.java b/open-api/src/main/java/com/iformall/config/WebMvcConfig.java new file mode 100644 index 0000000..13dc758 --- /dev/null +++ b/open-api/src/main/java/com/iformall/config/WebMvcConfig.java @@ -0,0 +1,105 @@ +package com.iformall.config; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.databind.DeserializationConfig; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import com.iformall.interceptor.AuthorizationInterceptor; +import com.iformall.interceptor.HttpServletRequestWrapperFilter; +import com.iformall.interceptor.RequestInterceptor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.*; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.text.SimpleDateFormat; +import java.util.List; + +/** + * MVC配置 + * + * @author stormeye.wu + * @email wugq@mippoint.com + * @date 2017-04-20 22:30 + */ +@Configuration +@EnableWebMvc +public class WebMvcConfig implements WebMvcConfigurer { + @Autowired + private AuthorizationInterceptor authorizationInterceptor; + @Autowired + private RequestInterceptor requestInterceptor; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(authorizationInterceptor).addPathPatterns("/api/**"); + registry.addInterceptor(requestInterceptor).addPathPatterns("/api/**"); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { +// registry.addResourceHandler("swagger-ui.html") +// .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("doc.html") + .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**") + .addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/api/**") + .allowedOrigins("*") + .allowCredentials(true) + .allowedMethods("GET", "POST", "DELETE", "PUT") + .maxAge(3600); + } + + @Override + public void configureMessageConverters(List> converters) { + MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter(); + //ObjectMapper 是Jackson库的主要类。它提供一些功能将转换成Java对象匹配JSON结构,反之亦然 + ObjectMapper objectMapper = new ObjectMapper(); + SimpleModule simpleModule = new SimpleModule(); + + //不显示为null的字段 + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + DeserializationConfig dc = objectMapper.getDeserializationConfig(); + // 设置反序列化日期格式、忽略不存在get、set的属性 + objectMapper.setConfig( + dc.with(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) + .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + ); + //序列化将Long转String类型 + simpleModule.addSerializer(Long.class, ToStringSerializer.instance); + simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); + SimpleModule bigIntegerModule = new SimpleModule(); + //序列化将BigInteger转String类型 + bigIntegerModule.addSerializer(BigInteger.class, ToStringSerializer.instance); + SimpleModule bigDecimalModule = new SimpleModule(); + //序列化将BigDecimal转String类型 + bigDecimalModule.addSerializer(BigDecimal.class, ToStringSerializer.instance); + objectMapper.registerModule(simpleModule); + objectMapper.registerModule(bigDecimalModule); + objectMapper.registerModule(bigIntegerModule); + jackson2HttpMessageConverter.setObjectMapper(objectMapper); + converters.add(jackson2HttpMessageConverter); + } + + @Bean + public FilterRegistrationBean Filters() { + FilterRegistrationBean registrationBean = new FilterRegistrationBean(); + registrationBean.setFilter(new HttpServletRequestWrapperFilter()); + registrationBean.addUrlPatterns("/*"); + registrationBean.setName("koalaSignFilter"); + return registrationBean; + } +} \ No newline at end of file diff --git a/open-api/src/main/java/com/iformall/controller/ApiMaterialMouldController.java b/open-api/src/main/java/com/iformall/controller/ApiMaterialMouldController.java new file mode 100644 index 0000000..ba66267 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ApiMaterialMouldController.java @@ -0,0 +1,32 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.dto.PageMaterialMouldDTO; +import com.iformall.service.ApiMaterialMouldService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 背景,素材模板api + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Api(tags = "物料模板api") +@RestController +@RequestMapping("/api/materialMould") +public class ApiMaterialMouldController extends BaseController { + + @Autowired + private ApiMaterialMouldService apiMaterialMouldService; + + @ApiOperation("分页查询物料模板") + @GetMapping("page") + public ResultData pageMaterialMould(PageMaterialMouldDTO dto) { + return new ResultData(apiMaterialMouldService.pageMaterialMould(dto)); + } +} diff --git a/open-api/src/main/java/com/iformall/controller/ApiPersonMouldController.java b/open-api/src/main/java/com/iformall/controller/ApiPersonMouldController.java new file mode 100644 index 0000000..4e35d0f --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ApiPersonMouldController.java @@ -0,0 +1,39 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.dto.PagePersonMouldDTO; +import com.iformall.service.ApiPersonMouldService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 数字人模板api + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Api(tags = "数字人模板api") +@RestController +@RequestMapping("/api/personPatch") +public class ApiPersonMouldController extends BaseController { + + @Autowired + private ApiPersonMouldService apiPersonMouldService; + + @ApiOperation("分页查询数字人模板") + @GetMapping("page") + public ResultData pagePersonMould(PagePersonMouldDTO dto) { + dto.setServiceId(this.getServiceId()); + return new ResultData(apiPersonMouldService.pagePersonMould(dto)); + } + + @ApiOperation("单个查询") + @GetMapping("get") + public ResultData getPersonMould(Long id) { + return new ResultData(apiPersonMouldService.getPersonMould(id)); + } +} diff --git a/open-api/src/main/java/com/iformall/controller/ApiServiceInfoController.java b/open-api/src/main/java/com/iformall/controller/ApiServiceInfoController.java new file mode 100644 index 0000000..25a8f72 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ApiServiceInfoController.java @@ -0,0 +1,55 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import com.iformall.dto.PageServiceVideoRecordDTO; +import com.iformall.service.sm.ServiceInfoService; +import com.iformall.service.sm.ServiceVideoRecordService; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 数字人模板api + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Api(tags = "接入方api") +@RestController +@RequestMapping("/api/serviceInfo") +public class ApiServiceInfoController extends BaseController { + + @Autowired + private ServiceInfoService serviceInfoService; + + @Autowired + private ServiceVideoRecordService serviceVideoRecordService; + + @ApiOperation("当前接入方信息") + @GetMapping("current") + public ResultData pagePersonMould() { + return new ResultData(serviceInfoService.getServiceInfo(getServiceId())); + } + + @ApiOperation("当前接入方生成视频记录") + @GetMapping("currentVideoRecords") + public ResultData currentVideoRecords(PageServiceVideoRecordDTO dto) { + ServiceVideoRecord svr = new ServiceVideoRecord(); + svr.setServiceId(getServiceId()); + return new ResultData(serviceVideoRecordService.listAsPage(svr, dto.getPageNum(), dto.getPageSize())); + } + + @ApiOperation("当前接入方生成视频记录") + @GetMapping("currentVideoTotals") + public ResultData currentVideoTotals(PageServiceVideoRecordDTO dto) { + ServiceVideoRecord svr = new ServiceVideoRecord(); + svr.setServiceId(getServiceId()); + return new ResultData(serviceVideoRecordService.totalTimes(svr)); + } + +} diff --git a/open-api/src/main/java/com/iformall/controller/ApiUserVideoController.java b/open-api/src/main/java/com/iformall/controller/ApiUserVideoController.java new file mode 100644 index 0000000..5a9f170 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ApiUserVideoController.java @@ -0,0 +1,46 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.dto.PageUserVideoDTO; +import com.iformall.service.ApiUserVideoService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 用户视频api + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Api(tags = "用户视频api") +@RestController +@RequestMapping("/api/userVideo") +public class ApiUserVideoController extends BaseController { + + @Autowired + private ApiUserVideoService apiUserVideoService; + + @ApiOperation("分页查询用户视频") + @GetMapping("page") + public ResultData pageUserVideo(PageUserVideoDTO dto) { + return new ResultData(apiUserVideoService.pageUserVideo(dto)); + } + + @ApiOperation("单个查询用户视频") + @GetMapping("get") + public ResultData getUserVideo(Long id) { + return new ResultData(apiUserVideoService.getUserVideo(id)); + } + + @ApiOperation("删除用户视频") + @PostMapping("delete") + public ResultData deleteUserVideo(Long id) { + apiUserVideoService.deleteUserVideo(id); + return new ResultData(); + } +} diff --git a/open-api/src/main/java/com/iformall/controller/ApiVoiceMouldController.java b/open-api/src/main/java/com/iformall/controller/ApiVoiceMouldController.java new file mode 100644 index 0000000..e74cb56 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ApiVoiceMouldController.java @@ -0,0 +1,38 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.dto.ListVoiceLanguageDTO; +import com.iformall.service.ApiVoiceMouldService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 声音模板api + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Api(tags = "声音模板api") +@RestController +@RequestMapping("/api/voiceMould") +public class ApiVoiceMouldController extends BaseController { + + @Autowired + private ApiVoiceMouldService apiVoiceMouldService; + + @ApiOperation("全查询语种") + @GetMapping("list") + public ResultData listVoiceLanguage(ListVoiceLanguageDTO dto) { + return new ResultData(apiVoiceMouldService.listVoiceLanguage(dto)); + } + + @ApiOperation("单个查询声音风格") + @GetMapping("get") + public ResultData getVoiceMould(Long id) { + return new ResultData(apiVoiceMouldService.getVoiceMould(id)); + } +} diff --git a/open-api/src/main/java/com/iformall/controller/BaseController.java b/open-api/src/main/java/com/iformall/controller/BaseController.java new file mode 100644 index 0000000..b4814f0 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/BaseController.java @@ -0,0 +1,72 @@ +package com.iformall.controller; + +import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.domain.po.base.TenantEntity; +import com.iformall.service.WxThirdPartyApiService; +import com.iformall.utils.Constant; +import com.iformall.utils.IPUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.beans.PropertyEditorSupport; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +@RestController +public class BaseController { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + WxThirdPartyApiService wxThirdPartyApiService; + + @InitBinder + public void InitBinder(WebDataBinder dataBinder) { + dataBinder.registerCustomEditor(Date.class, new PropertyEditorSupport() { + public void setAsText(String value) { + try { + setValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(value)); + } catch (ParseException e) { + try { + setValue(new SimpleDateFormat("yyyy-MM-dd ").parse(value)); + } catch (ParseException e1) { + setValue(null); + } + } + } + + public String getAsText() { + return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) getValue()); + } + }); + } + + public String getAppId() { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + return (String) request.getAttribute(Constant.APP_Id); + } + + public WxThirdPartyApi getAppConfig() { + return wxThirdPartyApiService.findByApp(this.getAppId(),null); + } + + public String getIpAddr() { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + return IPUtil.getIpAddr(request); + } + + public Long getServiceId() { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + return (Long) request.getAttribute(Constant.SERVICE_ID); + } +} diff --git a/open-api/src/main/java/com/iformall/controller/HomeController.java b/open-api/src/main/java/com/iformall/controller/HomeController.java new file mode 100644 index 0000000..61329bb --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/HomeController.java @@ -0,0 +1,29 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = "") +@RestController +@RequestMapping("/home") +public class HomeController extends BaseController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Value("${version}") + private String version; + + @ApiOperation("获取后端版本号") + @GetMapping("/version") + public ResultData version() { + logger.debug("[" + getIpAddr() + "] HomeController::version"); + return new ResultData(version); + } +} \ No newline at end of file diff --git a/open-api/src/main/java/com/iformall/controller/ai/AiVideoController.java b/open-api/src/main/java/com/iformall/controller/ai/AiVideoController.java new file mode 100644 index 0000000..8049208 --- /dev/null +++ b/open-api/src/main/java/com/iformall/controller/ai/AiVideoController.java @@ -0,0 +1,46 @@ +package com.iformall.controller.ai; + +import com.iformall.common.ResultData; +import com.iformall.controller.BaseController; +import com.iformall.dto.GenerateVideoDTO; +import com.iformall.dto.PagePersonMouldDTO; +import com.iformall.dto.PageServiceVideoRecordDTO; +import com.iformall.dto.PreviewVideoDTO; +import com.iformall.service.AiVideoService; +import com.iformall.sm.AiVideoParam; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@Api(tags = "视频相关api") +@RestController +@RequestMapping("/api/video") +public class AiVideoController extends BaseController { + + @Autowired + private AiVideoService aiVideoService; + + @ApiOperation("预览") + @PostMapping("/previewVideo") + public ResultData previewVideo(@RequestBody PreviewVideoDTO dto) { + return new ResultData(aiVideoService.previewVideo(PreviewVideoDTO.mappingParam(dto))); + } + + @ApiOperation("生成视频") + @PostMapping("generateVideo") + public ResultData generateVideo(@RequestBody AiVideoParam aiVideoParam) { + return new ResultData(aiVideoService.generateVideo(aiVideoParam, getServiceId())); + } + + @ApiOperation("分页查询生成记录列表") + @GetMapping("serviceVedioRecordPage") + public ResultData pagePersonMould(PageServiceVideoRecordDTO dto) { + dto.setServiceId(this.getServiceId()); + return new ResultData(aiVideoService.serviceVideoRecords(dto)); + } +} diff --git a/open-api/src/main/java/com/iformall/dto/GenerateVideoDTO.java b/open-api/src/main/java/com/iformall/dto/GenerateVideoDTO.java new file mode 100644 index 0000000..2e98534 --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/GenerateVideoDTO.java @@ -0,0 +1,56 @@ +package com.iformall.dto; + +import com.iformall.enums.sm.EnumThirdPartyType; +import com.iformall.sm.AiVideoParam; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * @author xmzhao71 + * @date 2023-10-27 + */ +@ApiModel(value = "生成视频请求参数") +@Data +public class GenerateVideoDTO { + /** + * 请求参数 + * { + * "gen_txt":"大家好,我是渣渣辉。是兄弟就来贪玩蓝月砍我一刀。望我,再望我,还望我,再望我就把你喝掉。", + * "video_template_id":"16938690720846922_vorSBabt", + * "voice_id":"zh-CN-XiaomengNeural", + * "voice_style":"chat", + * "video_files":{ + * "back_ground":{ + * "image":"", + * "type":"vertical" + * }, + * "digital_human":{ + * "coord":[ + * -202, + * 7 + * ], + * "level":1, + * "ratio":1.3 + * } + * }, + * "subtitle":{ + * "enabled":0 + * } + * } + */ +// @ApiModelProperty(value = "视频唯一标识") +// private Long id; + @ApiModelProperty(value = "接入方式") + private Integer type = EnumThirdPartyType.API_JOIN.getCode(); + @ApiModelProperty(value = "生成视频参数") + private AiVideoParam aiVideoParam; + + + public static GenerateVideoDTO build(AiVideoParam aiVideoParam, Integer type) { + GenerateVideoDTO dto = new GenerateVideoDTO(); + dto.setType(type); + dto.setAiVideoParam(aiVideoParam); + return dto; + } +} diff --git a/open-api/src/main/java/com/iformall/dto/ListVoiceLanguageDTO.java b/open-api/src/main/java/com/iformall/dto/ListVoiceLanguageDTO.java new file mode 100644 index 0000000..c1b4f84 --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/ListVoiceLanguageDTO.java @@ -0,0 +1,13 @@ +package com.iformall.dto; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "全查询语种请求参数") +@Data +public class ListVoiceLanguageDTO { + + @ApiModelProperty("语种名称") + private String chineseName; +} diff --git a/open-api/src/main/java/com/iformall/dto/PageDTO.java b/open-api/src/main/java/com/iformall/dto/PageDTO.java new file mode 100644 index 0000000..5744b6f --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PageDTO.java @@ -0,0 +1,9 @@ +package com.iformall.dto; + +import lombok.Data; + +@Data +public class PageDTO { + private Integer pageNum = 1; + private Integer pageSize = 20; +} diff --git a/open-api/src/main/java/com/iformall/dto/PageMaterialMouldDTO.java b/open-api/src/main/java/com/iformall/dto/PageMaterialMouldDTO.java new file mode 100644 index 0000000..77be6b5 --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PageMaterialMouldDTO.java @@ -0,0 +1,21 @@ +package com.iformall.dto; + +import com.iformall.domain.po.sm.MaterialMould; +import com.iformall.enums.EnumaMouldPatchStatus; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "分页查询物料模板请求参数") +@Data +public class PageMaterialMouldDTO extends PageDTO { + @ApiModelProperty("4:背景,5:素材") + private Integer type; + + public static MaterialMould mappingPO(PageMaterialMouldDTO dto) { + MaterialMould materialMould = new MaterialMould(); + materialMould.setType(dto.getType()); + materialMould.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + return materialMould; + } +} diff --git a/open-api/src/main/java/com/iformall/dto/PagePersonMouldDTO.java b/open-api/src/main/java/com/iformall/dto/PagePersonMouldDTO.java new file mode 100644 index 0000000..71e6a8b --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PagePersonMouldDTO.java @@ -0,0 +1,34 @@ +package com.iformall.dto; + +import java.util.List; + +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.enums.EnumaMouldPatchStatus; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "分页查询数字人模板请求参数") +@Data +public class PagePersonMouldDTO extends PageDTO { + + @ApiModelProperty("0:保密,1:男,2:女") + private Integer sex; + @ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + + private Long serviceId; + private Long id; + private List ids; + + public static PersonMould mappingPO(PagePersonMouldDTO dto) { + PersonMould personMould = new PersonMould(); + personMould.setSex(dto.getSex()); + personMould.setVideoType(dto.getVideoType()); + personMould.setId(dto.getId()); + personMould.setIds(dto.getIds()); + personMould.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + return personMould; + } +} diff --git a/open-api/src/main/java/com/iformall/dto/PageServiceVideoRecordDTO.java b/open-api/src/main/java/com/iformall/dto/PageServiceVideoRecordDTO.java new file mode 100644 index 0000000..7da64e5 --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PageServiceVideoRecordDTO.java @@ -0,0 +1,18 @@ +package com.iformall.dto; + +import com.iformall.domain.po.sm.ServiceVideoRecord; +import io.swagger.annotations.ApiModel; +import lombok.Data; + +@ApiModel(value = "分页查询数字人模板请求参数") +@Data +public class PageServiceVideoRecordDTO extends PageDTO { + + private Long serviceId; + + public static ServiceVideoRecord mappingPO(PageServiceVideoRecordDTO dto) { + ServiceVideoRecord svr = new ServiceVideoRecord(); + svr.setServiceId(dto.getServiceId()); + return svr; + } +} diff --git a/open-api/src/main/java/com/iformall/dto/PageUserVideoDTO.java b/open-api/src/main/java/com/iformall/dto/PageUserVideoDTO.java new file mode 100644 index 0000000..c949a1c --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PageUserVideoDTO.java @@ -0,0 +1,20 @@ +package com.iformall.dto; + +import com.iformall.domain.po.sm.UserMouldVideo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "分页查询用户视频请求参数") +@Data +public class PageUserVideoDTO extends PageDTO { + + @ApiModelProperty("名称") + private String title; + + public static UserMouldVideo mappingPO(PageUserVideoDTO dto) { + UserMouldVideo userMouldVideo = new UserMouldVideo(); + userMouldVideo.setTitle(dto.getTitle()); + return userMouldVideo; + } +} diff --git a/open-api/src/main/java/com/iformall/dto/PreviewVideoDTO.java b/open-api/src/main/java/com/iformall/dto/PreviewVideoDTO.java new file mode 100644 index 0000000..4bc0355 --- /dev/null +++ b/open-api/src/main/java/com/iformall/dto/PreviewVideoDTO.java @@ -0,0 +1,39 @@ +package com.iformall.dto; + +import com.iformall.sm.AiPreviewParam; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +/** + * 参数示例: + * { + * "paperwork": "文案", + * "voiceId": "zh-CN-XiaomengNeural", + * "voiceStyle": "default" + * } + * + * @author xmzhao71 + * @date 2023-10-23 + */ +@ApiModel(value = "预览视频请求参数") +@Data +public class PreviewVideoDTO { + @ApiModelProperty("文案") + private String paperwork; + @ApiModelProperty("声音id") + private String voiceId; + @ApiModelProperty("声音风格名称") + private String voiceStyle; + @ApiModelProperty("性别(male:男,female:女)") + private String gender; + + public static AiPreviewParam mappingParam(PreviewVideoDTO dto) { + AiPreviewParam aiPreviewParam = new AiPreviewParam(); + aiPreviewParam.setGen_txt(dto.getPaperwork()); + aiPreviewParam.setVoice_id(dto.getVoiceId()); + aiPreviewParam.setVoice_style(dto.getVoiceStyle()); + aiPreviewParam.setGender(dto.getGender()); + return aiPreviewParam; + } +} diff --git a/open-api/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java b/open-api/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java new file mode 100644 index 0000000..5b5cf7e --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java @@ -0,0 +1,128 @@ +package com.iformall.interceptor; + +import com.alibaba.fastjson.JSONObject; +import com.iformall.common.CommonConstants; +import com.iformall.common.ErrorCode; +import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.exception.MallinkException; +import com.iformall.service.WxThirdPartyApiService; +import com.iformall.utils.Constant; +import com.iformall.utils.RedisCacheUtils; +import com.iformall.utils.sign.SignUtils; +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.Qualifier; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.BufferedReader; +import java.util.Map; + + +@Component +public class AuthorizationInterceptor extends HandlerInterceptorAdapter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + private final String[] notKeys = {"sign","appId","appKey","signKey"}; + + @Autowired + @Qualifier("objectCommonRedisTemplate") + RedisTemplate redisTemplate; + + @Autowired + WxThirdPartyApiService wxThirdPartyApiService; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + + response.setHeader("Content-type", "application/json;charset=UTF-8"); + + String appkey = request.getHeader("appkey"); + if (StringUtils.isBlank(appkey) || !appkey.contains("&")) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"非法请求"); + } + String[] split = appkey.split("&"); + WxThirdPartyApi apiConfig = wxThirdPartyApiService.findByApp(split[0], split[1]); + if(apiConfig == null){ + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"非法请求"); + } + if (apiConfig.getStatus().intValue() == CommonConstants.STATUS_ABNORMAL.intValue()) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"app已封禁"); + } + request.setAttribute(Constant.SERVICE_ID, apiConfig.getServiceId()); + request.setAttribute(Constant.APP_Id, apiConfig.getAppId()); + request.setAttribute(Constant.TENANT_ID, apiConfig.getTenantId()); + request.setAttribute(Constant.PARENT_TENANT_ID, apiConfig.getParentTenantId()); + + String signature = request.getHeader("sign"); + logger.info("sign={}"+signature); + //没有加密 + if (StringUtils.isBlank(signature)) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"缺少加密串"); + } + +// BufferedReader reader = request.getReader(); +// StringBuilder stringBuilder = new StringBuilder(); +// String line; +// while ((line = reader.readLine()) != null) { +// stringBuilder.append(line); +// } +// String body = stringBuilder.toString(); +// //Map requestBodyMap = new Gson().fromJson(body, Map.class); + String body = ((BodyReaderHttpServletRequestWrapper) request).getBody(); + if(StringUtils.isBlank(body)){ + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"缺少请求body"); + } + try{ + logger.info("请求body{}--"+body); + Map parameterMap = JSONObject.parseObject(body, Map.class); + if(parameterMap.isEmpty()){ + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"参数格式不正确"); + } + + String timeStamp = parameterMap.get("timeStamp")==null?"":parameterMap.get("timeStamp").toString(); + if(StringUtils.isBlank(timeStamp)){ + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"缺少timeStamp"); + } + long timestampDate = Long.parseLong(timeStamp) + 1000*60*5;//五分钟有效 + long currDate = System.currentTimeMillis(); + // 请求过期 + if (timestampDate < currDate) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"请求过期"); + } + + for (String key:notKeys) { + parameterMap.remove(key); + } + + String newSignature = SignUtils.getSign(apiConfig.getSignKey(), parameterMap, "MD5"); + logger.info("newSignature={}"+newSignature); + //加密串不匹配 + if (!signature.equals(newSignature)) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"加密串校验失败"); + } + Integer cache = RedisCacheUtils.getCacheInteger(redisTemplate, Constant.publicApiNonce+signature); + + if (null != cache) { + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"重复调用"); + } + RedisCacheUtils.cache(redisTemplate, Constant.publicApiNonce+signature, 1, 300); + return true; + + }catch(MallinkException e){ + throw e; + } + catch(Exception e){ + throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"参数格式不正确"); + } + + } + +} diff --git a/open-api/src/main/java/com/iformall/interceptor/BodyReaderHttpServletRequestWrapper.java b/open-api/src/main/java/com/iformall/interceptor/BodyReaderHttpServletRequestWrapper.java new file mode 100644 index 0000000..c949469 --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/BodyReaderHttpServletRequestWrapper.java @@ -0,0 +1,99 @@ +package com.iformall.interceptor; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import java.io.*; + +public class BodyReaderHttpServletRequestWrapper extends XssHttpServletRequestWrapper { + private final String body; + + public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException { + super(request); + StringBuilder stringBuilder = new StringBuilder(); + BufferedReader bufferedReader = null; + try { + InputStream inputStream = cloneInputStream(request.getInputStream()); + if (inputStream != null) { + bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8")); + char[] charBuffer = new char[1024]; + int bytesRead = -1; + while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { + stringBuilder.append(charBuffer, 0, bytesRead); + } + } else { + stringBuilder.append(""); + } + } catch (IOException ex) { + throw ex; + } finally { + if (bufferedReader != null) { + try { + bufferedReader.close(); + } catch (IOException ex) { + throw ex; + } + } + } + body = stringBuilder.toString(); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + final ByteArrayInputStream byteArrayInputStream = + new ByteArrayInputStream(body.getBytes("utf-8")); + return new ServletInputStream() { + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener readListener) { + + } + + @Override + public int read() throws IOException { + return byteArrayInputStream.read(); + } + }; + } + + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(this.getInputStream())); + } + + /** + * Description: 复制输入流
+ * + * @param inputStream + * @return
+ */ + public InputStream cloneInputStream(ServletInputStream inputStream) { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len; + try { + while ((len = inputStream.read(buffer)) > -1) { + byteArrayOutputStream.write(buffer, 0, len); + } + byteArrayOutputStream.flush(); + } + catch (IOException e) { + e.printStackTrace(); + } + InputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + return byteArrayInputStream; + } + + public String getBody() { + return this.body; + } +} diff --git a/open-api/src/main/java/com/iformall/interceptor/HttpServletRequestWrapperFilter.java b/open-api/src/main/java/com/iformall/interceptor/HttpServletRequestWrapperFilter.java new file mode 100644 index 0000000..b2cb876 --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/HttpServletRequestWrapperFilter.java @@ -0,0 +1,70 @@ +package com.iformall.interceptor; + +import com.iformall.util.UrlCheck; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; + +public class HttpServletRequestWrapperFilter implements Filter { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + // 多个跨域域名设置 + // public static final String[] ALLOW_DOMAIN = {"https://admin.malls.iformall.com"}; + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + logger.debug("doFilter start"); + long start = System.currentTimeMillis(); + ServletRequest requestWrapper = null; + + /* // 跨域访问 + HttpServletRequest req = (HttpServletRequest) request; + HttpServletResponse res = (HttpServletResponse) response; + String originHeader = req.getHeader("Origin"); + + if (Arrays.asList(ALLOW_DOMAIN).contains(originHeader)) { + //通过在响应 header 中设置 ‘*’ 来允许来自所有域的跨域请求访问。 + res.setHeader("Access-Control-Allow-Origin", originHeader); + //通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie + //设置了Allow-Credentials,Allow-Origin就不能为*,需要指明具体的url域 + res.setHeader("Access-Control-Allow-Credentials", "true"); + //请求方式 + res.setHeader("Access-Control-Allow-Methods", "*"); + //(预检请求)的返回结果(即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息) 可以被缓存多久 + res.setHeader("Access-Control-Max-Age", "86400"); + //首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段 + //res.setHeader("Access-Control-Allow-Headers", "*"); + res.setHeader("Access-Control-Allow-Headers", + "Timestamp,Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers"); + } + */ + + //sql,xss过滤 + XssHttpServletRequestWrapper xssHttpServletRequestWrapper = new XssHttpServletRequestWrapper((HttpServletRequest)request); + String url = ""; + if (request instanceof HttpServletRequest) { + url = ((HttpServletRequest) request).getRequestURI(); + if (!UrlCheck.checkUrl(url)) { + requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request); + } + } + if (null == requestWrapper) { + chain.doFilter(xssHttpServletRequestWrapper, response); + } else { + chain.doFilter(requestWrapper, response); + } + logger.debug("doFilter end: " + url + " "+ (System.currentTimeMillis()- start) + "ms"); + } + + @Override + public void destroy() { + + } +} diff --git a/open-api/src/main/java/com/iformall/interceptor/RequestInterceptor.java b/open-api/src/main/java/com/iformall/interceptor/RequestInterceptor.java new file mode 100644 index 0000000..4b64964 --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/RequestInterceptor.java @@ -0,0 +1,122 @@ +package com.iformall.interceptor; + +import com.iformall.common.ErrorCode; +import com.iformall.exception.MallinkException; +import com.iformall.util.UrlCheck; +import com.iformall.utils.HashUtil; +import com.iformall.utils.IPUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.connection.RedisConnection; +import org.springframework.data.redis.core.RedisCallback; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.util.SafeEncoder; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.nio.charset.Charset; +import java.util.Enumeration; + +/** + * 幂等检查 + * @author stormeye.wu + * @email wuguoqiang@iformall.com + * @date 2017-03-23 15:38 + */ +@Component +public class RequestInterceptor extends HandlerInterceptorAdapter { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Resource + private RedisTemplate redisTemplate; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + logger.debug("preHandle start"); + if ("GET".equalsIgnoreCase(request.getMethod())) { + // 获取不检查幂等 + logger.debug("preHandle start 1"); + return true; + } + String ipaddress = IPUtil.getIpAddr(request); + String url = request.getRequestURL().toString(); + if (UrlCheck.checkUrl(url)) { + // pvlog不检查幂等 + // awsFileUpload不检查幂等 + // stopFee + return true; + } + StringBuilder sb = new StringBuilder(); + + sb.append(url); + + sb.append("method=").append(request.getMethod()).append("&"); + + sb.append("ip=").append(ipaddress).append("&"); + + final Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String key = (String) parameterNames.nextElement(); + if(key.equalsIgnoreCase("ran")) // 跳过ran + continue; + String parameter = request.getParameter(key); + sb.append(key).append("=").append(parameter).append("&"); + } + + InputStream inStream = request.getInputStream(); + ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int len = 0; + while ((len = inStream.read(buffer)) != -1) { + outSteam.write(buffer, 0, len); + } + String resultBody = new String(outSteam.toByteArray(), Charset.forName("UTF-8")); + inStream.close(); + outSteam.close(); + + sb.append(resultBody); + + String key = "request:C:" + HashUtil.md5(sb.toString()); + Boolean isAbsent = redisTemplate.execute(new RedisCallback() { + @Override + public Boolean doInRedis(RedisConnection connection) throws DataAccessException { + RedisSerializer valueSerializer = redisTemplate.getValueSerializer(); + RedisSerializer keySerializer = redisTemplate.getKeySerializer(); + Object obj = connection.execute("set", keySerializer.serialize(key), + valueSerializer.serialize(key), + SafeEncoder.encode("NX"), + SafeEncoder.encode("EX"), + Protocol.toByteArray(3)); // 3s + return obj != null; + } + }); + if (isAbsent) { + logger.info(key + ": 第一次提交"); + logger.debug("preHandle start 2"); + return true; + } + logger.info(key + ": 第二次提交"); + logger.debug("preHandle start 3"); + throw new MallinkException(ErrorCode.SYS_REPEAT_SUBMIT_EXCEPTION); + } + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { + logger.debug("postHandle"); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { + logger.debug("afterCompletion"); + } +} diff --git a/open-api/src/main/java/com/iformall/interceptor/WebLogAspect.java b/open-api/src/main/java/com/iformall/interceptor/WebLogAspect.java new file mode 100644 index 0000000..b1aafc3 --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/WebLogAspect.java @@ -0,0 +1,71 @@ +package com.iformall.interceptor; + +import com.iformall.utils.IPUtil; +import lombok.Data; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; + +@Aspect +@Component +public class WebLogAspect { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Data + private class MethodInfo { + Long startTime; + String url; + String ip; + String method; + String classMethod; + } + + ThreadLocal startInfo = new ThreadLocal<>(); + + + @Pointcut("execution(public * com.iformall.controller..*.*(..))") + public void webLog() {} + + @Before("webLog()") + public void doBefore(JoinPoint joinPoint) throws Throwable { + logger.debug("aspect start"); + // 接收到请求,记录请求内容 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + + MethodInfo info = new MethodInfo(); + info.setUrl(request.getRequestURL().toString()); + info.setStartTime(System.currentTimeMillis()); + info.setIp(IPUtil.getIpAddr(request)); + info.setMethod(request.getMethod()); + info.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); + startInfo.set(info); + logger.debug("aspect start ..."); + } + + @AfterReturning(returning = "ret", pointcut = "webLog()") + public void doAfterReturning(Object ret) throws Throwable { + logger.debug("aspect after"); + // 处理完请求,返回内容 + MethodInfo info = startInfo.get(); + StringBuilder sb = new StringBuilder(); + sb.append("URL: ").append(info.getUrl()) + .append(", METHOD: ").append(info.getMethod()) + .append(", DO: ").append(info.getClassMethod()) + .append(", IP: ").append(info.getIp()) + .append(", SPEND TIME: ").append(System.currentTimeMillis() -info.getStartTime()).append("ms"); + logger.info(sb.toString()); + logger.debug("aspect after .."); + } + + +} diff --git a/open-api/src/main/java/com/iformall/interceptor/XssHttpServletRequestWrapper.java b/open-api/src/main/java/com/iformall/interceptor/XssHttpServletRequestWrapper.java new file mode 100644 index 0000000..1d954d1 --- /dev/null +++ b/open-api/src/main/java/com/iformall/interceptor/XssHttpServletRequestWrapper.java @@ -0,0 +1,125 @@ +package com.iformall.interceptor; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * 防止sql注入,xss攻击 + * 前端可以对输入信息做预处理,后端也可以做处理。 + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { + private final Logger log = LoggerFactory.getLogger(getClass()); + private static String key = "and|exec|insert|select|delete|update|count|*|%|chr|mid|master|truncate|char|declare|;|or|-|+"; + private static Set notAllowedKeyWords = new HashSet(0); + private static String replacedString="INVALID"; + static { + String keyStr[] = key.split("\\|"); + for (String str : keyStr) { + notAllowedKeyWords.add(str); + } + } + + private String currentUrl; + + public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) { + super(servletRequest); + currentUrl = servletRequest.getRequestURI(); + } + + + /**覆盖getParameter方法,将参数名和参数值都做xss过滤。 + * 如果需要获得原始的值,则通过super.getParameterValues(name)来获取 + * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖 + */ + @Override + public String getParameter(String parameter) { + String value = super.getParameter(parameter); + if (value == null) { + return null; + } + return cleanXSS(value); + } + @Override + public String[] getParameterValues(String parameter) { + String[] values = super.getParameterValues(parameter); + if (values == null) { + return null; + } + int count = values.length; + String[] encodedValues = new String[count]; + for (int i = 0; i < count; i++) { + encodedValues[i] = cleanXSS(values[i]); + } + return encodedValues; + } + @Override + public Map getParameterMap(){ + Map values=super.getParameterMap(); + if (values == null) { + return null; + } + Map result=new HashMap<>(); + for(String key:values.keySet()){ + String encodedKey=cleanXSS(key); + int count=values.get(key).length; + String[] encodedValues = new String[count]; + for (int i = 0; i < count; i++){ + encodedValues[i]=cleanXSS(values.get(key)[i]); + } + result.put(encodedKey,encodedValues); + } + return result; + } + /** + * 覆盖getHeader方法,将参数名和参数值都做xss过滤。 + * 如果需要获得原始的值,则通过super.getHeaders(name)来获取 + * getHeaderNames 也可能需要覆盖 + */ + @Override + public String getHeader(String name) { + if(name.equalsIgnoreCase("user-agent")) { + return super.getHeader(name); + } + String value = super.getHeader(name); + if (value == null) { + return null; + } + return cleanXSS(value); + } + + private String cleanXSS(String valueP) { + // You'll need to remove the spaces from the html entities below + String value = valueP.replaceAll("<", "<").replaceAll(">", ">"); + value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;"); + value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;"); + value = value.replaceAll("'", "& #39;"); + value = value.replaceAll("eval\\((.*)\\)", ""); + value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); + value = value.replaceAll("script", ""); + value = cleanSqlKeyWords(value); + return value; + } + + private String cleanSqlKeyWords(String value) { + String paramValue = value; + for (String keyword : notAllowedKeyWords) { + if (paramValue.length() > keyword.length() + 4 + && (paramValue.contains(" "+keyword)||paramValue.contains(keyword+" ")||paramValue.contains(" "+keyword+" "))) { + paramValue = StringUtils.replace(paramValue, keyword, replacedString); + log.error(this.currentUrl + "已被过滤,因为参数中包含不允许sql的关键词(" + keyword + + ")"+";参数:"+value+";过滤后的参数:"+paramValue); + } + } + return paramValue; + } + +} diff --git a/open-api/src/main/java/com/iformall/service/AiVideoService.java b/open-api/src/main/java/com/iformall/service/AiVideoService.java new file mode 100644 index 0000000..65d4282 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/AiVideoService.java @@ -0,0 +1,35 @@ +package com.iformall.service; + +import com.iformall.dto.PageServiceVideoRecordDTO; +import com.iformall.sm.AiPreviewParam; +import com.iformall.sm.AiPreviewResult; +import com.iformall.sm.AiVideoParam; +import com.iformall.sm.AiVideoResult; +import com.iformall.vo.PageServiceVedioRecordVO; +import com.iformall.vo.PageVO; + +/** + * ai视频服务 + * + * @author xmzhao71 + * @date 2023-10-18 + */ +public interface AiVideoService { + + AiPreviewResult previewVideo(AiPreviewParam aiPreviewParam); + + /** + * 生成视频 + * + * @param aiVideoParam + * @return {@link AiVideoResult} + */ + AiVideoResult generateVideo(AiVideoParam aiVideoParam, Long serviceId); + + /** + * 生成视频记录分页 + * @param dto + * @return + */ + PageVO serviceVideoRecords(PageServiceVideoRecordDTO dto); +} diff --git a/open-api/src/main/java/com/iformall/service/ApiMaterialMouldService.java b/open-api/src/main/java/com/iformall/service/ApiMaterialMouldService.java new file mode 100644 index 0000000..f84ce4f --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/ApiMaterialMouldService.java @@ -0,0 +1,15 @@ +package com.iformall.service; + +import com.iformall.dto.PageMaterialMouldDTO; +import com.iformall.vo.PageMaterialMouldVO; +import com.iformall.vo.PageVO; + +/** + * 物料模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +public interface ApiMaterialMouldService { + PageVO pageMaterialMould(PageMaterialMouldDTO dto); +} diff --git a/open-api/src/main/java/com/iformall/service/ApiPersonMouldService.java b/open-api/src/main/java/com/iformall/service/ApiPersonMouldService.java new file mode 100644 index 0000000..087f53c --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/ApiPersonMouldService.java @@ -0,0 +1,32 @@ +package com.iformall.service; + +import com.github.pagehelper.PageInfo; +import com.iformall.dto.PagePersonMouldDTO; +import com.iformall.vo.GetPersonMouldVO; +import com.iformall.vo.PagePersonMouldVO; +import com.iformall.vo.PageVO; + +/** + * 数字人模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +public interface ApiPersonMouldService { + + /** + * 分页查询数字人模板 + * + * @param dto + * @return {@link PageInfo}<{@link PagePersonMouldVO}> + */ + PageVO pagePersonMould(PagePersonMouldDTO dto); + + /** + * 单个查询数字人模板 + * + * @param id + * @return {@link GetPersonMouldVO} + */ + GetPersonMouldVO getPersonMould(Long id); +} diff --git a/open-api/src/main/java/com/iformall/service/ApiUserVideoService.java b/open-api/src/main/java/com/iformall/service/ApiUserVideoService.java new file mode 100644 index 0000000..55f4fa2 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/ApiUserVideoService.java @@ -0,0 +1,21 @@ +package com.iformall.service; + +import com.iformall.dto.PageUserVideoDTO; +import com.iformall.vo.GetUserVideoVO; +import com.iformall.vo.PageUserVideoVO; +import com.iformall.vo.PageVO; + +/** + * 用户视频service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +public interface ApiUserVideoService { + + PageVO pageUserVideo(PageUserVideoDTO dto); + + GetUserVideoVO getUserVideo(Long id); + + void deleteUserVideo(Long id); +} diff --git a/open-api/src/main/java/com/iformall/service/ApiVoiceMouldService.java b/open-api/src/main/java/com/iformall/service/ApiVoiceMouldService.java new file mode 100644 index 0000000..da16ef5 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/ApiVoiceMouldService.java @@ -0,0 +1,31 @@ +package com.iformall.service; + +import com.iformall.dto.ListVoiceLanguageDTO; +import com.iformall.vo.GetVoiceMouldVO; +import com.iformall.vo.ListVoiceLanguageVO; + +import java.util.List; + +/** + * 声音模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +public interface ApiVoiceMouldService { + /** + * 全查询语种 + * + * @param dto + * @return {@link List}<{@link ListVoiceLanguageVO}> + */ + List listVoiceLanguage(ListVoiceLanguageDTO dto); + + /** + * 单个查询声音风格 + * + * @param id + * @return {@link GetVoiceMouldVO} + */ + List getVoiceMould(Long id); +} diff --git a/open-api/src/main/java/com/iformall/service/impl/AiVideoServiceImpl.java b/open-api/src/main/java/com/iformall/service/impl/AiVideoServiceImpl.java new file mode 100644 index 0000000..adeb71c --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/impl/AiVideoServiceImpl.java @@ -0,0 +1,99 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.CommonConstants; +import com.iformall.domain.dto.sm.SaveServiceVideoRecordDTO; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import com.iformall.dto.GenerateVideoDTO; +import com.iformall.dto.PagePersonMouldDTO; +import com.iformall.dto.PageServiceVideoRecordDTO; +import com.iformall.enums.sm.EnumThirdPartyType; +import com.iformall.service.AiVideoService; +import com.iformall.service.sm.ServiceInfoService; +import com.iformall.service.sm.ServiceVideoRecordService; +import com.iformall.sm.*; +import com.iformall.utils.Base64Util; +import com.iformall.vo.PagePersonMouldVO; +import com.iformall.vo.PageServiceVedioRecordVO; +import com.iformall.vo.PageVO; + +import java.math.BigDecimal; +import java.util.List; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * ai视频服务 + * + * @author xmzhao71 + * @date 2023-10-18 + */ +@Service +public class AiVideoServiceImpl implements AiVideoService { + + @Autowired + private ServiceInfoService serviceInfoService; + @Autowired + private ServiceVideoRecordService serviceVideoRecordService; + + @Override + public AiPreviewResult previewVideo(AiPreviewParam aiPreviewParam) { + return AiVideoHelper.voicePreview(aiPreviewParam); + } + + @Override + public AiVideoResult generateVideo(AiVideoParam aiVideoParam, Long serviceId) { + // 查询该接入商的接入方式 + ServiceInfo serviceInfo = serviceInfoService.getServiceInfo(serviceId); + // 如果是api接入,则将图片地址转为base64 + if (EnumThirdPartyType.API_JOIN.getCode().equals(serviceInfo.getType())) { + //判断时长是否还有 + if (serviceInfo.getRemainingTimes() <= 0 ) { + AiVideoResult result = new AiVideoResult(); + result.setSuccess(false); + result.setMsg("接入方无有效时长,请联系销售充时长。"); + return result; + } + AiVideoParam.VideoFiles videoFiles = aiVideoParam.getVideo_files(); + videoFiles.getBack_ground().setImage(Base64Util.imageUrlToBase64(videoFiles.getBack_ground().getImage())); + for (AiVideoParam.Material material : videoFiles.getMaterial()) { + material.setImage(Base64Util.imageUrlToBase64(material.getImage())); + } + }else if(EnumThirdPartyType.PRIVATE_JOIN.getCode().equals(serviceInfo.getType())) { + //私有化部署校验时长 + if (serviceInfo.getRemainingTimes() <= 0 ) { + AiVideoResult result = new AiVideoResult(); + result.setSuccess(false); + result.setMsg("接入方无有效时长,请联系销售充时长。"); + return result; + } + //本地部署的视频文件都是路径 + } + + AiVideoResult video = AiVideoHelper.createVideo(aiVideoParam); + if (video.isSuccess()) { + // 记录时长 + SaveServiceVideoRecordDTO saveServiceVideoRecordDTO = SaveServiceVideoRecordDTO.builder() + .serviceId(serviceId) + .videoTime(String.valueOf(video.getDuration())) + .videoUrl(video.getUrl()) + .userMouldVideoId(aiVideoParam.getTask_id()) + .build(); + serviceVideoRecordService.saveServiceVideoRecord(saveServiceVideoRecordDTO); + //扣掉总时长 + serviceInfoService.reduceTimes(serviceId, new BigDecimal(video.getDuration()).setScale(0,BigDecimal.ROUND_UP).longValue()); + } + return video; + } + + @Override + public PageVO serviceVideoRecords(PageServiceVideoRecordDTO dto) { + PageInfo personMouldPage = serviceVideoRecordService.listAsPage(PageServiceVideoRecordDTO.mappingPO(dto), dto.getPageNum(), dto.getPageSize()); + List result = personMouldPage.getList().stream().map(PageServiceVedioRecordVO::mapping).collect(Collectors.toList()); + return PageVO.build(personMouldPage.getTotal(), result); + } +} diff --git a/open-api/src/main/java/com/iformall/service/impl/ApiMaterialMouldServiceImpl.java b/open-api/src/main/java/com/iformall/service/impl/ApiMaterialMouldServiceImpl.java new file mode 100644 index 0000000..72ec395 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/impl/ApiMaterialMouldServiceImpl.java @@ -0,0 +1,34 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.sm.MaterialMould; +import com.iformall.dto.PageMaterialMouldDTO; +import com.iformall.service.ApiMaterialMouldService; +import com.iformall.service.sm.MaterialMouldService; +import com.iformall.vo.PageMaterialMouldVO; +import com.iformall.vo.PageVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 物料模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Service +public class ApiMaterialMouldServiceImpl implements ApiMaterialMouldService { + + @Autowired + private MaterialMouldService materialMouldService; + + @Override + public PageVO pageMaterialMould(PageMaterialMouldDTO dto) { + PageInfo materialMouldPage = materialMouldService.cListAsPage(PageMaterialMouldDTO.mappingPO(dto), dto.getPageNum(), dto.getPageSize()); + List result = materialMouldPage.getList().stream().map(PageMaterialMouldVO::mapping).collect(Collectors.toList()); + return PageVO.build(materialMouldPage.getTotal(), result); + } +} diff --git a/open-api/src/main/java/com/iformall/service/impl/ApiPersonMouldServiceImpl.java b/open-api/src/main/java/com/iformall/service/impl/ApiPersonMouldServiceImpl.java new file mode 100644 index 0000000..e6f3c31 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/impl/ApiPersonMouldServiceImpl.java @@ -0,0 +1,48 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.dto.PagePersonMouldDTO; +import com.iformall.service.ApiPersonMouldService; +import com.iformall.service.sm.PersonMouldService; +import com.iformall.vo.GetPersonMouldVO; +import com.iformall.vo.PagePersonMouldVO; +import com.iformall.vo.PageVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * 数字人模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Service +public class ApiPersonMouldServiceImpl implements ApiPersonMouldService { + + @Autowired + private PersonMouldService personMouldService; + + @Override + public PageVO pagePersonMould(PagePersonMouldDTO dto) { + List mouidList = personMouldService.getServiceMouldIds(dto.getServiceId()); + if (null == mouidList || mouidList.size() <= 0 ) { + dto.setId(-1L); + }else { + dto.setIds(mouidList); + } + PageInfo personMouldPage = personMouldService.cListAsPage(PagePersonMouldDTO.mappingPO(dto), dto.getPageNum(), dto.getPageSize()); + List result = personMouldPage.getList().stream().map(PagePersonMouldVO::mapping).collect(Collectors.toList()); + return PageVO.build(personMouldPage.getTotal(), result); + } + + @Override + public GetPersonMouldVO getPersonMould(Long id) { + PersonMould personMould = personMouldService.getDetailById(id); + return GetPersonMouldVO.mapping(personMould); + } +} diff --git a/open-api/src/main/java/com/iformall/service/impl/ApiUserVideoServiceImpl.java b/open-api/src/main/java/com/iformall/service/impl/ApiUserVideoServiceImpl.java new file mode 100644 index 0000000..8326214 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/impl/ApiUserVideoServiceImpl.java @@ -0,0 +1,46 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.sm.UserMouldVideo; +import com.iformall.dto.PageUserVideoDTO; +import com.iformall.service.ApiUserVideoService; +import com.iformall.service.sm.UserMouldVideoService; +import com.iformall.vo.GetUserVideoVO; +import com.iformall.vo.PageUserVideoVO; +import com.iformall.vo.PageVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 用户视频service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Service +public class ApiUserVideoServiceImpl implements ApiUserVideoService { + + @Autowired + private UserMouldVideoService userMouldVideoService; + + @Override + public PageVO pageUserVideo(PageUserVideoDTO dto) { + PageInfo userMouldVideoPage = userMouldVideoService.cListAsPage(PageUserVideoDTO.mappingPO(dto), dto.getPageNum(), dto.getPageSize()); + List result = userMouldVideoPage.getList().stream().map(PageUserVideoVO::mapping).collect(Collectors.toList()); + return PageVO.build(userMouldVideoPage.getTotal(), result); + } + + @Override + public GetUserVideoVO getUserVideo(Long id) { + UserMouldVideo userMouldVideo = userMouldVideoService.getUserVideo(id); + return GetUserVideoVO.mapping(userMouldVideo); + } + + @Override + public void deleteUserVideo(Long id) { + userMouldVideoService.deleteById(id); + } +} diff --git a/open-api/src/main/java/com/iformall/service/impl/ApiVoiceMouldServiceImpl.java b/open-api/src/main/java/com/iformall/service/impl/ApiVoiceMouldServiceImpl.java new file mode 100644 index 0000000..8450949 --- /dev/null +++ b/open-api/src/main/java/com/iformall/service/impl/ApiVoiceMouldServiceImpl.java @@ -0,0 +1,42 @@ +package com.iformall.service.impl; + +import com.iformall.domain.po.sm.VoiceInfo; +import com.iformall.domain.po.sm.VoiceLanguage; +import com.iformall.dto.ListVoiceLanguageDTO; +import com.iformall.service.ApiVoiceMouldService; +import com.iformall.service.sm.VoiceInfoService; +import com.iformall.service.sm.VoiceLanguageService; +import com.iformall.vo.GetVoiceMouldVO; +import com.iformall.vo.ListVoiceLanguageVO; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.stream.Collectors; + +/** + * 声音模板service + * + * @author xmzhao71 + * @date 2023-10-17 + */ +@Service +public class ApiVoiceMouldServiceImpl implements ApiVoiceMouldService { + + @Autowired + private VoiceLanguageService voiceLanguageService; + @Autowired + private VoiceInfoService voiceInfoService; + + @Override + public List listVoiceLanguage(ListVoiceLanguageDTO dto) { + List voiceLanguages = voiceLanguageService.listVoiceLanguage(dto.getChineseName()); + return voiceLanguages.stream().map(ListVoiceLanguageVO::mapping).collect(Collectors.toList()); + } + + @Override + public List getVoiceMould(Long id) { + List voiceInfos = voiceInfoService.chooseType(id); + return voiceInfos.stream().map(GetVoiceMouldVO::mapping).collect(Collectors.toList()); + } +} diff --git a/open-api/src/main/java/com/iformall/util/UrlCheck.java b/open-api/src/main/java/com/iformall/util/UrlCheck.java new file mode 100644 index 0000000..0e350d6 --- /dev/null +++ b/open-api/src/main/java/com/iformall/util/UrlCheck.java @@ -0,0 +1,11 @@ +package com.iformall.util; + +public class UrlCheck { + + public static boolean checkUrl(String url) { + return url.contains("awsFileUpload") + || url.contains("awsFilesUpload") + || url.contains("getCarStopFee"); + } + +} diff --git a/open-api/src/main/java/com/iformall/vo/GetPersonMouldVO.java b/open-api/src/main/java/com/iformall/vo/GetPersonMouldVO.java new file mode 100644 index 0000000..522dfe4 --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/GetPersonMouldVO.java @@ -0,0 +1,65 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.PersonMould; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "单个查询数字人模板返回数据") +@Data +public class GetPersonMouldVO { + @ApiModelProperty("模板标识") + private Long id; + @ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + @ApiModelProperty("0:保密,1:男,2:女") + private Integer sex; + @ApiModelProperty("封面图") + private String coverImg; + @ApiModelProperty("多封面图") + private String coverPicture; + @ApiModelProperty("详情多图") + private String detailPicture; + @ApiModelProperty("年龄") + private Integer age; + @ApiModelProperty("颜色") + private Integer colour; + @ApiModelProperty("背景id") + private Long backgroundId; + @ApiModelProperty("背景素材") + private String backgroundMaterial; + @ApiModelProperty("创建时间") + private Date createDate; + @ApiModelProperty("更新时间") + private Date updateDate; + @ApiModelProperty("素材") + private String material; + @ApiModelProperty("模板第三方Id") + private String mouldSmId; + @ApiModelProperty("模板类型") + private Integer sendType; + @ApiModelProperty("状态(-1:全部,0:草稿/待生效,1:已生效,2:已失效,3:已作废)") + private Integer status; + + public static GetPersonMouldVO mapping(PersonMould personMould) { + GetPersonMouldVO vo = new GetPersonMouldVO(); + vo.setId(personMould.getId()); + vo.setVideoType(personMould.getVideoType()); + vo.setSex(personMould.getSex()); + vo.setCoverImg(personMould.getCoverImg()); + vo.setCoverPicture(personMould.getCoverPicture()); + vo.setDetailPicture(personMould.getDetailPicture()); + vo.setAge(personMould.getAge()); + vo.setColour(personMould.getColour()); + vo.setBackgroundId(personMould.getBackgroundId()); + vo.setBackgroundMaterial(personMould.getBackgroundMaterial()); + vo.setCreateDate(personMould.getCreateDate()); + vo.setUpdateDate(personMould.getUpdateDate()); + vo.setMaterial(personMould.getMaterial()); + vo.setSendType(personMould.getSendType()); + vo.setStatus(personMould.getStatus()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/GetUserVideoVO.java b/open-api/src/main/java/com/iformall/vo/GetUserVideoVO.java new file mode 100644 index 0000000..84467de --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/GetUserVideoVO.java @@ -0,0 +1,64 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.UserMouldVideo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "单个查询用户视频返回数据") +@Data +public class GetUserVideoVO { + + @ApiModelProperty("用户视频标识") + private Long id; + @ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + @ApiModelProperty(value="封面图",name="coverImg") + private String coverImg; + @ApiModelProperty(value="生成视频时间",name="createVideoDate") + private Date createVideoDate; + @ApiModelProperty(value="文案",name="paperwork") + private String paperwork; + @ApiModelProperty(value="名称",name="title") + private String title; + @ApiModelProperty(value="视频文件",name="videoId") + private String videoId; + @ApiModelProperty(value="生成视频信息",name="videoMsg") + private String videoMsg; + @ApiModelProperty(value="视频地址",name="videoPath") + private String videoPath; + @ApiModelProperty(value="播放地址",name="videoPlayUrl") + private String videoPlayUrl; + @ApiModelProperty(value="视频大小(byte)",name="videoSize") + private Long videoSize; + @ApiModelProperty("视频状态") + private Integer videoStatus; + @ApiModelProperty(value="视频时长(秒)",name="videoTime") + private String videoTime; + @ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + + public static GetUserVideoVO mapping(UserMouldVideo userMouldVideo) { + GetUserVideoVO vo = new GetUserVideoVO(); + vo.setId(userMouldVideo.getId()); + vo.setCreateDate(userMouldVideo.getCreateDate()); + vo.setUpdateDate(userMouldVideo.getUpdateDate()); + vo.setCoverImg(userMouldVideo.getCoverImg()); + vo.setCreateVideoDate(userMouldVideo.getCreateVideoDate()); + vo.setPaperwork(userMouldVideo.getPaperwork()); + vo.setTitle(userMouldVideo.getTitle()); + vo.setVideoId(userMouldVideo.getVideoId()); + vo.setVideoMsg(userMouldVideo.getVideoMsg()); + vo.setVideoPath(userMouldVideo.getVideoPath()); + vo.setVideoPlayUrl(userMouldVideo.getVideoPlayUrl()); + vo.setVideoSize(userMouldVideo.getVideoSize()); + vo.setVideoStatus(userMouldVideo.getVideoStatus()); + vo.setVideoTime(userMouldVideo.getVideoTime()); + vo.setVideoType(userMouldVideo.getVideoType()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/GetVoiceMouldVO.java b/open-api/src/main/java/com/iformall/vo/GetVoiceMouldVO.java new file mode 100644 index 0000000..0b7ac7f --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/GetVoiceMouldVO.java @@ -0,0 +1,44 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.VoiceInfo; +import com.iformall.domain.vo.VoiceInfoVo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; + +import java.util.Collections; +import java.util.Date; +import java.util.List; + +@ApiModel(value = "单个查询声音风格返回数据") +@Data +public class GetVoiceMouldVO { + + @ApiModelProperty("性别") + private Integer sex; + @ApiModelProperty("年纪类型") + private Integer ageType; + @ApiModelProperty("展示名称") + private String displayName; + @ApiModelProperty("本地名称") + private String localName; + @ApiModelProperty("创建时间") + private Date createDate; + @ApiModelProperty("更新时间") + private Date updateDate; + @ApiModelProperty("声音风格") + private List styles; + + public static GetVoiceMouldVO mapping(VoiceInfo voiceInfo) { + GetVoiceMouldVO vo = new GetVoiceMouldVO(); + vo.setSex(voiceInfo.getSex()); + vo.setAgeType(voiceInfo.getAgeType()); + vo.setDisplayName(voiceInfo.getDisplayName()); + vo.setLocalName(voiceInfo.getLocalName()); + vo.setCreateDate(voiceInfo.getCreateDate()); + vo.setStyles(voiceInfo.getStyle()); + return null; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/ListVoiceLanguageVO.java b/open-api/src/main/java/com/iformall/vo/ListVoiceLanguageVO.java new file mode 100644 index 0000000..18a590a --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/ListVoiceLanguageVO.java @@ -0,0 +1,45 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.VoiceLanguage; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "全查询语种请求参数返回数据") +@Data +public class ListVoiceLanguageVO { + @ApiModelProperty("语种标识") + private Long id; + @ApiModelProperty("国家code") + private String country; + @ApiModelProperty("语言code") + private String language; + @ApiModelProperty("地区语言") + private String local; + @ApiModelProperty("地区国家名称") + private String name; + @ApiModelProperty("语言名称") + private String chineseName; + @ApiModelProperty("地区国家图片") + private String img; + @ApiModelProperty("创建时间") + private Date createDate; + @ApiModelProperty("更新时间") + private Date updateDate; + + public static ListVoiceLanguageVO mapping(VoiceLanguage voiceLanguage) { + ListVoiceLanguageVO vo = new ListVoiceLanguageVO(); + vo.setId(voiceLanguage.getId()); + vo.setCountry(voiceLanguage.getCountry()); + vo.setLanguage(voiceLanguage.getLanguage()); + vo.setLocal(voiceLanguage.getLocal()); + vo.setName(voiceLanguage.getName()); + vo.setChineseName(voiceLanguage.getChineseName()); + vo.setImg(voiceLanguage.getImg()); + vo.setCreateDate(voiceLanguage.getCreateDate()); + vo.setUpdateDate(voiceLanguage.getUpdateDate()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/PageMaterialMouldVO.java b/open-api/src/main/java/com/iformall/vo/PageMaterialMouldVO.java new file mode 100644 index 0000000..f91eeef --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/PageMaterialMouldVO.java @@ -0,0 +1,38 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.MaterialMould; +import io.swagger.annotations.ApiModel; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "分页查询物料模板返回数据") +@Data +public class PageMaterialMouldVO { + @io.swagger.annotations.ApiModelProperty("物料标识") + private Long id; + @io.swagger.annotations.ApiModelProperty("创建时间") + private Date createDate; + @io.swagger.annotations.ApiModelProperty("更新时间") + private Date updateDate; + @io.swagger.annotations.ApiModelProperty("素材地址") + private String material; + @io.swagger.annotations.ApiModelProperty("名称") + private String title; + @io.swagger.annotations.ApiModelProperty("4:背景,5:素材") + private Integer type; + @io.swagger.annotations.ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + + public static PageMaterialMouldVO mapping(MaterialMould materialMould) { + PageMaterialMouldVO vo = new PageMaterialMouldVO(); + vo.setId(materialMould.getId()); + vo.setCreateDate(materialMould.getCreateDate()); + vo.setUpdateDate(materialMould.getUpdateDate()); + vo.setMaterial(materialMould.getMaterial()); + vo.setTitle(materialMould.getTitle()); + vo.setType(materialMould.getType()); + vo.setVideoType(materialMould.getVideoType()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/PagePersonMouldVO.java b/open-api/src/main/java/com/iformall/vo/PagePersonMouldVO.java new file mode 100644 index 0000000..b513745 --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/PagePersonMouldVO.java @@ -0,0 +1,60 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.PersonMould; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "分页查询数字人模板返回数据") +@Data +public class PagePersonMouldVO { + @ApiModelProperty("模板标识") + private Long id; + @ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + @ApiModelProperty("0:保密,1:男,2:女") + private Integer sex; + @ApiModelProperty("封面图") + private String coverImg; + @ApiModelProperty("多封面图") + private String coverPicture; + @ApiModelProperty("年龄") + private Integer age; + @ApiModelProperty("颜色") + private Integer colour; + @ApiModelProperty("背景id") + private Long backgroundId; + @ApiModelProperty("背景素材") + private String backgroundMaterial; + @ApiModelProperty("创建时间") + private Date createDate; + @ApiModelProperty("更新时间") + private Date updateDate; + @ApiModelProperty("素材") + private String material; + @ApiModelProperty("模板类型") + private Integer sendType; + @ApiModelProperty("状态(-1:全部,0:草稿/待生效,1:已生效,2:已失效,3:已作废)") + private Integer status; + + public static PagePersonMouldVO mapping(PersonMould personMould) { + PagePersonMouldVO vo = new PagePersonMouldVO(); + vo.setId(personMould.getId()); + vo.setVideoType(personMould.getVideoType()); + vo.setSex(personMould.getSex()); + vo.setCoverImg(personMould.getCoverImg()); + vo.setCoverPicture(personMould.getCoverPicture()); + vo.setAge(personMould.getAge()); + vo.setColour(personMould.getColour()); + vo.setBackgroundId(personMould.getBackgroundId()); + vo.setBackgroundMaterial(personMould.getBackgroundMaterial()); + vo.setCreateDate(personMould.getCreateDate()); + vo.setUpdateDate(personMould.getUpdateDate()); + vo.setMaterial(personMould.getMaterial()); + vo.setSendType(personMould.getSendType()); + vo.setStatus(personMould.getStatus()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/PageServiceVedioRecordVO.java b/open-api/src/main/java/com/iformall/vo/PageServiceVedioRecordVO.java new file mode 100644 index 0000000..f851df4 --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/PageServiceVedioRecordVO.java @@ -0,0 +1,31 @@ +package com.iformall.vo; + +import java.util.Date; + +import com.iformall.domain.po.sm.ServiceVideoRecord; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "分页查询数字人模板返回数据") +@Data +public class PageServiceVedioRecordVO { + @ApiModelProperty("接入商标识") + private Long serviceId; + @ApiModelProperty("视频时长") + private String videoTime; + @ApiModelProperty("视频链接") + private String videoUrl; + @ApiModelProperty("创建时间") + private Date createDate; + + + public static PageServiceVedioRecordVO mapping(ServiceVideoRecord serviceVideoRecord) { + PageServiceVedioRecordVO vo = new PageServiceVedioRecordVO(); + vo.setServiceId(serviceVideoRecord.getServiceId()); + vo.setVideoTime(serviceVideoRecord.getVideoTime()); + vo.setCreateDate(serviceVideoRecord.getCreateTime()); + vo.setVideoUrl(serviceVideoRecord.getVideoUrl()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/PageUserVideoVO.java b/open-api/src/main/java/com/iformall/vo/PageUserVideoVO.java new file mode 100644 index 0000000..111a769 --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/PageUserVideoVO.java @@ -0,0 +1,63 @@ +package com.iformall.vo; + +import com.iformall.domain.po.sm.UserMouldVideo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "分页查询用户视频返回数据") +@Data +public class PageUserVideoVO { + @ApiModelProperty("用户视频标识") + private Long id; + @ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + @ApiModelProperty(value="封面图",name="coverImg") + private String coverImg; + @ApiModelProperty(value="生成视频时间",name="createVideoDate") + private Date createVideoDate; + @ApiModelProperty(value="文案",name="paperwork") + private String paperwork; + @ApiModelProperty(value="名称",name="title") + private String title; + @ApiModelProperty(value="视频文件",name="videoId") + private String videoId; + @ApiModelProperty(value="生成视频信息",name="videoMsg") + private String videoMsg; + @ApiModelProperty(value="视频地址",name="videoPath") + private String videoPath; + @ApiModelProperty(value="播放地址",name="videoPlayUrl") + private String videoPlayUrl; + @ApiModelProperty(value="视频大小(byte)",name="videoSize") + private Long videoSize; + @ApiModelProperty("视频状态") + private Integer videoStatus; + @ApiModelProperty(value="视频时长(秒)",name="videoTime") + private String videoTime; + @ApiModelProperty("1:竖版,2:横版") + private Integer videoType; + + public static PageUserVideoVO mapping(UserMouldVideo userMouldVideo) { + PageUserVideoVO vo = new PageUserVideoVO(); + vo.setId(userMouldVideo.getId()); + vo.setCreateDate(userMouldVideo.getCreateDate()); + vo.setUpdateDate(userMouldVideo.getUpdateDate()); + vo.setCoverImg(userMouldVideo.getCoverImg()); + vo.setCreateVideoDate(userMouldVideo.getCreateVideoDate()); + vo.setPaperwork(userMouldVideo.getPaperwork()); + vo.setTitle(userMouldVideo.getTitle()); + vo.setVideoId(userMouldVideo.getVideoId()); + vo.setVideoMsg(userMouldVideo.getVideoMsg()); + vo.setVideoPath(userMouldVideo.getVideoPath()); + vo.setVideoPlayUrl(userMouldVideo.getVideoPlayUrl()); + vo.setVideoSize(userMouldVideo.getVideoSize()); + vo.setVideoStatus(userMouldVideo.getVideoStatus()); + vo.setVideoTime(userMouldVideo.getVideoTime()); + vo.setVideoType(userMouldVideo.getVideoType()); + return vo; + } +} diff --git a/open-api/src/main/java/com/iformall/vo/PageVO.java b/open-api/src/main/java/com/iformall/vo/PageVO.java new file mode 100644 index 0000000..c8b734c --- /dev/null +++ b/open-api/src/main/java/com/iformall/vo/PageVO.java @@ -0,0 +1,25 @@ +package com.iformall.vo; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.List; + +@Data +@ApiModel(value = "分页信息主体") +public class PageVO { + @ApiModelProperty(value = "总条数") + private long total; + @ApiModelProperty(value = "具体数据") + private List records; + + public PageVO(long total, List records) { + this.total = total; + this.records = records; + } + + public static PageVO build(long total, List records) { + return new PageVO(total, records); + } +} diff --git a/open-api/src/main/resources/application-dev.yml b/open-api/src/main/resources/application-dev.yml new file mode 100644 index 0000000..07ba499 --- /dev/null +++ b/open-api/src/main/resources/application-dev.yml @@ -0,0 +1,215 @@ +spring: + profiles: + #include: aliyunRocketMQ + include: rabbitMQ + # JDBC + datasource: + url: jdbc:mysql://182.92.151.30:3306/mallink_suimang_test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useUnicode=true&useSSL=false&useAffectedRows=true&allowMultiQueries=true + username: root + password: sm2023@ms + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver + filters: stat + maxActive: 20 + initialSize: 1 + maxWait: 60000 + minIdle: 1 + timeBetweenEvictionRunsMillis: 28000 + minEvictableIdleTimeMillis: 28000 + validationQuery: select 'x' + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + poolPreparedStatements: true + maxOpenPreparedStatements: 20 + connectionProperties: "druid.stat.mergeSql=true;druid.stat.slowSqlMillis=60000" + #jackson: + #date-format: yyyy-MM-dd HH:mm:ss + # REDIS + redis: + host: 101.200.130.134 + port: 6379 + password: iF0rm@2l2ol9 + timeout: 3600 + expire: 1800 #30分钟 + database: 5 + defaultExpiration: 2592000 # 默认生命周期30天 + jedis: + pool: + max-active: 100 + max-idle: 500 + max-wait: -1 + min-idle: 10 + + + aliyun: + sms: + accessKeyId: LTAI5tQs4MBjzLFbiQLjsMYy + accessKeySecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + product: Dysmsapi + domain: dysmsapi.aliyuncs.com + regionId: cn-hangzhou + dateFormat: yyyyMMdd + endpointName: cn-hangzhou + oss: + endpoint: oss-cn-beijing.aliyuncs.com + keyid: LTAI5tQs4MBjzLFbiQLjsMYy + keysecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + bucketname: suimang + filehost: admin + filedomain: https://suimang.oss-accelerate.aliyuncs.com + + # EMAIL + mail: + host: smtp.exmail.qq.com + username: zhengfangyuan@iformall.com + password: 2hSeppFRaw7KZZyf # 授权密码 + properties: + mail: + smtp: + auth: true + starttls: + enable: true + socketFactory: + port: 465 + class: javax.net.ssl.SSLSocketFactory + + # ROCKETMQ + rocketmq: + nameServer: 127.0.0.1:9876 + producer: + retry-times-when-send-async-failed: 0 + send-msg-timeout: 300000 + compress-msg-body-over-howmuch: 4096 + max-message-size: 4194304 + retry-another-broker-when-not-store-ok: false + retry-times-when-send-failed: 2 + # RABBITMQ + rabbitmq: + host: 127.0.0.1 + port: 5672 + username: fumao + password: f9l98 + publisher-confirms: true + publisher-returns: false + virtual-host: / + aliyunRocketmq: + accessKeyId: "LTAI4G7ixY4AhvM35F8o3W3V" + accessKeySecret: "VfWqGb83qIQrS9us45utskl8itd7ry" + groupId: "GID_P_1" + namesrvAddr: "http://MQ_INST_1796289517488555_Bcqaq2is.cn-beijing.mq-internal.aliyuncs.com:8080" + flyway: + enabled: false + +aws: + clientRegion: cn-northwest-1 + bucketName: iformall-net + access: ENC(3gx5ghDFBqGrEhO3Wf8aYmXsnwHO7Cj3HNKJGOeUj0o=) + secret: ENC(HVKIJwCJKVXLlUpGlQPwNqJOlnpxn4xYuy91SH0seTSm2uAttIQHvA49fXWWax90v5wloIk0QuU=) + +#wechat: +# web: +# appId: "wxe31beafbfd8295ba" +# secret: "c689fabf3c4c9f5b6424ff2a36a26727" +# url: "https://mall.youlane.cn" +# open: +# componentAppId: "wx897e4673286c915d" +# componentSecret: "cdfdfda65c45689beb6766c4c427eed2" +# componentToken: "formall2018" +# componentAesKey: "htKq8EjBMPNndfZQK9JiFojFaqFwFpw42VfeWFtx7HN" +# redis: +# host: 202.165.179.86 +# port: 6379 +# password: iF0rm@2l2ol9 +# timeout: 3600 +# expire: 1800 #30分钟 +# database: 2 +# defaultExpiration: 2592000 # 默认生命周期30天 +# jedis: +# pool: +# max-active: 100 +# max-idle: 500 +# max-wait: -1 +# min-idle: 10 + +wechat: + web: + appId: "wx091907dd0bfd3f6b" + secret: "2a2ca10738998b9ef92c1fe8a4d366a6" + url: "https://admintest.malls.iformall.com" + open: + componentAppId: wxdfc8fb4e62d6b52b + componentSecret: 98daa62b316dd6feabaad708327ce233 + componentToken: formall2018 + componentAesKey: htKq8EjBMPNndfZQK9JiFojFaqFwFpw42VfeWFtx7HN + redis: + host: 101.200.130.134 + port: 6379 + password: iF0rm@2l2ol9 + timeout: 3600 + expire: 1800 #30分钟 + database: 2 + defaultExpiration: 2592000 # 默认生命周期30天 + jedis: + pool: + max-active: 100 + max-idle: 100 + max-wait: -1 + min-idle: 10 + +alipay: + open: + appId: 2021002137663024 + appPrivateKey: MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCUfymV5J73QQMG52PVIGUbowkloYCO4B7TQoKbrTZf2YeYsg/To/o4PiXPMNwEUfEUU8NYQ6WwNhCd2fa1ei8WFXJUf3bfgswtBk1aOmHLeY9yoXFxIKMTQ9RcobnmBzKQZlaAPMTSr7t1QtKZKPuc2gEHGRFYKO/ZuL8gIpnsVidVtmi52yd7hzao/pI3ThLA0lreg4L3rYP5ESQZRytxIPgUQ4KI11pZxFgbe+uy28AGDYIQscSIb+SWOHPYKLvOEqqepIZ8M18w/U0lZzpzepzi/V/llekvXJ6UEf1lzl7x/4UIA3WPN1B40+NzbD/OxEGTuM0UctOG6ZTd4Te9AgMBAAECggEAPYksnHbvARspu/SrRCh2fatkIPn6Ijrxyy3mnch7neCw9i/jqxpqmF/4nxFqO0gRlRDZBHyT7p+Y5zDpsW5+kLI2fJmNkzXKkmXoLBnBaOZo8WHBdtXFfjg/iltig9Y7t+cQtXd5QK2eCwuz5dA75FXa0ywqKdRdAGY0nYZ5LpwrHVU8RXheUDCJyhKNj2+W6lIaSKDxLZU3laO1oBrv1agcy7Crd5E2ndb8O3Enga+z7wSz2h7A1BasC/Yl/Ro0Y21wLCH3s/R6qA0Paq12+WEF+xdodM7SrP43CCTVFGbC1TfEOdanJfixop8QuYsIp7pHrL925+vP4eY9RfckgQKBgQDQqLdpDzzU7Ot/L9Vc/r8d4iwXXbX8+HwVFV4oBuausgFyv8eJJpfrI+IlEoB1ubJcPpJBFqfmeYTW6/v6ioFljJAlWfFvesUVt/HszBMIOsU0Bzt7ex6WlwKOagb0q0ZPA4T0OY0K0lg0loaaaR8ZTr4ivDymaGBtTBYhslpc7QKBgQC2MBznGEc5r2dhyENvdPOR20PnXQcevGnPdqSus8m0VmDcHE72RVcckcZtwczsb3NaLSqmjAcWTn51/VFmlvhB3F34FcFTPZGq6sj7fWK8HuFq7l7mu5OzYuVr73zy9ggsUuaw10IqvvwIVxszNAF0hiRnSGH3z27CoRmz3s+8EQKBgQCK3o7atBJ3X4rIJiypbL4DhIB1uJ+jUjk6yvLUTut+fufp1+tTw0S+cS5UIAEw2Lr1G4u5F/v8rwmTBJG6SC4gSLGyui6uVBYRA1BWmedcxchzfRDAeMt9y9kesUAZ3Fe5xIzbAeZ1ulKMBVZmM+pHrJlsgr0Wv0bV1xqvqITtbQKBgBIsIGXopQoa9dvqBtfyOW1eCprkS5aEQqWf9vM6Ga90QjsSU8n6xqKh48IE57TZtQ7UnIF6TCasc66/MsRh4KdpHLJnMR5lcMc0nhF/wz5ychehaTPol+X3wlyOyc7OPah2KG6ROhdbb3ZBggQMduyxiKYIsUTvmuOtAAxR+DSRAoGADtuDzGQDOJYWiO2uuP6FpA5IJaiwlSfu3xncJVfhO8SVr6VBJFg88igbIB3w6nk/sv7j9VTXqXre9HMvp1flxaaLsdxM4HcTSALS9q6t/ajaveqte6S5kAtWx0WW8C6PtgWXHbxcD7LXARSsKLoEl2JXXyUVS/m2l/RzHBQ8GJI= + appPublicKeyCertPath: /opt/iformall/service/alipay/appCertPublicKey_2021002137663024.crt + alipayCertPath: /opt/iformall/service/alipay/alipayCertPublicKey_RSA2.crt + alipayRootCertPath: /opt/iformall/service/alipay/alipayRootCert.crt + callback: https://callbacktest.malls.iformall.com/api/alipay/notify/callback + +video: + aliyun: + accessKeyId: LTAI5tQs4MBjzLFbiQLjsMYy + accessKeySecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + regionId: cn-beijing + endPoint: https://oss-cn-beijing.aliyuncs.com + corePoolSize: 6 + maxPoolSize: 20 + queueCapacity: 1000 + namePrefix: aliyun-video-upload + + +jasypt: + encryptor: + password: oRqdnDbK5pj3eMmB + +fm: + exception: true + exception_emails: xuxiaohu@iformall.com + deploy: 1 + open: true + upload_dir: /home/test/server/uploads/ + ocr_data: /root/ocr_data/ + videoType: aliyun + +ueditor: + config: config.json + unified: true + upload-path: ./upload/ + url-prefix: "" + +logging: + level: + com.iformall: debug + path: ./logs/admin + +suimang: + oral_broadcasting: http://nas.pucao.cn:50014 + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://nas.pucao.cn:50015 + photo_speak_hy: http://nas.pucao.cn:50013 + digital_avatar: http://nas.pucao.cn:2005 + digital_avatar_hy: http://nas.pucao.cn:2003 + callbackUrl: https://mtest.metavatar.cc/C + local_deploy: false + token: fm2023 \ No newline at end of file diff --git a/open-api/src/main/resources/application-prod.yml b/open-api/src/main/resources/application-prod.yml new file mode 100644 index 0000000..e953109 --- /dev/null +++ b/open-api/src/main/resources/application-prod.yml @@ -0,0 +1,171 @@ +spring: + profiles: + include: aliyunRocketMQ + # JDBC + datasource: + url: jdbc:mysql://182.92.151.30:3306/mallink_suimang?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false&useAffectedRows=true&allowMultiQueries=true + username: root + password: sm2023@ms + type: com.alibaba.druid.pool.DruidDataSource + driver-class-name: com.mysql.cj.jdbc.Driver + filters: stat + maxActive: 200 + initialSize: 1 + maxWait: 60000 + minIdle: 1 + timeBetweenEvictionRunsMillis: 28000 + minEvictableIdleTimeMillis: 28000 + validationQuery: select 'x' + testWhileIdle: true + testOnBorrow: false + testOnReturn: false + poolPreparedStatements: true + maxOpenPreparedStatements: 20 + connectionProperties: "druid.stat.mergeSql=true;druid.stat.slowSqlMillis=60000" + # REDIS + redis: + host: 182.92.151.30 + port: 6379 + password: sm2023@rd + timeout: 3600 + expire: 1800 #30分钟 + database: 1 + defaultExpiration: 2592000 # 默认生命周期30天 + jedis: + pool: + max-active: 100 + max-idle: 20 + max-wait: -1 + min-idle: 0 + + # SMS + aliyun: + sms: + accessKeyId: LTAI5tQs4MBjzLFbiQLjsMYy + accessKeySecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + product: Dysmsapi + domain: dysmsapi.aliyuncs.com + regionId: cn-hangzhou + dateFormat: yyyyMMdd + endpointName: cn-hangzhou + oss: + endpoint: oss-cn-beijing.aliyuncs.com + keyid: LTAI5tQs4MBjzLFbiQLjsMYy + keysecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + bucketname: suimang + filehost: admin + filedomain: https://suimang.oss-accelerate.aliyuncs.com + # EMAIL + mail: + host: smtp.exmail.qq.com + username: system@metavatar.com.cn + password: 2bKGhFaKKjhQFeka # 授权密码 + properties: + mail: + smtp: + auth: true + starttls: + enable: true + socketFactory: + port: 465 + class: javax.net.ssl.SSLSocketFactory + # RABBITMQ + rabbitmq: + host: 127.0.0.1 + port: 5672 + username: ENC(lRmLd6EzgeY1RT5ktcHv9g==) + password: ENC(gBI8mCjr3OC0v57jcnSb660Ux7mW03K2oePgvohhg7w=) + publisher-confirms: true + publisher-returns: false + virtual-host: / + # + aliyunRocketmq: + accessKeyId: "LTAI4G7ixY4AhvM35F8o3W3V" + accessKeySecret: "VfWqGb83qIQrS9us45utskl8itd7ry" + groupId: "GID_P_1" + namesrvAddr: "http://MQ_INST_1796289517488555_Bcqaq2is.cn-beijing.mq-internal.aliyuncs.com:8080" + flyway: + enabled: false + +aws: + clientRegion: cn-northwest-1 + bucketName: iformall-net + access: ENC(a6SN1sZ1enNL49ypiOXkg/pPPAnZD8H4buQFTTKN08s=) + secret: ENC(5P5ff4bTMJUbXVR4ZsM03UHzOKZ4+Zg5Iutcdkyp/Quny/oXg+A4KpfwEyGarlLu3vQMJahGP5M=) + +wechat: + web: + appId: "wx9cc4ca09eb20fe03" + secret: "af1d7f7a1268022a73cb4ce0b9cf0985" + url: "https://admin.malls.iformall.com" + open: + componentAppId: ENC(b3JG0MUZgQfz5Zj+DC2ZM1zDeLOiGTmmeokfe2O8kaM=) + componentSecret: ENC(QVyc4BPGdnSjXGs2ivgpDBE1v8wPWHLLRMYI7Vv8uYwC0SiZHQz0QpyyQV/b48Pb) + componentToken: ENC(rkxj0733WxFFDLgA9x01m2s5Fi2L+0PC) + componentAesKey: ENC(EIbJUBpbYOrLb4YQ/HXLQmxlxgAqIp2ZmpnGICC8pu5xiTz3Cqfkbwd2S8raCcK/IvYcX2GmedI=) + redis: + host: 182.92.151.30 + port: 6379 + password: sm2023@rd + timeout: 3600 + expire: 1800 #30分钟 + database: 2 + defaultExpiration: 2592000 # 默认生命周期30天 + jedis: + pool: + max-active: 100 + max-idle: 100 + max-wait: -1 + min-idle: 10 + +alipay: + open: + appId: 2021002140616334 + appPrivateKey: MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCEJmHIlS0luIH7zJRRVlypCcgiSkqpSlnmgyCEM7nu8IerV8Yf7dMBitBklTpJB+4URV1bW+q6Ijzo8RsCyjm1Kx+EFiKf1PiJXlT0h1+bF3fYdDr6r5GK0/TtB8O80p774NcRD3HgbzUS8AEe/GcBvhiXbDRgJh7yAngW9vxl9u1o5UcaxOXVLWDrjlQGF6qyXUlycCNIdPXj3LduP3PBK5daVZwJm33Pr7kmSI0agZvV267HaTpSKaiXI7Zwo+nFMqx9g9kpzmYRfOgHx3DWpQUFI646IB8nEpLpQp3/0eDocuqiHXYgEpLpPoFKoVE228v74YSFh3Y4fFGX+qtjAgMBAAECggEAIJK9Y42xtSyHjaNdo7bf3CK3HAyn3pafFjyYFT4SxJyxNEDMay5Z5nVq7IAD/+BehMycOFqtvveVf+1+NO/XzZo1iH9URYVfRazkz+lWXYopVkdACm6gN1ILeymAy9g2q+s918ywyxteP668+ABK+5j5wsk/F7wNwKVvKGn0yMT7DP0FAL1e0KWndZCZlF79VnFpBLscDJq28GqRzqYop4CWqHHTA6DBvIqkfQV4U3IzqnzOsxNLEMBwhnbK08XfYZ3DxCPH0jQdA2Jj/aABrntq2EpWjzW5H9iZqrVo33rmsNHUSQvla/333RkbpwGyNhI6kcPBRq4cVSAa3y7dMQKBgQDVfyDUPWKXVwIJUgO1my8WIUu2p6nhuT7Mfnpk4X7ewdFaRVjb/r0KvhLgoz2/KOwkqtWTlEvNaCDDycpLXk+V5ZH833kYsDEmxY7ikOUjCcrfYJgT7P77//cZ4Kx8a5X45SiKAZT2GQv7BTtIfNhrfTUj6AQx/3MP3sa2QAWeNQKBgQCedWoF7t+qyck2hctqtTFC7fRkEk7RNJVph1ZOeTqOIAKhmhkwaOE3joxQ/VqHDy212YdW4hI0BWUzbEdMy0Idz2G3y9ERVD84hZehf5GGRdiSrY9EEQgHlcI6Qb8/AnDdpy1DlKUMwTYjVNzkDL3AzeWn61JS1XQaOzZBsJy2NwKBgFa+pJQXrOtYytcGn8M2Hlebh6vbS8cPAVkNOqWqiWXw0iMfcg9Q3XZz7C+hpAD7m5b6YnToGDSJTma+opck5qk88agRFJ7XV+Es+/VKcg9edzNzh9bwwFmbksbM5shW3kSWt3X7Vo73dkqzwXaeY0CpSuIf7zRxWkrkdVCvipjRAoGAMcJlPN+6VQNwsDJromKryXy31gT5wzBkCvN44sOm46KhsOWXK2CD+NJGtdgZaXgWvphEq7/qP3PCR9ekvDTH2lyZLwJN8Mcn4zPwXcKVjDi6vbTK3HEMuHUKvQiQadT2ZGRvDl3LRqoVuhqYEvT9UWJWz9hRzblB8ErPyukPDRkCgYB7bMv2iflpaGE1J3gkTlVJB+2QSfnAXaUDMLWsZN4gYjwEBVCEJ+mhWL1/GeEIBjSs5/qZIeRsYzlxGEcnsJzRfog6ITBF14AeZ+xNkHq83ja87OGVKMypiccGwRehijDhJi6tgMJ0u0w6PiqcJvh0SX4jBhDDPjuWzK2XD+lx8A== + appPublicKeyCertPath: /opt/iformall/service/alipay/appCertPublicKey_2021002140616334.crt + alipayCertPath: /opt/iformall/service/alipay/alipayCertPublicKey_RSA2.crt + alipayRootCertPath: /opt/iformall/service/alipay/alipayRootCert.crt + callback: https://callback.malls.iformall.com/api/alipay/notify/callback + +video: + aliyun: + accessKeyId: LTAI5tQs4MBjzLFbiQLjsMYy + accessKeySecret: nYmnexFJxrsBu0AGVIOSbUaSaweJu7 + regionId: cn-beijing + endPoint: https://oss-cn-beijing.aliyuncs.com + corePoolSize: 6 + maxPoolSize: 20 + queueCapacity: 1000 + namePrefix: aliyun-video-upload + +fm: + exception: true + exception_emails: houtaikaifa@iformall.com + deploy: 3 + open: true + upload_dir: /root/uploads/ + ocr_data: /root/ocr_data/ + videoType: aliyun + +ueditor: + config: config.json + unified: true + upload-path: ./upload/ + url-prefix: "" + +logging: + level: + com.iformall.mapper: debug + path: ./logs/admin + +suimang: + oral_broadcasting: http://111.198.0.15:22266 + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://111.198.0.15:22299 + photo_speak_hy: http://111.198.0.15:22288 + digital_avatar: http://111.198.0.15:22200 + digital_avatar_hy: http://*****:2003 + callbackUrl: https://neuver.metavatar.cc/C + local_deploy: false + token: fm2023 \ No newline at end of file diff --git a/open-api/src/main/resources/application.yml b/open-api/src/main/resources/application.yml new file mode 100644 index 0000000..a2243ed --- /dev/null +++ b/open-api/src/main/resources/application.yml @@ -0,0 +1,54 @@ +server: + port: 7070 + servlet: + context-path: /public + +spring: + application: + name: suimang + profiles: + active: dev + jackson: + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + default-property-inclusion: non_null +# rocketmq: +# nameServer: 127.0.0.1:9876 +# producer: +# retry-times-when-send-async-failed: 0 +# send-msg-timeout: 300000 +# compress-msg-body-over-howmuch: 4096 +# max-message-size: 4194304 +# retry-another-broker-when-not-store-ok: false +# retry-times-when-send-failed: 2 + +# MybatisPlus +mybatis-plus: + mapper-locations: classpath:mapper/*Mapper.xml + global-config: + db-config: + id-type: id_worker + field-strategy: not_null + db-type: mysql + configuration: + jdbc-type-for-null: 'null' + cache-enabled: false + call-setters-on-nulls: true + type-aliases-package: com.iformall.domain.po + type-enums-package: com.iformall.enums + +# PageHelper +pagehelper: + helperDialect: mysql + reasonable: false + supportMethodsArguments: true + params: count=countSql + offset-as-page-num: true + page-size-zero: true + row-bounds-with-count: true + +mapper: + mappers: + - com.iformall.common.CommonMapper + +version: @project.version@ \ No newline at end of file diff --git a/open-api/src/main/resources/logback-spring.xml b/open-api/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..3a54d11 --- /dev/null +++ b/open-api/src/main/resources/logback-spring.xml @@ -0,0 +1,100 @@ + + + + + + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] --%mdc{client}%msg%n + + + + + ${logPath}/trace.log + + ${logPath}/daily/trace.%d{yyyy-MM-dd}.log + 30 + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%logger:%line]--%mdc{client} %msg%n + + + + + ${logPath}/info.log + + ${logPath}/daily/info.%d{yyyy-MM-dd}.log + 30 + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%logger:%line]--%mdc{client} %msg%n + + + INFO + ACCEPT + DENY + + + + + ${logPath}/debug.log + + ${logPath}/daily/debug.%d{yyyy-MM-dd}.log + 30 + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%logger:%line]--%mdc{client} %msg%n + + + DEBUG + ACCEPT + DENY + + + + + + ${logPath}/warn.log + + ${logPath}/daily/warn.%d{yyyy-MM-dd}.log + 30 + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%logger:%line]--%mdc{client} %msg%n + + + WARN + ACCEPT + DENY + + + + + + + ${logPath}/error.log + + ${logPath}/daily/error.%d{yyyy-MM-dd}.log + 30 + + + [%date{yyyy-MM-dd HH:mm:ss.SSS}] [%-5level] [%logger:%line]--%mdc{client} %msg%n + + + ERROR + ACCEPT + DENY + + + + + + + + + + + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index ff7ed95..a6615de 100644 --- a/pom.xml +++ b/pom.xml @@ -20,6 +20,8 @@ suimangCApi suimangSchedule suimangMQConsumer + open-api + suimang-swagger @@ -185,21 +187,21 @@ - - io.springfox - springfox-swagger2 - 2.8.0 - - - io.springfox - springfox-swagger-ui - 2.8.0 - - - io.springfox - springfox-spring-web - 2.8.0 - + + + + + + + + + + + + + + + com.fasterxml.jackson.core jackson-core diff --git a/suimang-mybatis/.gitignore b/suimang-mybatis/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimang-mybatis/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimang-swagger/pom.xml b/suimang-swagger/pom.xml new file mode 100644 index 0000000..b4352b0 --- /dev/null +++ b/suimang-swagger/pom.xml @@ -0,0 +1,28 @@ + + + + suimang + com.iformall + 1.0 + + 4.0.0 + + suimang-swagger + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + com.github.xiaoymin + swagger-bootstrap-ui + 1.9.3 + + + \ No newline at end of file diff --git a/suimang-swagger/src/main/java/com/iformall/annotation/ApiVersion.java b/suimang-swagger/src/main/java/com/iformall/annotation/ApiVersion.java new file mode 100644 index 0000000..d9ceb4e --- /dev/null +++ b/suimang-swagger/src/main/java/com/iformall/annotation/ApiVersion.java @@ -0,0 +1,19 @@ +package com.iformall.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ApiVersion { + + /** + * 接口版本号(对应swagger中的group) + * + * @return String[] + */ + String[] group(); +} diff --git a/suimang-swagger/src/main/java/com/iformall/annotation/BaseEnableSwagger.java b/suimang-swagger/src/main/java/com/iformall/annotation/BaseEnableSwagger.java new file mode 100644 index 0000000..fb78b80 --- /dev/null +++ b/suimang-swagger/src/main/java/com/iformall/annotation/BaseEnableSwagger.java @@ -0,0 +1,14 @@ +package com.iformall.annotation; + +import com.iformall.config.SwaggerConfiguration; +import org.springframework.context.annotation.Import; + +import java.lang.annotation.*; + +@Target({ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@Inherited +@Import({SwaggerConfiguration.class}) +public @interface BaseEnableSwagger { +} diff --git a/suimang-swagger/src/main/java/com/iformall/config/SwaggerConfiguration.java b/suimang-swagger/src/main/java/com/iformall/config/SwaggerConfiguration.java new file mode 100644 index 0000000..7d83072 --- /dev/null +++ b/suimang-swagger/src/main/java/com/iformall/config/SwaggerConfiguration.java @@ -0,0 +1,94 @@ +package com.iformall.config; + +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.iformall.annotation.ApiVersion; +import com.iformall.constant.SwaggerConstant; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +import javax.servlet.ServletContext; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +@Configuration +@EnableSwagger2 +@EnableAutoConfiguration +@EnableConfigurationProperties(SwaggerProperties.class) +@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true) +public class SwaggerConfiguration { + + private static final List DEFAULT_EXCLUDE_PATH = Arrays.asList("/error"); + private static final String BASE_PATH = "/**"; + + @Autowired + private SwaggerProperties swaggerProperties; + + /** + * 1、分组 + * 2、切换分组,修改访问/v2/api-docs/ 接口的路径 + * https://admintest.malls.iformall.com/v2/api-docs/ + * https://admintest.malls.iformall.com/B/v2/api-docs/ + * + * @param servletContext + * @return {@link Docket} + */ + @Bean + public Docket docket(ServletContext servletContext) { + // base-path处理 + if (swaggerProperties.getBasePath().isEmpty()) { + swaggerProperties.getBasePath().add(BASE_PATH); + } + List> basePath = new ArrayList<>(swaggerProperties.getBasePath().size()); + swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path))); + + // exclude-path处理 + if (swaggerProperties.getExcludePath().isEmpty()) { + swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH); + } + List> excludePath = new ArrayList<>(); + swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path))); + + return new Docket(DocumentationType.SWAGGER_2) + .host(swaggerProperties.getHost()) + .apiInfo(apiInfo(swaggerProperties)).select() + .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) + .apis(input -> { + ApiVersion apiVersion = input.getHandlerMethod().getMethodAnnotation(ApiVersion.class); + return apiVersion != null && Arrays.asList(apiVersion.group()).contains(SwaggerConstant.V_1_0_0); + }) + .paths( + Predicates.and( + Predicates.not(Predicates.or(excludePath)), + Predicates.or(basePath) + ) + ) + .build(); + } + + private ApiInfo apiInfo(SwaggerProperties swaggerProperties) { + return new ApiInfoBuilder() + .title(swaggerProperties.getTitle()) + .description(swaggerProperties.getDescription()) + .license(swaggerProperties.getLicense()) + .licenseUrl(swaggerProperties.getLicenseUrl()) + .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) + .contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail())) + .version(swaggerProperties.getVersion()) + .build(); + } +} + diff --git a/suimang-swagger/src/main/java/com/iformall/config/SwaggerProperties.java b/suimang-swagger/src/main/java/com/iformall/config/SwaggerProperties.java new file mode 100644 index 0000000..b43bae8 --- /dev/null +++ b/suimang-swagger/src/main/java/com/iformall/config/SwaggerProperties.java @@ -0,0 +1,123 @@ +package com.iformall.config; + +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@Data +@ConfigurationProperties("swagger") +public class SwaggerProperties { + private Map services; + private String prePath; + /** + * 是否开启swagger + */ + private Boolean enabled; + /** + * swagger会解析的包路径 + **/ + private String basePackage = ""; + /** + * swagger会解析的url规则 + **/ + private List basePath = new ArrayList<>(); + /** + * 在basePath基础上需要排除的url规则 + **/ + private List excludePath = new ArrayList<>(); + /** + * 标题 + **/ + private String title = ""; + /** + * 描述 + **/ + private String description = ""; + /** + * 版本 + **/ + private String version = ""; + /** + * 许可证 + **/ + private String license = ""; + /** + * 许可证URL + **/ + private String licenseUrl = ""; + /** + * 服务条款URL + **/ + private String termsOfServiceUrl = ""; + + /** + * host信息 + **/ + private String host = ""; + /** + * 联系人信息 + */ + private Contact contact = new Contact(); + /** + * 全局统一鉴权配置 + **/ + private Authorization authorization = new Authorization(); + + @Data + public static class Contact { + /** + * 联系人 + **/ + private String name = ""; + /** + * 联系人url + **/ + private String url = ""; + /** + * 联系人email + **/ + private String email = ""; + } + + @Data + @NoArgsConstructor + public static class Authorization { + + /** + * 鉴权策略ID,需要和SecurityReferences ID保持一致 + */ + private String name = ""; + + /** + * 需要开启鉴权URL的正则 + */ + private String authRegex = "^.*$"; + + /** + * 鉴权作用域列表 + */ + private List authorizationScopeList = new ArrayList<>(); + + private List tokenUrlList = new ArrayList<>(); + } + + @Data + @NoArgsConstructor + public static class AuthorizationScope { + + /** + * 作用域名称 + */ + private String scope = ""; + + /** + * 作用域描述 + */ + private String description = ""; + + } +} diff --git a/suimang-swagger/src/main/java/com/iformall/constant/SwaggerConstant.java b/suimang-swagger/src/main/java/com/iformall/constant/SwaggerConstant.java new file mode 100644 index 0000000..db4158c --- /dev/null +++ b/suimang-swagger/src/main/java/com/iformall/constant/SwaggerConstant.java @@ -0,0 +1,8 @@ +package com.iformall.constant; + +public interface SwaggerConstant { + /** + * + */ + String V_1_0_0 = "v1.0.0"; +} diff --git a/suimang.iml b/suimang.iml index bb300b6..c7b2669 100644 --- a/suimang.iml +++ b/suimang.iml @@ -25,6 +25,7 @@ + @@ -161,7 +162,7 @@ - + @@ -184,21 +185,6 @@ - - - - - - - - - - - - - - - @@ -239,6 +225,7 @@ + diff --git a/suimangAdmin/.gitignore b/suimangAdmin/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangAdmin/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangAdmin/src/main/java/com/iformall/AdminApplication.java b/suimangAdmin/src/main/java/com/iformall/AdminApplication.java index 0284ebf..cfc34ca 100644 --- a/suimangAdmin/src/main/java/com/iformall/AdminApplication.java +++ b/suimangAdmin/src/main/java/com/iformall/AdminApplication.java @@ -1,5 +1,6 @@ package com.iformall; +import com.iformall.annotation.BaseEnableSwagger; import com.ulisesbocchio.jasyptspringboot.annotation.EnableEncryptableProperties; import org.mybatis.spring.annotation.MapperScan; import org.rocketmq.starter.annotation.EnableRocketMQ; @@ -18,7 +19,7 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; */ @SpringBootApplication @MapperScan(basePackages = {"com.iformall.mapper"}) -@EnableSwagger2 +@BaseEnableSwagger @EnableEncryptableProperties @EnableAsync @EnableRocketMQ diff --git a/suimangAdmin/src/main/java/com/iformall/config/MyAuthenticationToken.java b/suimangAdmin/src/main/java/com/iformall/config/MyAuthenticationToken.java new file mode 100644 index 0000000..49a55f1 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/config/MyAuthenticationToken.java @@ -0,0 +1,55 @@ +package com.iformall.config; + +import org.apache.shiro.authc.AuthenticationToken; + +public class MyAuthenticationToken implements AuthenticationToken{ + + private Integer projectType; + private String username; + private char[] password; + + public Integer getProjectType() { + return projectType; + } + + public void setProjectType(Integer projectType) { + this.projectType = projectType; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public char[] getPassword() { + return password; + } + + public void setPassword(char[] password) { + this.password = password; + } + + @Override + public Object getPrincipal() { + return getUsername(); + } + + @Override + public Object getCredentials() { + return getPassword(); + } + + public MyAuthenticationToken() { + + } + + public MyAuthenticationToken(Integer projectType, String username, char[] password) { + this.projectType = projectType; + this.username = username; + this.password = password; + } + +} diff --git a/suimangAdmin/src/main/java/com/iformall/config/ShiroConfig.java b/suimangAdmin/src/main/java/com/iformall/config/ShiroConfig.java index 75223d8..89b38cb 100644 --- a/suimangAdmin/src/main/java/com/iformall/config/ShiroConfig.java +++ b/suimangAdmin/src/main/java/com/iformall/config/ShiroConfig.java @@ -139,6 +139,7 @@ public class ShiroConfig { // } // swagger-ui filterChainDefinitionMap.put("/swagger-ui.html", "anon"); + filterChainDefinitionMap.put("/doc.html", "anon"); filterChainDefinitionMap.put("/v2/**", "anon"); filterChainDefinitionMap.put("/swagger-resources/**", "anon"); filterChainDefinitionMap.put("/webjars/**", "anon"); @@ -149,8 +150,8 @@ public class ShiroConfig { //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了 filterChainDefinitionMap.put("/logout", "authc"); -// filterChainDefinitionMap.put("/**", "corsFilter,token,authc"); - filterChainDefinitionMap.put("/**", "anon"); + filterChainDefinitionMap.put("/**", "corsFilter,token,authc"); +// filterChainDefinitionMap.put("/**", "anon"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); diff --git a/suimangAdmin/src/main/java/com/iformall/config/Swagger2Config.java b/suimangAdmin/src/main/java/com/iformall/config/Swagger2Config.java index 335b86b..fc80b3b 100644 --- a/suimangAdmin/src/main/java/com/iformall/config/Swagger2Config.java +++ b/suimangAdmin/src/main/java/com/iformall/config/Swagger2Config.java @@ -1,61 +1,61 @@ -package com.iformall.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.ParameterBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.schema.ModelRef; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Parameter; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.paths.RelativePathProvider; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import javax.servlet.ServletContext; -import java.util.ArrayList; -import java.util.List; - -//参考:http://blog.csdn.net/catoop/article/details/50668896 -@Configuration -@EnableSwagger2 -public class Swagger2Config { - - @Autowired - private ServletContext servletContext; - - @Bean - public Docket createRestApi() { - ParameterBuilder tokenPar = new ParameterBuilder(); - List pars = new ArrayList(); - //增加一个request的header参数 - tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); - pars.add(tokenPar.build()); - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.iformall.controller")) - .paths(PathSelectors.any()) - .build() - .globalOperationParameters(pars) - .pathProvider(new RelativePathProvider(servletContext) { - @Override - public String getApplicationBasePath() { - return "/api"; - } - }); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("a端 api") - .description("a api") - .termsOfServiceUrl("http://localhost:7000") - .version("2.0") - .build(); - } - -} \ No newline at end of file +//package com.iformall.config; +// +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import springfox.documentation.builders.ApiInfoBuilder; +//import springfox.documentation.builders.ParameterBuilder; +//import springfox.documentation.builders.PathSelectors; +//import springfox.documentation.builders.RequestHandlerSelectors; +//import springfox.documentation.schema.ModelRef; +//import springfox.documentation.service.ApiInfo; +//import springfox.documentation.service.Parameter; +//import springfox.documentation.spi.DocumentationType; +//import springfox.documentation.spring.web.paths.RelativePathProvider; +//import springfox.documentation.spring.web.plugins.Docket; +//import springfox.documentation.swagger2.annotations.EnableSwagger2; +// +//import javax.servlet.ServletContext; +//import java.util.ArrayList; +//import java.util.List; +// +////参考:http://blog.csdn.net/catoop/article/details/50668896 +//@Configuration +//@EnableSwagger2 +//public class Swagger2Config { +// +// @Autowired +// private ServletContext servletContext; +// +// @Bean +// public Docket createRestApi() { +// ParameterBuilder tokenPar = new ParameterBuilder(); +// List pars = new ArrayList(); +// //增加一个request的header参数 +// tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); +// pars.add(tokenPar.build()); +// return new Docket(DocumentationType.SWAGGER_2) +// .apiInfo(apiInfo()) +// .select() +// .apis(RequestHandlerSelectors.basePackage("com.iformall.controller")) +// .paths(PathSelectors.any()) +// .build() +// .globalOperationParameters(pars) +// .pathProvider(new RelativePathProvider(servletContext) { +// @Override +// public String getApplicationBasePath() { +// return "/api"; +// } +// }); +// } +// +// private ApiInfo apiInfo() { +// return new ApiInfoBuilder() +// .title("a端 api") +// .description("a api") +// .termsOfServiceUrl("http://localhost:7000") +// .version("2.0") +// .build(); +// } +// +//} \ No newline at end of file diff --git a/suimangAdmin/src/main/java/com/iformall/config/WebConfig.java b/suimangAdmin/src/main/java/com/iformall/config/WebConfig.java index d4e0620..7064277 100644 --- a/suimangAdmin/src/main/java/com/iformall/config/WebConfig.java +++ b/suimangAdmin/src/main/java/com/iformall/config/WebConfig.java @@ -100,7 +100,9 @@ public class WebConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html") +// registry.addResourceHandler("swagger-ui.html") +// .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); diff --git a/suimangAdmin/src/main/java/com/iformall/controller/base/BaseController.java b/suimangAdmin/src/main/java/com/iformall/controller/base/BaseController.java index 9c7937a..f607020 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/base/BaseController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/base/BaseController.java @@ -48,10 +48,9 @@ public class BaseController { public MallUserInfo getUser(){ MallUserInfo user = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); // MallUserInfo user = new MallUserInfo(); -// user.setId(463627091581734912L); -// user.setName("富茂光谷测试版管理员"); -// user.setTenantId("1025"); -// user.setParentTenantId("1024"); +// user.setId(2L); +// user.setName("localtest"); +// user.setIsAdmin(1); return user; } diff --git a/suimangAdmin/src/main/java/com/iformall/controller/basic/WxProjectConfigController.java b/suimangAdmin/src/main/java/com/iformall/controller/basic/WxProjectConfigController.java index 8b87e0b..c6fa3e5 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/basic/WxProjectConfigController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/basic/WxProjectConfigController.java @@ -426,10 +426,10 @@ public class WxProjectConfigController extends BaseController { } boolean bChangedPhone = false; if(userInfo.getId() == null){ - if(userInfoService.cntByUserName(userInfo.getUsername()) > 0){ + if(userInfoService.cntByUserName(userInfo.getUsername(),EnumProject.PROJECT_2.getCode()) > 0){ return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); } - if(userInfoService.cntByUserPhone(userInfo.getPhone()) > 0){ + if(userInfoService.cntByUserPhone(userInfo.getPhone(),EnumProject.PROJECT_2.getCode()) > 0){ return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); } Assert.notNull(userInfo.getPassword(), "密码不能为空"); @@ -442,12 +442,12 @@ public class WxProjectConfigController extends BaseController { }else{ MallUserInfo oldUser = userInfoService.getById(userInfo.getId()); if (!oldUser.getUsername().equals(userInfo.getUsername())) { - if(userInfoService.cntByUserName(userInfo.getUsername()) > 0){ + if(userInfoService.cntByUserName(userInfo.getUsername(),EnumProject.PROJECT_2.getCode()) > 0){ return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); } } if (!oldUser.getPhone().equals(userInfo.getPhone())) { - if(userInfoService.cntByUserPhone(userInfo.getPhone()) > 0){ + if(userInfoService.cntByUserPhone(userInfo.getPhone(),EnumProject.PROJECT_2.getCode()) > 0){ return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); } bChangedPhone = true; @@ -814,76 +814,6 @@ public class WxProjectConfigController extends BaseController { } } - @ApiOperation("获取抖音支付2.0 回调接口配置") - @GetMapping("/ttcallback/query/settings") - @SystemControllerLog(description = "") - @TenantIgnore - public ResultData ttcallbackQuerySettings(String appid) { - logger.debug("[" + getIpAddr() + "] WxProjectConfigController::ttcallbackQuerySettings"); - try { - WxAppinfo appinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appid); - if(appinfo == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未找到对应的小程序"); - } - if(!EnumAppPlat.TOUTIAO.getCode().equals(appinfo.getPlat()) - || !EnumAppType.C.getCode().equals(appinfo.getType())){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"该小程序不支持"); - } - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - if(payAccount == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未找到对应的支付数据"); - } - TtPayService ttPayService = maUtil.getTtPayService(appinfo, payAccount); - CallBackSettingsRequest callBackSettingsRequest = ttPayService.querySettings(); - return new ResultData(callBackSettingsRequest); - }catch (Exception e){ - logger.error(e.getMessage(),e); - return new ResultData(ErrorCode.SYS_SERVER_ERROR); - } - } - @ApiOperation("配置抖音支付2.0 回调接口") - @PostMapping("/ttcallback/settings") - @SystemControllerLog(description = "商场集团-更新") - @TenantIgnore - public ResultData ttcallbackSettings(@RequestBody Map map) { - logger.debug("[" + getIpAddr() + "] WxProjectConfigController::ttcallbackSettings"); - String appid = map.get("appid"); - String create_order_callback = map.get("createOrderCallback"); - String refund_callback = map.get("refundCallback"); - String delivery_qrcode_redirect = map.get("deliveryQrcodeRedirect"); - if(StringUtils.isBlank(appid) || StringUtils.isBlank(create_order_callback) - || StringUtils.isBlank(refund_callback)){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL); - } - try { - WxAppinfo appinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appid); - if(appinfo == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未找到对应的小程序"); - } - if(!EnumAppPlat.TOUTIAO.getCode().equals(appinfo.getPlat()) - || !EnumAppType.C.getCode().equals(appinfo.getType())){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"该小程序不支持"); - } - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - if(payAccount == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未找到对应的支付数据"); - } - TtPayService ttPayService = maUtil.getTtPayService(appinfo, payAccount); - CallBackSettingsRequest request = new CallBackSettingsRequest(); - request.setCreateOrderCallback(create_order_callback); - request.setRefundCallback(refund_callback); - request.setDeliveryQrcodeRedirect(delivery_qrcode_redirect); - boolean b = ttPayService.callbackSettings(request); - if(b){ - return new ResultData(); - }else{ - return new ResultData(ErrorCode.SYS_SERVER_ERROR); - } - }catch (Exception e){ - logger.error(e.getMessage(),e); - return new ResultData(ErrorCode.SYS_SERVER_ERROR); - } - } } diff --git a/suimangAdmin/src/main/java/com/iformall/controller/mem/WxCUserBasicInfoController.java b/suimangAdmin/src/main/java/com/iformall/controller/mem/WxCUserBasicInfoController.java index 36e7f14..f22555e 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/mem/WxCUserBasicInfoController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/mem/WxCUserBasicInfoController.java @@ -179,10 +179,10 @@ public class WxCUserBasicInfoController extends BaseController { @ApiOperation("分页列表接口") @GetMapping("list") @ApiImplicitParams({ - @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), - @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + @ApiImplicitParam(name = "PageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "PageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) @SystemControllerLog(description = "会员管理-列表") - public ResultData list(@ModelAttribute WxCUserBasicInfo wxCUserBasicInfo, Integer pageNum, Integer pageSize) { + public ResultData list(@ModelAttribute WxCUserBasicInfo wxCUserBasicInfo, Integer PageNum, Integer PageSize) { logger.debug("[" + getIpAddr() + "] WxCUserBasicInfoController::list"); if (null == wxCUserBasicInfo) { wxCUserBasicInfo = new WxCUserBasicInfo(); @@ -198,7 +198,7 @@ public class WxCUserBasicInfoController extends BaseController { } } wxCUserBasicInfo.setSortColumns(BaseEntity.SortField.wcubiActiveTime_DESC); - PageInfo page = wxCUserBasicInfoService.listAsPage(wxCUserBasicInfo, pageNum, pageSize); + PageInfo page = wxCUserBasicInfoService.listAsPage(wxCUserBasicInfo, PageNum, PageSize); if (page.getSize() > 0) { for (WxCUserBasicInfo info : page.getList()) { diff --git a/suimangAdmin/src/main/java/com/iformall/controller/msg/WxMsgValidationcodeController.java b/suimangAdmin/src/main/java/com/iformall/controller/msg/WxMsgValidationcodeController.java index 5a9d1d7..afb430a 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/msg/WxMsgValidationcodeController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/msg/WxMsgValidationcodeController.java @@ -7,6 +7,7 @@ import com.iformall.common.ResultData; import com.iformall.controller.base.BaseController; import com.iformall.domain.po.WxMsgValidationcode; import com.iformall.domain.po.base.TenantEntity; +import com.iformall.enums.EnumProject; import com.iformall.service.WxMsgValidationcodeService; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -87,7 +88,7 @@ public class WxMsgValidationcodeController extends BaseController { wxMsgValidationcode.setParentTenantId(parentTenantId); wxMsgValidationcode.setPhone(phone); wxMsgValidationcode.setType(type); - return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode); + return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode,EnumProject.PROJECT_2.getCode()); } @GetMapping("hasvalidationcode") diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiGuideController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiGuideController.java new file mode 100644 index 0000000..72fdb67 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiGuideController.java @@ -0,0 +1,47 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.domain.dto.sm.SaveApiGuideDTO; +import com.iformall.domain.dto.sm.UpdateApiGuideDTO; +import com.iformall.domain.po.sm.ApiGuide; +import com.iformall.service.sm.ApiGuideService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/apiGuide") +@Api(tags = "api指南接口") +public class ApiGuideController { + + @Autowired + private ApiGuideService apiGuideService; + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("分页查询api指南") + @GetMapping("/page") + public R> pageApiGuide(ApiGuide apiGuide, Integer pageNum, Integer pageSize) { + return R.ok(apiGuideService.pageApiGuide(apiGuide, pageNum, pageSize)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("新增api指南") + @PostMapping("/save") + public R saveApiGuide(@RequestBody SaveApiGuideDTO dto) { + apiGuideService.saveApiGuide(dto); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("修改api指南") + @PostMapping("/update") + public R updateApiGuide(@RequestBody UpdateApiGuideDTO dto) { + apiGuideService.updateApiGuide(dto); + return R.ok(); + } +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiMenuController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiMenuController.java new file mode 100644 index 0000000..b990f18 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/ApiMenuController.java @@ -0,0 +1,68 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; +import com.iformall.common.ErrorCode; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.domain.dto.sm.SaveApiMenuDTO; +import com.iformall.domain.dto.sm.UpdateApiMenuDTO; +import com.iformall.domain.po.sm.ApiMenu; +import com.iformall.exception.BizException; +import com.iformall.service.sm.ApiMenuService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/apiMenu") +@Api(tags = "api菜单接口") +public class ApiMenuController { + + @Autowired + private ApiMenuService apiMenuService; + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("分页查询api菜单") + @GetMapping("/page") + public R> pageApiMenu(ApiMenu ApiMenu, Integer pageNum, Integer pageSize) { + return R.ok(apiMenuService.pageApiMenu(ApiMenu, pageNum, pageSize)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询api菜单") + @GetMapping("/get") + public R getApiMenu(Long id) { + if (id == null) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + return R.ok(apiMenuService.getApiMenu(id)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("新增api菜单") + @PostMapping("/save") + public R saveApiMenu(@RequestBody SaveApiMenuDTO dto) { + apiMenuService.saveApiMenu(dto); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("修改api菜单") + @PostMapping("/update") + public R updateApiMenu(@RequestBody UpdateApiMenuDTO dto) { + apiMenuService.updateApiMenu(dto); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("全查询父级api菜单") + @GetMapping("/listParentMenu") + public R> listParentMenu() { + return R.ok(apiMenuService.listParentMenu()); + } +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/PersonMouldController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/PersonMouldController.java new file mode 100644 index 0000000..39fa21d --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/PersonMouldController.java @@ -0,0 +1,170 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.controller.base.BaseController; +import com.iformall.domain.po.MallUserInfo; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServicePersonMould; +import com.iformall.domain.po.sm.UserPersonMould; +import com.iformall.enums.EnumaMouldPatchStatus; +import com.iformall.exception.BizException; +import com.iformall.service.WxCUserBasicInfoService; +import com.iformall.service.sm.PersonMouldService; +import com.iformall.service.sm.ServiceInfoService; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; + +import java.util.ArrayList; +import java.util.List; + +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.*; + + +@RestController +@RequestMapping("/personMould") +@Api(description = "模板接口") +public class PersonMouldController extends BaseController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private PersonMouldService personMouldService; + + @Autowired + private ServiceInfoService serviceInfoService; + + @Autowired + private WxCUserBasicInfoService wxCUserBasicInfoService; + + @ApiOperation("分页列表接口") + @GetMapping("alList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData list(@ModelAttribute PersonMould record, Integer pageNum, Integer pageSize) { + if (record == null) record = new PersonMould(); + if(record.getVideoType() != null && record.getVideoType().intValue() == -1){ + record.setVideoType(null); + } + if(record.getSex() != null && record.getSex().intValue() == -1){ + record.setSex(null); + } + record.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + final PageInfo page = personMouldService.listAsPage(record, pageNum, pageSize); + return new ResultData(page); + } + + @ApiOperation("接入商分页列表接口") + @GetMapping("serviceMouldList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData serviceMouldList(@ModelAttribute PersonMould record, Integer pageNum, Integer pageSize) { + MallUserInfo user = this.getUser(); + ServiceInfo si = serviceInfoService.getServiceInfoByMallUserInfo(user.getId()); + if (null == si) { + return new ResultData(); + } + List mouldIds = personMouldService.getServiceMouldIds(si.getId()); + if (null == mouldIds || mouldIds.size() <= 0 ) { + return new ResultData(); + } + PersonMould pm = new PersonMould(); + pm.setIds(mouldIds); + if(record.getVideoType() != null && record.getVideoType().intValue() == -1){ + pm.setVideoType(null); + } + if(record.getSex() != null && record.getSex().intValue() == -1){ + pm.setSex(null); + } + pm.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + pm.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + final PageInfo page = personMouldService.listAsPage(pm, pageNum, pageSize); + return new ResultData(page); + } + + @ApiOperation("用户分页列表接口") + @GetMapping("userMouldList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "PageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "PageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData userMouldList(@ModelAttribute PersonMould record, Integer PageNum, Integer PageSize) { + if (null == record) { + record = new PersonMould(); + } + if (StringUtils.isNotBlank(record.getPhone())) { + List cUserIds = wxCUserBasicInfoService.findIdsListByPhone(null, record.getPhone()); + if (null == cUserIds || cUserIds.size() <= 0 ) { + record.setId(-1L); + }else { + List mids = personMouldService.getUserMouldIds(cUserIds); + if (null == mids || mids.size() <= 0 ) { + record.setId(-1L); + }else { + record.setIds(mids); + } + } + } + + if(record.getVideoType() != null && record.getVideoType().intValue() == -1){ + record.setVideoType(null); + } + if(record.getSex() != null && record.getSex().intValue() == -1){ + record.setSex(null); + } + record.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + final PageInfo page = personMouldService.listAsPage(record, PageNum, PageSize); + if (null != page && null != page.getList() && page.getList().size() > 0 ) { + for (int i = 0 ; i < page.getList().size(); i++) { + PersonMould pm = page.getList().get(i); + List cuserIds = personMouldService.getCUserIds(pm.getId()); + if (null != cuserIds && cuserIds.size() > 0) { + WxCUserBasicInfo u = new WxCUserBasicInfo(); + u.setIds(cuserIds); + pm.setWxCUserBasicInfoList(wxCUserBasicInfoService.findList(u)); + } + } + } + return new ResultData(page); + } + + @ApiOperation("用户模板编码分页列表接口") + @GetMapping("userPersonMouldIdList") + public ResultData userPersonMouldIdList(Long cUserId) { + if (null == cUserId) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),cUserId+"不为空"); + } + List uids = new ArrayList(); + uids.add(cUserId); + List mouldIds = personMouldService.getUserMouldIds(uids); + return new ResultData(mouldIds); + } + + @ApiOperation("设置用户关联模板") + @PostMapping("/associatedUserMoulds") + public ResultData associatedUserMoulds(@RequestBody UserPersonMould spm) { + if (null == spm.getMouldIds() || spm.getMouldIds().size() <= 0 ) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"请选择模板"); + } + + if (null == spm.getUserId() ) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"请选择用户"); + } + personMouldService.associatedUserMoulds(spm.getMouldIds(), spm.getUserId()); + return new ResultData(); + } +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/ProductOrderController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/ProductOrderController.java new file mode 100644 index 0000000..6318ceb --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/ProductOrderController.java @@ -0,0 +1,175 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.ResultData; +import com.iformall.controller.base.BaseController; +import com.iformall.domain.po.*; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.enums.*; +import com.iformall.service.*; +import com.iformall.service.pay.PayServiceFactory; +import com.iformall.service.pay.service.pay.PayAdapterService; +import com.iformall.utils.DateUtils; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; + +import java.util.List; + +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.*; + + +@RestController +@RequestMapping("/productOrder") +@Api(description = "模板接口") +public class ProductOrderController extends BaseController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private ProductOrderService productOrderService; + + @Autowired + private WxCUserBasicInfoService wxCUserBasicInfoService; + + + @ApiOperation("根据id查询接口") + @GetMapping("/paiedOrders") + @ApiImplicitParams({ + @ApiImplicitParam(name = "projectType", value = "projectType", dataType = "String", paramType = "query", required = true), + @ApiImplicitParam(name = "PageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "PageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData myPaiedOrders(@ModelAttribute ProductOrder record,Integer PageNum,Integer PageSize) { + if(record.getProjectType() == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_TYPE_ERROR.getCode(),"projectType参数错误"); + } + EnumProject projectTypeEnum = EnumProject.getEnum(record.getProjectType()); + if(projectTypeEnum == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_TYPE_ERROR.getCode(),"projectType参数错误"); + } + + if (StringUtils.isNotBlank(record.getPhone())) { + List cUserIds = wxCUserBasicInfoService.findIdsListByPhone(null, record.getPhone()); + if (null == cUserIds || cUserIds.size() <= 0 ) { + record.setId(-1L); + }else { + record.setCUserIds(cUserIds); + } + } + record.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode()); + PageInfo page =productOrderService.listAsPage(record, PageNum, PageSize); + if (null != page && null != page.getList() && page.getList().size() > 0 ) { + for (int i = 0 ; i < page.getList().size(); i++) { + ProductOrder pm = page.getList().get(i); + pm.setCUserInfo(wxCUserBasicInfoService.getById(pm.getUserId())); + } + } + return new ResultData(page); + } + + +// @AuthIgnore +// @ApiOperation(value = "获取详情链接", notes = "") +// @PostMapping("getPayUrl") +// public ResultData getPayUrl(@RequestBody ProductOrder record) { +// logger.debug("[" + getIpAddr() + "] ProductOrderController::getPayUrl"); +// if(StringUtils.isBlank(record.getAppId())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); +// } +// WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(record.getAppId()); +// if(wxAppinfo == null){ +// return new ResultData(ErrorCode.APP_ID_NOT_FOUND); +// } +// +// if(record.getUserId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); +// } +// WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); +// if(basicUser == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); +// } +// +// if(record.getProductId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); +// } +// Product product = productService.getById(record.getProductId()); +// if(product == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); +// } +// +// if(!wxAppinfo.getProjectType().equals(product.getProjectType())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"商品数据异常"); +// } +// +// try { +// EnumProject project = EnumProject.getEnum(wxAppinfo.getProjectType()); +// EnumAppPlat plat = EnumAppPlat.getByCode(wxAppinfo.getPlat()); +// String productScheme = Constant.mainPageUrl; +// String sceneParam = "t:dt_p:"+record.getProductId()+"_u:"+record.getUserId(); +// Date timeAfterDays = DateUtils.getTimeAfterDays(1, new Date()); +// Long expireTime = timeAfterDays.getTime()/1000; +// return schemeService.generateScheme(project,plat,productScheme,sceneParam,expireTime); +// } catch (MallinkException e) { +// return new ResultData(e.getErrorCode(), e.getMessage()); +// }catch (Exception e) { +// this.logger.error(e.getMessage(), e); +// return new ResultData(ErrorCode.SYS_SERVER_ERROR); +// } +// } + + +// @AuthIgnore +// @ApiOperation(value = "创建支付(不验证用户)", notes = "") +// @PostMapping("pay") +// public ResultData pay(@RequestBody ProductOrder record) { +// logger.debug("[" + getIpAddr() + "] ProductOrderController::pay"); +// if(record.getPayVendor() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式为空"); +// } +// EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.getEnum(record.getPayVendor()); +// if(payVendorEnum == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式参数错误"); +// } +// +// if(EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode().equals(record.getPayVendor())){ +// if(StringUtils.isBlank(record.getOpenId())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"openId为空"); +// } +// } +//// record.setProfitSharing(payVendorEnum.getProfitSharing()); +// +// if(record.getUserId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); +// } +// WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); +// if(basicUser == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); +// } +// +// if(record.getProductId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); +// } +// Product product = productService.getById(record.getProductId()); +// if(product == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); +// } +// +// record.setProductTitle(product.getTitle()); +// record.setProductEnTitle(product.getEnTitle()); +// record.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); +// record.setProjectType(product.getProjectType()); +// record.setOrderPrice(product.getSellPriceRmb()); +// productOrderService.saveOrUpdate(record); +// +// return productOrderService.createPay(record); +// } + + +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/ServiceInfoController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/ServiceInfoController.java new file mode 100644 index 0000000..3201a37 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/ServiceInfoController.java @@ -0,0 +1,265 @@ +package com.iformall.controller.sm; + +import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils; +import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; +import com.iformall.common.ErrorCode; +import com.iformall.common.R; +import com.iformall.common.Result; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.controller.base.BaseController; +import com.iformall.controller.sys.mallUserInfo.MallUserInfoBaseController; +import com.iformall.domain.dto.sm.SaveServiceInfoDTO; +import com.iformall.domain.dto.sm.UpdateServiceInfoDTO; +import com.iformall.domain.dto.sm.UpdateServiceInfoStatusDTO; +import com.iformall.domain.po.MallUserInfo; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServicePersonMould; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import com.iformall.enums.EnumProject; +import com.iformall.enums.EnumUserAdmin; +import com.iformall.enums.EnumYesOrNo; +import com.iformall.enums.EnumaMouldPatchStatus; +import com.iformall.exception.BizException; +import com.iformall.service.MallUserInfoService; +import com.iformall.service.sm.PersonMouldService; +import com.iformall.service.sm.ServiceInfoService; +import com.iformall.service.sm.ServiceVideoRecordService; +import com.iformall.sm.AiVideoHelper; +import com.iformall.smsdk.SmSdkUtils; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/serviceInfo") +@Api(tags = "合作商接口") +public class ServiceInfoController extends MallUserInfoBaseController{ + + @Autowired + private ServiceInfoService serviceInfoService; + + @Autowired + private MallUserInfoService mallUserInfoService; + + @Autowired + private PersonMouldService personMouldService; + + @Autowired + private ServiceVideoRecordService serviceVideoRecordService; + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("分页查询合作商") + @GetMapping("/page") + public R> pageServiceInfo(ServiceInfo serviceInfo, Integer pageNum, Integer pageSize) { + return R.ok(serviceInfoService.pageServiceInfo(serviceInfo, pageNum, pageSize)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询合作商") + @GetMapping("/get") + public R getServiceInfo(Long id) { + if (id == null) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + return R.ok(serviceInfoService.getServiceInfo(id)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("新增合作商(同步生成密钥)") + @PostMapping("/save") + public R saveServiceInfo(@RequestBody SaveServiceInfoDTO dto) { + serviceInfoService.saveServiceInfo(dto); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("慧影-设置登录账号") + @PostMapping("/saveMallUserInfo") + public R saveMallUserInfo(@RequestBody MallUserInfo dto) { + if (null == dto.getServiceId()) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"serviceId无效"); + } + dto.setUsername(StringUtils.trimToNull(dto.getUsername())); + if (StringUtils.isBlank(dto.getUsername()) || dto.getUsername().length() < 6) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"账号必须大于6位"); + } + + ServiceInfo si = serviceInfoService.getServiceInfo(dto.getServiceId()); + if (null == si) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"serviceId无效"); + } + + dto.setId(si.getMallUserInfo()); + if (null == dto.getId() || dto.getId() <= 0 ) { + ResultData data = this.doCreateUser(dto, EnumProject.PROJECT_2); + if (data.code == Result.SUCCESS) { + MallUserInfo mui = (MallUserInfo) data.data; + si.setMallUserInfo(mui.getId()); + serviceInfoService.updateServiceInfo(si); + }else { + throw new BizException(data.code,data.message); + } + }else { + this.doUpdateUser(dto, EnumProject.PROJECT_2); + } + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("慧影-查询登录账号") + @GetMapping("/getMallUserInfo") + public R getMallUserInfo(Long serviceId) { + if (null == serviceId) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"serviceId无效"); + } + + ServiceInfo si = serviceInfoService.getServiceInfo(serviceId); + if (null == si) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"serviceId无效"); + } + if (null != si.getMallUserInfo()) { + return R.ok(mallUserInfoService.getById(si.getMallUserInfo())); + } + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("慧影-设置时长") + @PostMapping("/setRemainingTimes") + public R setRemainingTimes(@RequestBody ServiceInfo dto) { + if (null == dto.getId()) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"id无效"); + } + if (null == dto.getTimes()) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"times无效"); + } + ServiceInfo si = serviceInfoService.getServiceInfo(dto.getId()); + if (null == si) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"id无效"); + } + + si.setRemainingTimes(dto.getTimes()); + serviceInfoService.updateServiceInfo(si); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("修改合作商") + @PostMapping("/update") + public R updateServiceInfo(@RequestBody UpdateServiceInfoDTO dto) { + serviceInfoService.updateServiceInfo(dto); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("修改合作商状态") + @PostMapping("/updateStatus") + public R updateServiceInfoStatus(@RequestBody UpdateServiceInfoStatusDTO dto) { + serviceInfoService.updateServiceInfoStatus(dto); + return R.ok(); + } + + @ApiOperation("接入商分页列表接口") + @GetMapping("personMouldIdList") + public ResultData serviceMouldIdList(Long serviceId) { + if (null == serviceId) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),serviceId+"不为空"); + } + List mouldIds = personMouldService.getServiceMouldIds(serviceId); + return new ResultData(mouldIds); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("设置关联模板") + @PostMapping("/associatedMould") + public R associatedMould(@RequestBody ServicePersonMould spm) { + if (null == spm.getMouldIds() || spm.getMouldIds().size() <= 0 ) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"请选择模板"); + } + serviceInfoService.associatedMoulds(spm.getMouldIds(), spm.getServiceId()); + return R.ok(); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("当前") + @GetMapping("/current") + public ResultData currentInfo() { + MallUserInfo user = this.getUser(); + ServiceInfo si = serviceInfoService.getServiceInfoByMallUserInfo(user.getId()); + return new ResultData(si); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("当前视频生成记录") + @GetMapping("/currentVideoRecords") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData currentVideoRecords(Integer pageNum, Integer pageSize) { + MallUserInfo user = this.getUser(); + ServiceInfo si = serviceInfoService.getServiceInfoByMallUserInfo(user.getId()); + ServiceVideoRecord svr = new ServiceVideoRecord(); + svr.setServiceId(si.getId()); + PageInfo personMouldPage = serviceVideoRecordService.listAsPage(svr, pageNum, pageSize); + return new ResultData(personMouldPage); + } + + @ApiOperation("当前视频生成记录总时长") + @GetMapping("/currentVideoToal") + public ResultData currentVideoToal() { + MallUserInfo user = this.getUser(); + ServiceInfo si = serviceInfoService.getServiceInfoByMallUserInfo(user.getId()); + ServiceVideoRecord svr = new ServiceVideoRecord(); + svr.setServiceId(si.getId()); + return new ResultData(serviceVideoRecordService.totalTimes(svr)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("私有化部署管理员当前") + @GetMapping("/privateDeployAdminCurrent") + public ResultData privateDeployAdminCurrent() { + MallUserInfo user = this.getUser(); + if (AiVideoHelper.localDeploy && user.checkAdmin()) { + return new ResultData(SmSdkUtils.getCurrentServiceInfo()); + }else { + return new ResultData(Result.ERROR,"当前访问非法"); + } + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("私有化部署管理员当前视频生成记录") + @GetMapping("/privateDeployAdminCurrentVideoRecords") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData privateDeployAdminCurrentVideoRecords(Integer pageNum, Integer pageSize) { + MallUserInfo user = this.getUser(); + if (AiVideoHelper.localDeploy && user.checkAdmin()) { + return new ResultData(SmSdkUtils.currentVideoRecords(pageNum,pageSize)); + }else { + return new ResultData(Result.ERROR,"当前访问非法"); + } + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("私有化部署管理员当前视频生成记录总时长") + @GetMapping("/privateDeployAdminCurrentVideoTotal") + public ResultData privateDeployAdminCurrentVideoTotal() { + MallUserInfo user = this.getUser(); + if (AiVideoHelper.localDeploy && user.checkAdmin()) { + return new ResultData(SmSdkUtils.currentVideoTotals()); + }else { + return new ResultData(Result.ERROR,"当前访问非法"); + } + } +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/ThirdPartyApiController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/ThirdPartyApiController.java new file mode 100644 index 0000000..75954df --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/ThirdPartyApiController.java @@ -0,0 +1,80 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; +import com.iformall.common.ErrorCode; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.controller.base.BaseController; +import com.iformall.domain.dto.sm.UpdateThirdPartyApiStatusDTO; +import com.iformall.domain.po.MallUserInfo; +import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.exception.BizException; +import com.iformall.service.WxThirdPartyApiService; +import com.iformall.service.sm.ServiceInfoService; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +@RestController +@RequestMapping("/thirdPartyApi") +@Api(tags = "秘钥接口") +public class ThirdPartyApiController extends BaseController{ + + @Autowired + private WxThirdPartyApiService thirdPartyApiService; + + @Autowired + private ServiceInfoService serviceInfoService; + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("分页查询秘钥") + @GetMapping("/page") + public R> pageThirdPartyApi(WxThirdPartyApi thirdPartyApi, Integer pageNum, Integer pageSize) { + return R.ok(thirdPartyApiService.pageThirdPartyApi(thirdPartyApi, pageNum, pageSize)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询秘钥") + @GetMapping("/getByServiceId") + public R getThirdPartyApiByServiceId(Long serviceId) { + if (serviceId == null) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + return R.ok(thirdPartyApiService.getThirdPartyApiByServiceId(serviceId)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询秘钥") + @GetMapping("/get") + public R getThirdPartyApi(Long id) { + if (id == null) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + return R.ok(thirdPartyApiService.getThirdPartyApi(id)); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("当前api信息") + @GetMapping("/current") + public R current() { + MallUserInfo user = this.getUser(); + ServiceInfo si = serviceInfoService.getServiceInfoByMallUserInfo(user.getId()); + if (null == si) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"当前登录账号无接入方信息."); + } + return R.ok(thirdPartyApiService.getThirdPartyApiByServiceId(si.getId())); + } + + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("修改秘钥状态") + @PostMapping("/updateStatus") + public R updateThirdPartyApiStatus(@RequestBody UpdateThirdPartyApiStatusDTO dto) { + thirdPartyApiService.updateThirdPartyApiStatus(dto); + return R.ok(); + } +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/UserMouldVideoController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/UserMouldVideoController.java index aff3731..2637439 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sm/UserMouldVideoController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/UserMouldVideoController.java @@ -9,9 +9,13 @@ import com.iformall.domain.po.base.BaseEntity; import com.iformall.domain.po.sm.MouldPatch; import com.iformall.domain.po.sm.MouldPatchSign; import com.iformall.domain.po.sm.UserMouldVideo; +import com.iformall.enums.EnumVideoStatus; +import com.iformall.service.WxCUserBasicInfoService; import com.iformall.service.sm.MouldPatchService; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.UserMouldVideoService; +import com.iformall.utils.DateUtils; + import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -33,17 +37,30 @@ public class UserMouldVideoController extends BaseController { @Autowired private UserMouldVideoService userMouldVideoService; + + @Autowired + private WxCUserBasicInfoService wxCUserBasicInfoService; @ApiOperation("分页列表接口") @GetMapping("list") @ApiImplicitParams({ - @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), - @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) - public ResultData list(@ModelAttribute UserMouldVideo record, Integer pageNum, Integer pageSize) { + @ApiImplicitParam(name = "PageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "PageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData list(@ModelAttribute UserMouldVideo record, Integer PageNum, Integer PageSize) { logger.debug("[" + getIpAddr() + "] UserMouldVideoController::list"); if (record == null) record = new UserMouldVideo(); + + if (StringUtils.isNotBlank(record.getPhone())) { + List cUserIds = wxCUserBasicInfoService.findIdsListByPhone(null, record.getPhone()); + if (null == cUserIds || cUserIds.size() <= 0 ) { + record.setId(-1L); + }else { + record.setCUserIds(cUserIds); + } + } + record.setVideoStatus(EnumVideoStatus.upload_success.getCode()); record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); - final PageInfo page = userMouldVideoService.listAsPage(record, pageNum, pageSize); + final PageInfo page = userMouldVideoService.listAsPage(record, PageNum, PageSize); return new ResultData(page); } diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sm/VoiceMouldController.java b/suimangAdmin/src/main/java/com/iformall/controller/sm/VoiceMouldController.java new file mode 100644 index 0000000..4e9e3b5 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sm/VoiceMouldController.java @@ -0,0 +1,131 @@ +package com.iformall.controller.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.ResultData; +import com.iformall.controller.base.BaseController; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.sm.PersonMould; +import com.iformall.domain.po.sm.UserMouldVideo; +import com.iformall.domain.po.sm.UserPersonMould; +import com.iformall.domain.po.sm.UserVoiceLanguage; +import com.iformall.domain.po.sm.VoiceLanguage; +import com.iformall.domain.po.sm.VoiceMould; +import com.iformall.enums.*; +import com.iformall.exception.BizException; +import com.iformall.language.LanguageDetect; +import com.iformall.service.WxCUserBasicInfoService; +import com.iformall.service.WxCVoiceService; +import com.iformall.service.sm.*; +import com.iformall.sm.AiPreviewParam; +import com.iformall.smsdk.SmPreviewVideoDTO; +import com.iformall.smsdk.SmSdkUtils; +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 java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + + +@RestController +@RequestMapping("voiceMould") +@Api(description = "模板接口") +public class VoiceMouldController extends BaseController { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + private VoiceLanguageService voiceLanguageService; + + @Autowired + private WxCUserBasicInfoService wxCUserBasicInfoService; + + + @ApiOperation("分页列表接口") + @GetMapping("alList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData list(@ModelAttribute VoiceLanguage record, Integer pageNum, Integer pageSize) { + if (record == null) record = new VoiceLanguage(); + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + record.setIsDel(EnumYesOrNo.NO.getCode()); + final PageInfo page = voiceLanguageService.listAsPage(record, pageNum, pageSize); + return new ResultData(page); + } + + @ApiOperation("用户声纹编码列表接口") + @GetMapping("userVoiceIdList") + public ResultData userVoiceIdList(Long cUserId) { + if (null == cUserId) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),cUserId+"不为空"); + } + List uids = new ArrayList(); + uids.add(cUserId); + List voiceIds = voiceLanguageService.getUserVoiceIdList(uids); + return new ResultData(voiceIds); + } + + @ApiOperation("设置用户关联模板") + @PostMapping("/associatedUserVoices") + public ResultData associatedUserVoices(@RequestBody UserVoiceLanguage uvl) { + if (null == uvl.getVoiceLanguageIdList() || uvl.getVoiceLanguageIdList().size() <= 0 ) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"请选择声纹"); + } + + if (null == uvl.getUserId() ) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"请选择用户"); + } + voiceLanguageService.associatedUserVoices(uvl.getVoiceLanguageIdList(), uvl.getUserId()); + return new ResultData(); + } + + @ApiOperation("用户分页列表接口") + @GetMapping("userVoiceList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "PageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "PageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData userVoiceList(@ModelAttribute VoiceLanguage record, Integer PageNum, Integer PageSize) { + if (null == record) { + record = new VoiceLanguage(); + } + if (StringUtils.isNotBlank(record.getPhone())) { + List cUserIds = wxCUserBasicInfoService.findIdsListByPhone(null, record.getPhone()); + if (null == cUserIds || cUserIds.size() <= 0 ) { + record.setId(-1L); + }else { + List mids = voiceLanguageService.getUserVoiceIdList(cUserIds); + if (null == mids || mids.size() <= 0 ) { + record.setId(-1L); + }else { + record.setIds(mids); + } + } + } + + record.setIsDel(EnumYesOrNo.NO.getCode()); + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + final PageInfo page = voiceLanguageService.listAsPage(record, PageNum, PageSize); + if (null != page && null != page.getList() && page.getList().size() > 0 ) { + for (int i = 0 ; i < page.getList().size(); i++) { + VoiceLanguage pm = page.getList().get(i); + List cuserIds = voiceLanguageService.getCUserIds(pm.getId()); + if (null != cuserIds && cuserIds.size() > 0) { + WxCUserBasicInfo u = new WxCUserBasicInfo(); + u.setIds(cuserIds); + pm.setWxCUserBasicInfoList(wxCUserBasicInfoService.findList(u)); + } + } + } + return new ResultData(page); + } + +} diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/HomeController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/HomeController.java index f7cb3c0..95ed4d0 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sys/HomeController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/HomeController.java @@ -2,10 +2,13 @@ package com.iformall.controller.sys; import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; +import com.iformall.annotation.ApiVersion; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; import com.iformall.controller.base.BaseController; +import com.iformall.controller.sys.mallUserInfo.MallUserInfoBaseController; import com.iformall.domain.po.*; import com.iformall.domain.po.base.TenantEntity; import com.iformall.domain.vo.MallUserInfoVo; @@ -15,6 +18,7 @@ import com.iformall.annotation.SystemControllerLog; import com.iformall.service.*; import com.iformall.shiro.UserSession; import com.iformall.shiro.UseriFormallToken; +import com.iformall.sm.AiVideoHelper; import com.iformall.utils.Constant; import com.iformall.utils.RedisCacheUtils; import com.iformall.utils.ShiroUtils; @@ -52,7 +56,7 @@ import java.util.Map; @RestController @Api(description = "登录相关接口") -public class HomeController extends BaseController { +public class HomeController extends MallUserInfoBaseController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${version}") @@ -61,20 +65,11 @@ public class HomeController extends BaseController { @Autowired private Producer producer; - @Autowired - private MallUserInfoService mallUserInfoService; - - @Autowired - private WxMsgValidationcodeService wxMsgValidationcodeService; - - @Autowired - private MallUserActionService mallUserActionService; - - @Autowired @Qualifier("objectCommonRedisTemplate") RedisTemplate redisTemplate; + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation("验证码") @GetMapping("/captcha.jpg") public void captcha(HttpServletResponse response)throws ServletException, IOException { @@ -87,178 +82,35 @@ public class HomeController extends BaseController { //生成图片验证码 BufferedImage image = producer.createImage(text); //保存到shiro session - ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); +// ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text); + String key = Constant.captchaPrev + ":" + getIpAddr(); + RedisCacheUtils.cache(redisTemplate, key, text, 60); + logger.info("验证码接口-生成的验证码:{}", text); ServletOutputStream out = response.getOutputStream(); ImageIO.write(image, "jpg", out); IOUtils.closeQuietly(out); } - @ApiOperation("登录") + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("慧影登录") @PostMapping("/doLogin") public ResultData login(@RequestBody MallUserInfo user, HttpServletResponse response) { - String ipaddress = getIpAddr(); - logger.debug("[" + ipaddress + "] HomeController::doLogin"); - try { - String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY); - if(!user.getCaptcha().equalsIgnoreCase(kaptcha)){ - return new ResultData(ErrorCode.KAPCHA_NOT_EQUAL); - } - } catch (MallinkException e) { - logger.error("验证码" + e.getMessage()); - return new ResultData(ErrorCode.KAPCHA_NOT_VALID.getCode(), e.getMessage()); - } - - if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) { -// throw new SystemException(ErrorCode.LOGIN_USER_OR_PWD_ERROR); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL); - } - // check user - MallUserInfo userCheck = mallUserInfoService.getByUsername(user.getUsername()); - if(userCheck == null) { - logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - if(userCheck.getStatus().equals(EnumMallUserStatus.NOT_VALID.getCode())) { - logger.error(ErrorCode.USER_IS_LOCKED.getMessage()); - return new ResultData(ErrorCode.USER_IS_LOCKED); - } - boolean isLogin = false; - try { - Subject subject = SecurityUtils.getSubject(); - UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); - subject.login(token); - isLogin = true; - logger.info("ADMIN USER:"+user.getUsername() + ", password:" + user.getPassword()); - } catch (UnknownAccountException e) { - logger.error(e.getMessage()); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } catch (DisabledAccountException e) { - logger.error(e.getMessage()); - return new ResultData(ErrorCode.USER_IS_LOCKED); - } catch (Exception e) { - logger.error(e.getMessage()); - return new ResultData(ErrorCode.USER_PASSWD_ERR); - } - - if(isLogin) { - MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); - info.protectInfos(); - mallUserActionService.saveActionInfo(info, EnumMallUserAction.CONTROLLER.getCode(), ipaddress, info.getId(), "用户登录"); - - try { - String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); - Cookie unameCookie = new Cookie("uname", cookieName); - unameCookie.setPath("/"); - unameCookie.setMaxAge(3600); - response.addCookie(unameCookie); - return new ResultData(); - } catch (Exception e) { - logger.error(e.getMessage()); - return new ResultData(Result.ERROR, e.getMessage()); - } - } - return new ResultData(Result.ERROR,"登陆失败"); + return doLogin(user, response, EnumProject.PROJECT_2); } - - @ApiOperation("发送手机验证码") + + @ApiOperation("慧影发送手机验证码") @GetMapping("sendLoginPhoneCode") @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true)}) public ResultData sendLoginPhoneCode(String phone) { - logger.debug("[" + getIpAddr() + "] HomeController::sendlogincode"); - // 1. 检查手机号是否在用户列表里, 是否只有一个 - // 2. 发送手机验证码, 直接发 - List users = mallUserInfoService.getUserByPhone(phone); - if(users.size() <= 0) { - logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - if(users.size() > 1) { - logger.error(ErrorCode.USER_IS_MULTI.getMessage()); - return new ResultData(ErrorCode.USER_IS_MULTI); - } - MallUserInfoVo user = users.get(0); - if (user==null) { - logger.error("用户不存在, userName: " + user.getUsername()); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - if(user.getStatus() == EnumMallUserStatus.NOT_VALID.getCode()){ - logger.error("用户已停用, userName: " + user.getUsername()); - return new ResultData(ErrorCode.USER_IS_LOCKED); - } - WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); - wxMsgValidationcode.setPhone(phone); - wxMsgValidationcode.updateTenantInfo(user); - wxMsgValidationcode.setType(EnumMsgModel.VALIDATION_CODE.getCode()); - return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode); + return doSendLoginPhoneCode(phone, EnumProject.PROJECT_2); } - @ApiOperation(value = "手机验证码登录", notes = "{\"phone\",\"string\",\"code\",\"string\"}") + @ApiOperation(value = "慧影手机验证码登录", notes = "{\"phone\",\"string\",\"code\",\"string\"}") @PostMapping("/doLoginByPhone") public ResultData doLoginByPhone(@RequestBody Map params, HttpServletResponse response) { - String ipaddress = getIpAddr(); - logger.debug("[" + ipaddress + "] HomeController::doLoginByPhone"); - // String phone,String code,String pwd - String phone = params.get("phone"); - String code = params.get("code"); - - if (StringUtils.isBlank(phone)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "userName不能为空"); - } - if (StringUtils.isBlank(code)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "验证码不能为空"); - } - - // 获取用户信息列表 - List userList = mallUserInfoService.getUserByPhone(phone); - if(userList.size() == 1) { - MallUserInfoVo user = userList.get(0); - if (user == null) { - logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - if (user.getStatus()==null ||!EnumMallUserStatus.VALID.getCode().equals(user.getStatus())) { - logger.error(ErrorCode.USER_IS_LOCKED.getMessage()); - return new ResultData(ErrorCode.USER_IS_LOCKED); - } - // check 验证码正确 - boolean isValidCode = false; - try { - isValidCode = wxMsgValidationcodeService.checkCodeValid(user.getPhone(),code); - } catch (Exception e) { - return new ResultData(Result.ERROR, e.getMessage()); - } - if(isValidCode) { - - // 验证码正确,直接登录 - try { - Subject subject = SecurityUtils.getSubject(); - UseriFormallToken token = new UseriFormallToken(user.getUsername()); - subject.login(token); - - MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); - info.protectInfos(); - mallUserActionService.saveActionInfo(info, EnumMallUserAction.CONTROLLER.getCode(), ipaddress, info.getId(), "用户手机号登录"); - - String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); - Cookie unameCookie = new Cookie("uname", cookieName); - unameCookie.setPath("/"); - unameCookie.setMaxAge(3600); - response.addCookie(unameCookie); - - return new ResultData(); - } catch (MallinkException e) { - return new ResultData(e.getErrorCode(), e.getMessage()); - } catch (Exception e) { - return new ResultData(ErrorCode.USER_PASSWD_ERR); - } - } else { - return new ResultData(ErrorCode.MSG_VERIFY_CODE_NOT_FOUND); - } - } else { - return new ResultData(ErrorCode.USER_IS_EMPTY); - } + return doLoginByPhone(params, response, EnumProject.PROJECT_2); } @ApiOperation("登出") @@ -278,4 +130,10 @@ public class HomeController extends BaseController { logger.info(">>>>>>>>>>>>>"+version); return new ResultData(version); } + + @ApiOperation("是否本地化部署") + @GetMapping("/localDeploy") + public ResultData localDeploy() { + return new ResultData(AiVideoHelper.localDeploy); + } } \ No newline at end of file diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/MallRoleController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/MallRoleController.java index e6178e8..92e3efb 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sys/MallRoleController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/MallRoleController.java @@ -1,10 +1,12 @@ package com.iformall.controller.sys; import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; import com.iformall.annotation.SystemControllerLog; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; import com.iformall.controller.base.BaseController; import com.iformall.domain.po.*; import com.iformall.domain.po.base.BaseEntity; @@ -43,13 +45,12 @@ public class MallRoleController extends BaseController { @Autowired private MallUserRoleService mallUserRoleService; + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation("角色列表") @GetMapping("list") - //@RequiresPermissions("sys:role:list") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) - @SystemControllerLog(description = "用户管理-role列表") public ResultData list(MallRole sysRole, Integer pageNum, Integer pageSize) { logger.debug("[" + getIpAddr() + "] MallRoleController::list"); sysRole.updateTenantInfo(getTenantInfo()); @@ -97,7 +98,7 @@ public class MallRoleController extends BaseController { return new ResultData(role); } - + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation("角色保存") @PostMapping("saveOrUpdate") //@RequiresPermissions("sys:role:save") @@ -128,6 +129,7 @@ public class MallRoleController extends BaseController { return new ResultData(); } + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation("角色删除") @PostMapping("/del") //@RequiresPermissions("sys:role:del") diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/MallUserInfoController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/MallUserInfoController.java index fa22251..11b9aa1 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sys/MallUserInfoController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/MallUserInfoController.java @@ -1,14 +1,18 @@ package com.iformall.controller.sys; import com.github.pagehelper.PageInfo; +import com.iformall.annotation.ApiVersion; import com.iformall.annotation.SystemControllerLog; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; import com.iformall.controller.base.BaseController; +import com.iformall.controller.sys.mallUserInfo.MallUserInfoBaseController; import com.iformall.domain.po.*; import com.iformall.domain.po.base.BaseEntity; import com.iformall.enums.EnumMallUserStatus; +import com.iformall.enums.EnumProject; import com.iformall.enums.EnumUserAdmin; import com.iformall.service.*; import com.iformall.shiro.PasswordHelper; @@ -35,18 +39,10 @@ import java.util.Map; @Api(value = "API - UserInfoController", description = "用户接口") @RestController @RequestMapping("user") -public class MallUserInfoController extends BaseController { +public class MallUserInfoController extends MallUserInfoBaseController { private final Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - MallUserInfoService userInfoService; - - @Autowired - MallUserRoleService userRoleService; - - @Autowired - MallRoleService mallRoleService; @Autowired MallUserRoleService mallUserRoleService; @@ -60,7 +56,8 @@ public class MallUserInfoController extends BaseController { @Autowired WxMsgValidationcodeService wxMsgValidationcodeService; - @ApiOperation(value = "用户分页接口", response = String.class) + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation(value = "慧影-用户分页接口", response = String.class) @GetMapping("lists") //@RequiresPermissions("sys:user:list") @ApiImplicitParams({ @@ -68,30 +65,7 @@ public class MallUserInfoController extends BaseController { @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) @SystemControllerLog(description = "用户管理-列表") public ResultData listAsPage(MallUserInfo userInfo, Integer pageNum, Integer pageSize) { - logger.debug("[" + getIpAddr() + "] MallUserInfoController::listAsPage"); - - userInfo.updateTenantInfo(getTenantInfo()); - userInfo.setSortColumns(BaseEntity.SortField.CreateTime_DESC,BaseEntity.SortField.Id_DESC); - final PageInfo page = userInfoService.listAsPage(userInfo, pageNum, pageSize); - for (MallUserInfo u : page.getList()) { - MallUserRole r = new MallUserRole(); - r.setUid(u.getId()); - PageInfo ur = userRoleService.listAsPage(r, 1, 1); - if (ur.getSize() > 0) { - MallRole role = mallRoleService.getById(ur.getList().get(0).getRoleId()); - if (role != null) { - u.setRoleName(role.getName()); - u.setRoleId(role.getId()); - } - } - // 保密 - u.setPassword(null); - u.setBopenId(null); - if(StringUtils.isNotBlank(u.getWebOpenId())) { - u.setWebOpenId("保密"); - } - } - return new ResultData(page); + return listAsPage(userInfo, pageNum, pageSize, EnumProject.PROJECT_2); } @ApiOperation(value = "用户详情接口", response = String.class) @@ -106,125 +80,28 @@ public class MallUserInfoController extends BaseController { if(StringUtils.isNotBlank(user.getWebOpenId())) { user.setWebOpenId("保密"); } - return new ResultData(user); } - @ApiOperation(value = "创建用户接口", response = String.class) + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation(value = "慧影-创建用户接口", response = String.class) @PostMapping("add") //@RequiresPermissions("sys:user:add") @SystemControllerLog(description = "用户管理-创建用户") public ResultData createUser(@RequestBody MallUserInfo userInfo) { - logger.debug("[" + getIpAddr() + "] MallUserInfoController::createUser"); - MallUserInfo currentUser = getUser(); - if(currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) { - return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有系统管理员才能添加用户"); - } - - if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ - return new ResultData(ErrorCode.USER_NO_PERMISSION); - } - - if(checkUniqueName(userInfo.getUsername()) > 0){ - return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); - } - if(checkUniquePhone(userInfo.getPhone()) > 0){ - return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); - } - Assert.notNull(userInfo.getPassword(), "密码不能为空"); - PasswordHelper passwordHelper = new PasswordHelper(); - passwordHelper.encryptPassword(userInfo); - userInfo.updateTenantInfo(currentUser); - // 无法创建超管 - userInfo.setIsAdmin(EnumUserAdmin.Normal.getCode()); - userInfoService.saveOrUpdate(userInfo); - if (userInfo.getRoleId() != null) { - MallUserRole r = new MallUserRole(); - r.setRoleId(userInfo.getRoleId()); - r.setUid(userInfo.getId()); - userRoleService.saveOrUpdate(r); - } - return new ResultData(userInfo); + return doCreateUser(userInfo, EnumProject.PROJECT_2); } - @ApiOperation(value = "修改用户接口", response = String.class) + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation(value = "慧影-修改用户接口", response = String.class) @PostMapping("update") //@RequiresPermissions("sys:user:update") @SystemControllerLog(description = "用户管理-修改用户") public ResultData updateUser(@RequestBody MallUserInfo userInfo) { - logger.debug("[" + getIpAddr() + "] MallUserInfoController::updateUser"); - boolean bChangedPhone = false; - MallUserInfo currentUser = getUser(); - // 只有超管和自己能更新信息 - if (!(currentUser.getId().equals(userInfo.getId()) || - currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode()))) { - return new ResultData(ErrorCode.USER_NO_PERMISSION.getCode(), "系统管理员和自己才能修改信息"); - } - if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ - return new ResultData(ErrorCode.USER_NO_PERMISSION); - } - MallUserInfo oldUser = userInfoService.getById(userInfo.getId()); - if (!oldUser.getUsername().equals(userInfo.getUsername())) { - if(checkUniqueName(userInfo.getUsername()) > 0){ - return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); - } - } - if (!oldUser.getPhone().equals(userInfo.getPhone())) { - if(checkUniquePhone(userInfo.getPhone()) > 0){ - return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); - } - bChangedPhone = true; - } - - userInfo.updateTenantInfo(currentUser); - if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() > 0) { - PasswordHelper passwordHelper = new PasswordHelper(); - passwordHelper.encryptPassword(userInfo); - } - // 系统内人员不能设置系统管理员 - userInfo.setIsAdmin(null); - /* - if (!currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode())) { - // 只有系统管理员才能设置系统管理员 - userInfo.setIsAdmin(null); - } - */ - - if (currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode()) && - currentUser.getId().equals(userInfo.getId())) { - // 超管 - MallUserInfo adminUser = new MallUserInfo(); - adminUser.setEmail(userInfo.getEmail()); - adminUser.setId(userInfo.getId()); - if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() > 0) { - adminUser.setPassword(userInfo.getPassword()); - } - if (StringUtils.isNotBlank(userInfo.getNickName())) { - adminUser.setNickName(userInfo.getNickName()); - } - if (StringUtils.isNotBlank(userInfo.getPhone())) { - adminUser.setPhone(userInfo.getPhone()); - } - adminUser.setInvestRule(userInfo.getInvestRule()); - userInfoService.saveOrUpdate(adminUser); - } else { - userInfoService.saveOrUpdate(userInfo); - if (userInfo.getRoleId() != null) { - userRoleService.deleteByUserId(userInfo.getId()); - MallUserRole r = new MallUserRole(); - r.setRoleId(userInfo.getRoleId()); - r.setUid(userInfo.getId()); - userRoleService.saveOrUpdate(r); - } - } - if(bChangedPhone) { - // 手机号修改,清除bopen_id, 清除web_open_id - userInfoService.cleanAllOpenId(userInfo); - } - - return new ResultData(); + return doUpdateUser(userInfo,EnumProject.PROJECT_2); } + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation(value = "删除用户接口", response = String.class) @PostMapping("/del") //@RequiresPermissions("sys:user:del") @@ -235,9 +112,9 @@ public class MallUserInfoController extends BaseController { if (currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) { return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有系统管理员才能删除用户"); } - if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ - return new ResultData(ErrorCode.USER_NO_PERMISSION); - } +// if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ +// return new ResultData(ErrorCode.USER_NO_PERMISSION); +// } if (currentUser.getId().equals(userInfo.getId())) { return new ResultData(ErrorCode.USER_NO_PERMISSION.getCode(), "用户不能删除自己"); } @@ -255,9 +132,9 @@ public class MallUserInfoController extends BaseController { MallUserInfo currentUser = getUser(); if (currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode())) { - if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ - return new ResultData(ErrorCode.USER_NO_PERMISSION); - } +// if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ +// return new ResultData(ErrorCode.USER_NO_PERMISSION); +// } MallUserInfo userInfo1 = userInfoService.getById(userInfo.getId()); if(userInfo1 == null) { @@ -275,14 +152,6 @@ public class MallUserInfoController extends BaseController { } } - private int checkUniqueName(String userName) { - return userInfoService.cntByUserName(userName); - } - - private int checkUniquePhone(String phone) { - return userInfoService.cntByUserPhone(phone); - } - @ApiOperation(value = "用户权限检查") @GetMapping("hasButtonPermission") @@ -320,78 +189,22 @@ public class MallUserInfoController extends BaseController { return new ResultData(menu); } - @ApiOperation(value = "用户密码发送验证码") + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation(value = "慧影-用户密码发送验证码") @GetMapping("sendvalidationcode") @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "手机号", dataType = "String", paramType = "query", required = true), @ApiImplicitParam(name = "type", value = "场景(1:登录)", dataType = "Integer", paramType = "query", required = true)}) public ResultData sendvalidationcode(String userName, Integer type) { - logger.debug("[" + getIpAddr() + "] MallUserInfoController::sendvalidationcode"); - MallUserInfo userQ = new MallUserInfo(); - userQ.setUsername(userName); - - MallUserInfo user = userInfoService.getByUsername(userName); - if (user==null) { - logger.error("用户不存在, userName: " + userName); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - - if(user.getStatus() == EnumMallUserStatus.NOT_VALID.getCode()){ - logger.error("用户已停用, userName: " + userName); - return new ResultData(ErrorCode.USER_IS_LOCKED); - } - - if (StringUtils.isBlank(user.getPhone())) { - logger.error("用户手机号为空, userName: " + userName); - return new ResultData(ErrorCode.USER_PHONE_IS_NOT_FOUND); - } - - WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); - wxMsgValidationcode.updateTenantInfo(user); - wxMsgValidationcode.setPhone(user.getPhone()); - wxMsgValidationcode.setType(type); - return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode); + return doSendvalidationcode(userName,type,EnumProject.PROJECT_2); } - @ApiOperation(value = "修改密码", notes = "{\"userName\",\"string\",\"code\",\"string\",\"pwd\",\"string\"}") + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation(value = "慧影-修改密码", notes = "{\"userName\",\"string\",\"pwd\",\"string\"}") @PostMapping("/updatepwd") @SystemControllerLog(description = "用户管理-修改密码") public ResultData updatepwd(@RequestBody Map params) { - logger.debug("[" + getIpAddr() + "] MallUserInfoController::updatepwd"); - // String phone,String code,String pwd - String userName = params.get("userName"); - String code = params.get("code"); - String pwd = params.get("pwd"); - - if (StringUtils.isBlank(userName)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "userName不能为空"); - } - if (StringUtils.isBlank(code)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "验证码不能为空"); - } - if (StringUtils.isBlank(pwd)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "密码不能为空"); - } - - MallUserInfo userQ = new MallUserInfo(); - userQ.setUsername(userName); - MallUserInfo user = userInfoService.getByUsername(userName); - if (user==null) { - logger.error("用户不存在, userName: " + userName); - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - - user.setPassword(pwd); - - PasswordHelper passwordHelper = new PasswordHelper(); - passwordHelper.encryptPassword(user); - - - try { - return userInfoService.updatepwd(user, code); - } catch (Exception e) { - return new ResultData(Result.ERROR, e.getMessage()); - } + return doUpdatepwd(params, EnumProject.PROJECT_2); } diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/SysMenuController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/SysMenuController.java index 26fd86c..165d5b9 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sys/SysMenuController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/SysMenuController.java @@ -1,9 +1,11 @@ package com.iformall.controller.sys; +import com.iformall.annotation.ApiVersion; import com.iformall.annotation.SystemControllerLog; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; import com.iformall.controller.base.BaseController; import com.iformall.domain.po.MallPermission; import com.iformall.domain.po.MallRole; @@ -65,6 +67,7 @@ public class SysMenuController extends BaseController { return new ResultData(map); } + @ApiVersion(group = SwaggerConstant.V_1_0_0) @ApiOperation("所有菜单列表") @GetMapping("list") //@RequiresPermissions("sys:menu:list") diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/WechatLoginController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/WechatLoginController.java index 6fa048c..a8ac878 100644 --- a/suimangAdmin/src/main/java/com/iformall/controller/sys/WechatLoginController.java +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/WechatLoginController.java @@ -287,155 +287,155 @@ public class WechatLoginController extends BaseController { } } - @ApiOperation(value = "微信用户登录") - @GetMapping("weChatUserLogin") - @ApiImplicitParams({ - @ApiImplicitParam(name = "key", value = "key", dataType = "String", paramType = "query", required = true), - @ApiImplicitParam(name = "userName", value = "userName", dataType = "String", paramType = "query", required = true)}) - public ResultData weChatUserLogin(String key, String userName, HttpServletRequest request, HttpServletResponse response) { - String ipaddress = getIpAddr(); - log.debug("[" + ipaddress + "] MallUserInfoController::weChatUserLogin"); - String host = request.getHeader("host"); - log.debug("Host: " + host); - if(StringUtils.isBlank(userName)) { - log.error("请选择要登录的用户"); - return new ResultData(ErrorCode.WECHAT_LOGIN_USER_SELECT); - } - - String openKey = WECHAT_PREV + key; - // 限时时间内查找到此用户openId - if (openRedisTemplate.hasKey(openKey)){ - log.info(openKey + " - 找不到"); - String openId = openRedisTemplate.opsForValue().get(openKey); - openRedisTemplate.delete(openKey); - log.info("KEY: " + openKey + " deleted"); - - MallUserInfo userInfo = mallUserInfoService.getByUsername(userName); - if (userInfo == null) { - return new ResultData(ErrorCode.USER_IS_EMPTY); - } - if (userInfo.getStatus()==null ||!EnumMallUserStatus.VALID.getCode().equals(userInfo.getStatus())) { - return new ResultData(ErrorCode.USER_IS_LOCKED); - } - if(userInfo.getWebOpenId().equals(openId)) { - boolean isLogin = false; - try { - Subject subject = SecurityUtils.getSubject(); - UseriFormallToken token = new UseriFormallToken(userInfo.getUsername()); - subject.login(token); - MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); - info.protectInfos(); - String menus = mallUserRoleService.getPermissionsByUser(info); - if(StringUtils.isNotBlank(menus)) { - info.setMenus(menus); - } - Map ret = new HashMap<>(); - WxMall mall = mallService.getByTenantInfo(info); - if (mall == null) { - ret.put("code", Result.ERROR); - ret.put("message", "未配置相应的mall"); - log.info("用户登录失败-4,返回登录"); - try { - String errCode = URLEncoder.encode(JSON.toJSONString(ret), "utf-8"); - response.sendRedirect("https://" + host + "/#/login?errcode=" + errCode); - } catch (Exception e) { - log.error(e.getMessage()); - } - } - if (!mall.isValid()) { - ret.put("code", Result.ERROR); - ret.put("message", "mall已过期"); - log.info("用户登录失败-5,返回登录"); - try { - String errCode = URLEncoder.encode(JSON.toJSONString(ret), "utf-8"); - response.sendRedirect("https://" + host + "/#/login?errcode=" + errCode); - } catch (Exception e) { - log.error(e.getMessage()); - } - } - // 登录cookie - String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); - Cookie unameCookie = new Cookie("uname", cookieName); - unameCookie.setPath("/"); - unameCookie.setMaxAge(3600); - response.addCookie(unameCookie); - - MallUserAction action = new MallUserAction(); - action.updateTenantInfo(info); - action.setType(EnumMallUserAction.CONTROLLER.getCode()); - action.setIp(ipaddress); - action.setUserId(info.getId()); - action.setActionDesc("用户微信登录"); - action.setActionTime(new Date()); - mallUserActionService.saveOrUpdate(action); - - return new ResultData(); - } catch (UnknownAccountException e) { - log.error(e.getMessage()); - return new ResultData(ErrorCode.USER_IS_EMPTY.getCode(), e.getMessage()); - } catch (DisabledAccountException e) { - log.error(e.getMessage()); - return new ResultData(ErrorCode.USER_IS_LOCKED.getCode(), e.getMessage()); - } catch (Exception e) { - log.error(e.getMessage()); - return new ResultData(Result.ERROR, e.getMessage()); - } - } else { - // 登录失败 - log.error("微信登录失败,用户微信未绑定:" + openId); - return new ResultData(ErrorCode.WECHAT_LOGIN_NOT_BIND); - } - } - log.error("微信登录失败,KEY已过期: "+ key); - return new ResultData(ErrorCode.WECHAT_LOGIN_KEY_OVERTIME); - } - - @ApiOperation(value = "微信第三方登录绑定", notes = "请配置此callback到网页redirect_uri") - @GetMapping("bindWebOpenId") - @SystemControllerLog(description = "微信第三方登录绑定") - public void userBindWebOpenId(String code, String state, HttpServletRequest request, HttpServletResponse response) { - log.debug("[" + getIpAddr() + "] WechatLoginController::bindWebOpenId"); - String host = request.getHeader("host"); - String errCode = null; - try { - WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); - log.debug("accessToken: " + accessToken.getAccessToken() + ", openId: " + accessToken.getOpenId() + ", unionId: " + accessToken.getUnionId()); - - // 获取 用户信息 - WxMpUser mpUser = wxMpService.oauth2getUserInfo(accessToken, null); - if(mpUser != null) { - log.debug(mpUser.toString()); - } - - String uname = state; - MallUserInfo user = mallUserInfoService.getByUsername(uname); - if(user != null) { - user.setWebOpenId(accessToken.getOpenId()); - mallUserInfoService.updateWebOpenId(user); - log.debug("https://" + host + "/#/layout"); - response.sendRedirect("https://" + host + "/#/layout"); - } else { - log.debug("https://" + host + "/#/layout?errcode=绑定失败"); - errCode = URLEncoder.encode("绑定失败", "utf-8"); - response.sendRedirect("https://" + host + "/#/layout?errcode="+errCode); - } - } catch (WxErrorException e) { - log.error(e.getMessage()); - errCode = e.getMessage(); - } catch (IOException e) { - log.error(e.getMessage()); - errCode = e.getMessage(); - } +// @ApiOperation(value = "微信用户登录") +// @GetMapping("weChatUserLogin") +// @ApiImplicitParams({ +// @ApiImplicitParam(name = "key", value = "key", dataType = "String", paramType = "query", required = true), +// @ApiImplicitParam(name = "userName", value = "userName", dataType = "String", paramType = "query", required = true)}) +// public ResultData weChatUserLogin(String key, String userName, HttpServletRequest request, HttpServletResponse response) { +// String ipaddress = getIpAddr(); +// log.debug("[" + ipaddress + "] MallUserInfoController::weChatUserLogin"); +// String host = request.getHeader("host"); +// log.debug("Host: " + host); +// if(StringUtils.isBlank(userName)) { +// log.error("请选择要登录的用户"); +// return new ResultData(ErrorCode.WECHAT_LOGIN_USER_SELECT); +// } +// +// String openKey = WECHAT_PREV + key; +// // 限时时间内查找到此用户openId +// if (openRedisTemplate.hasKey(openKey)){ +// log.info(openKey + " - 找不到"); +// String openId = openRedisTemplate.opsForValue().get(openKey); +// openRedisTemplate.delete(openKey); +// log.info("KEY: " + openKey + " deleted"); +// +// MallUserInfo userInfo = mallUserInfoService.getByUsername(userName); +// if (userInfo == null) { +// return new ResultData(ErrorCode.USER_IS_EMPTY); +// } +// if (userInfo.getStatus()==null ||!EnumMallUserStatus.VALID.getCode().equals(userInfo.getStatus())) { +// return new ResultData(ErrorCode.USER_IS_LOCKED); +// } +// if(userInfo.getWebOpenId().equals(openId)) { +// boolean isLogin = false; +// try { +// Subject subject = SecurityUtils.getSubject(); +// UseriFormallToken token = new UseriFormallToken(userInfo.getUsername()); +// subject.login(token); +// MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); +// info.protectInfos(); +// String menus = mallUserRoleService.getPermissionsByUser(info); +// if(StringUtils.isNotBlank(menus)) { +// info.setMenus(menus); +// } +// Map ret = new HashMap<>(); +// WxMall mall = mallService.getByTenantInfo(info); +// if (mall == null) { +// ret.put("code", Result.ERROR); +// ret.put("message", "未配置相应的mall"); +// log.info("用户登录失败-4,返回登录"); +// try { +// String errCode = URLEncoder.encode(JSON.toJSONString(ret), "utf-8"); +// response.sendRedirect("https://" + host + "/#/login?errcode=" + errCode); +// } catch (Exception e) { +// log.error(e.getMessage()); +// } +// } +// if (!mall.isValid()) { +// ret.put("code", Result.ERROR); +// ret.put("message", "mall已过期"); +// log.info("用户登录失败-5,返回登录"); +// try { +// String errCode = URLEncoder.encode(JSON.toJSONString(ret), "utf-8"); +// response.sendRedirect("https://" + host + "/#/login?errcode=" + errCode); +// } catch (Exception e) { +// log.error(e.getMessage()); +// } +// } +// // 登录cookie +// String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); +// Cookie unameCookie = new Cookie("uname", cookieName); +// unameCookie.setPath("/"); +// unameCookie.setMaxAge(3600); +// response.addCookie(unameCookie); +// +// MallUserAction action = new MallUserAction(); +// action.updateTenantInfo(info); +// action.setType(EnumMallUserAction.CONTROLLER.getCode()); +// action.setIp(ipaddress); +// action.setUserId(info.getId()); +// action.setActionDesc("用户微信登录"); +// action.setActionTime(new Date()); +// mallUserActionService.saveOrUpdate(action); +// +// return new ResultData(); +// } catch (UnknownAccountException e) { +// log.error(e.getMessage()); +// return new ResultData(ErrorCode.USER_IS_EMPTY.getCode(), e.getMessage()); +// } catch (DisabledAccountException e) { +// log.error(e.getMessage()); +// return new ResultData(ErrorCode.USER_IS_LOCKED.getCode(), e.getMessage()); +// } catch (Exception e) { +// log.error(e.getMessage()); +// return new ResultData(Result.ERROR, e.getMessage()); +// } +// } else { +// // 登录失败 +// log.error("微信登录失败,用户微信未绑定:" + openId); +// return new ResultData(ErrorCode.WECHAT_LOGIN_NOT_BIND); +// } +// } +// log.error("微信登录失败,KEY已过期: "+ key); +// return new ResultData(ErrorCode.WECHAT_LOGIN_KEY_OVERTIME); +// } - if(StringUtils.isNotBlank(errCode)) { - try { - errCode = URLEncoder.encode(errCode, "utf-8"); - response.sendRedirect("https://" + host + "/#/layout?errcode="+errCode); - } catch (Exception e) { - log.error(e.getMessage()); - } - } - } +// @ApiOperation(value = "微信第三方登录绑定", notes = "请配置此callback到网页redirect_uri") +// @GetMapping("bindWebOpenId") +// @SystemControllerLog(description = "微信第三方登录绑定") +// public void userBindWebOpenId(String code, String state, HttpServletRequest request, HttpServletResponse response) { +// log.debug("[" + getIpAddr() + "] WechatLoginController::bindWebOpenId"); +// String host = request.getHeader("host"); +// String errCode = null; +// try { +// WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); +// log.debug("accessToken: " + accessToken.getAccessToken() + ", openId: " + accessToken.getOpenId() + ", unionId: " + accessToken.getUnionId()); +// +// // 获取 用户信息 +// WxMpUser mpUser = wxMpService.oauth2getUserInfo(accessToken, null); +// if(mpUser != null) { +// log.debug(mpUser.toString()); +// } +// +// String uname = state; +// MallUserInfo user = mallUserInfoService.getByUsername(uname); +// if(user != null) { +// user.setWebOpenId(accessToken.getOpenId()); +// mallUserInfoService.updateWebOpenId(user); +// log.debug("https://" + host + "/#/layout"); +// response.sendRedirect("https://" + host + "/#/layout"); +// } else { +// log.debug("https://" + host + "/#/layout?errcode=绑定失败"); +// errCode = URLEncoder.encode("绑定失败", "utf-8"); +// response.sendRedirect("https://" + host + "/#/layout?errcode="+errCode); +// } +// } catch (WxErrorException e) { +// log.error(e.getMessage()); +// errCode = e.getMessage(); +// } catch (IOException e) { +// log.error(e.getMessage()); +// errCode = e.getMessage(); +// } +// +// if(StringUtils.isNotBlank(errCode)) { +// try { +// errCode = URLEncoder.encode(errCode, "utf-8"); +// response.sendRedirect("https://" + host + "/#/layout?errcode="+errCode); +// } catch (Exception e) { +// log.error(e.getMessage()); +// } +// } +// } @ApiOperation(value = "微信第三方登录解绑", notes = "请配置此callback到网页redirect_uri") @GetMapping("cleanWebOpenId") diff --git a/suimangAdmin/src/main/java/com/iformall/controller/sys/mallUserInfo/MallUserInfoBaseController.java b/suimangAdmin/src/main/java/com/iformall/controller/sys/mallUserInfo/MallUserInfoBaseController.java new file mode 100644 index 0000000..4f1a073 --- /dev/null +++ b/suimangAdmin/src/main/java/com/iformall/controller/sys/mallUserInfo/MallUserInfoBaseController.java @@ -0,0 +1,472 @@ +package com.iformall.controller.sys.mallUserInfo; + +import com.github.pagehelper.PageInfo; +import com.google.code.kaptcha.Constants; +import com.google.code.kaptcha.Producer; +import com.iformall.annotation.ApiVersion; +import com.iformall.common.ErrorCode; +import com.iformall.common.Result; +import com.iformall.common.ResultData; +import com.iformall.config.MyAuthenticationToken; +import com.iformall.constant.SwaggerConstant; +import com.iformall.controller.base.BaseController; +import com.iformall.domain.po.*; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.base.TenantEntity; +import com.iformall.domain.vo.MallUserInfoVo; +import com.iformall.enums.*; +import com.iformall.exception.MallinkException; +import com.iformall.annotation.SystemControllerLog; +import com.iformall.service.*; +import com.iformall.shiro.PasswordHelper; +import com.iformall.shiro.UserSession; +import com.iformall.shiro.UseriFormallToken; +import com.iformall.utils.Constant; +import com.iformall.utils.RedisCacheUtils; +import com.iformall.utils.ShiroUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.DisabledAccountException; +import org.apache.shiro.authc.UnknownAccountException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.session.Session; +import org.apache.shiro.subject.Subject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.util.Assert; +import org.springframework.web.bind.annotation.*; +import javax.imageio.ImageIO; +import javax.servlet.ServletException; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletResponse; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class MallUserInfoBaseController extends BaseController{ + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + public MallUserInfoService mallUserInfoService; + + @Autowired + public WxMsgValidationcodeService wxMsgValidationcodeService; + + @Autowired + public MallUserActionService mallUserActionService; + + @Autowired + public MallUserInfoService userInfoService; + + @Autowired + public MallUserRoleService userRoleService; + + @Autowired + public MallRoleService mallRoleService; + + + @Autowired + @Qualifier("objectCommonRedisTemplate") + public RedisTemplate redisTemplate; + + /** + * 登录 + * @param user + * @param response + * @param projectType + * @return + */ + public ResultData doLogin(MallUserInfo user, HttpServletResponse response,EnumProject projectType) { + String ipaddress = getIpAddr(); +// try { +// String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY); +// logger.info("登录接口-验证码:{}", user.getCaptcha()); +// logger.info("登录接口-生成的验证码:{}", kaptcha); +// if(!user.getCaptcha().equalsIgnoreCase(kaptcha)){ +// return new ResultData(ErrorCode.KAPCHA_NOT_EQUAL); +// } +// } catch (MallinkException e) { +// logger.error("验证码" + e.getMessage()); +// return new ResultData(ErrorCode.KAPCHA_NOT_VALID.getCode(), e.getMessage()); +// } + String key = Constant.captchaPrev + ":" + getIpAddr(); + String code = RedisCacheUtils.getCacheString(redisTemplate, key); + if (StringUtils.isBlank(code)) { + return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); + } + if (!code.equals(user.getCaptcha())) { + return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); + } + + + if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + // check user + MallUserInfo userCheck = mallUserInfoService.getByUsername(user.getUsername(),projectType.getCode()); + if(userCheck == null) { + logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + if(userCheck.getStatus().equals(EnumMallUserStatus.NOT_VALID.getCode())) { + logger.error(ErrorCode.USER_IS_LOCKED.getMessage()); + return new ResultData(ErrorCode.USER_IS_LOCKED); + } + boolean isLogin = false; + try { + Subject subject = SecurityUtils.getSubject(); + //UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword()); + //subject.login(token); + MyAuthenticationToken mytoken = new MyAuthenticationToken(projectType.getCode(),user.getUsername(),user.getPassword().toCharArray()); + subject.login(mytoken); + isLogin = true; + logger.info("ADMIN USER:"+user.getUsername() + ", password:" + user.getPassword()); + } catch (UnknownAccountException e) { + logger.error(e.getMessage()); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } catch (DisabledAccountException e) { + logger.error(e.getMessage()); + return new ResultData(ErrorCode.USER_IS_LOCKED); + } catch (Exception e) { + logger.error(e.getMessage()); + return new ResultData(ErrorCode.USER_PASSWD_ERR); + } + + if(isLogin) { + MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); + info.protectInfos(); + mallUserActionService.saveActionInfo(info, EnumMallUserAction.CONTROLLER.getCode(), ipaddress, info.getId(), "用户登录"); + + try { + String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); + Cookie unameCookie = new Cookie("uname", cookieName); + unameCookie.setPath("/"); + unameCookie.setMaxAge(3600); + response.addCookie(unameCookie); + return new ResultData(); + } catch (Exception e) { + logger.error(e.getMessage()); + return new ResultData(Result.ERROR, e.getMessage()); + } + } + return new ResultData(Result.ERROR,"登陆失败"); + } + + //登录发送手机验证码 + public ResultData doSendLoginPhoneCode(String phone,EnumProject projectType) { + List users = mallUserInfoService.getUserByPhone(phone,projectType.getCode()); + if(users.size() <= 0) { + logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + if(users.size() > 1) { + logger.error(ErrorCode.USER_IS_MULTI.getMessage()); + return new ResultData(ErrorCode.USER_IS_MULTI); + } + MallUserInfoVo user = users.get(0); + if (user==null) { + logger.error("用户不存在, userName: " + user.getUsername()); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + if(user.getStatus() == EnumMallUserStatus.NOT_VALID.getCode()){ + logger.error("用户已停用, userName: " + user.getUsername()); + return new ResultData(ErrorCode.USER_IS_LOCKED); + } + WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); + wxMsgValidationcode.setPhone(phone); + wxMsgValidationcode.updateTenantInfo(user); + wxMsgValidationcode.setType(EnumMsgModel.VALIDATION_CODE.getCode()); + return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode,projectType.getCode()); + } + + //手机验证码登录 + public ResultData doLoginByPhone(Map params, HttpServletResponse response,EnumProject projectType) { + String ipaddress = getIpAddr(); + logger.debug("[" + ipaddress + "] HomeController::doLoginByPhone"); + // String phone,String code,String pwd + String phone = params.get("phone"); + String code = params.get("code"); + + if (StringUtils.isBlank(phone)) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "userName不能为空"); + } + if (StringUtils.isBlank(code)) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "验证码不能为空"); + } + + // 获取用户信息列表 + List userList = mallUserInfoService.getUserByPhone(phone,projectType.getCode()); + if(userList.size() == 1) { + MallUserInfoVo user = userList.get(0); + if (user == null) { + logger.error(ErrorCode.USER_IS_EMPTY.getMessage()); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + if (user.getStatus()==null ||!EnumMallUserStatus.VALID.getCode().equals(user.getStatus())) { + logger.error(ErrorCode.USER_IS_LOCKED.getMessage()); + return new ResultData(ErrorCode.USER_IS_LOCKED); + } + // check 验证码正确 + boolean isValidCode = false; + try { + isValidCode = wxMsgValidationcodeService.checkCodeValid(user.getPhone(),code,projectType.getCode()); + } catch (Exception e) { + return new ResultData(Result.ERROR, e.getMessage()); + } + if(isValidCode) { + + // 验证码正确,直接登录 + try { + Subject subject = SecurityUtils.getSubject(); + UseriFormallToken token = new UseriFormallToken(user.getUsername()); + subject.login(token); + + MallUserInfo info = (MallUserInfo) SecurityUtils.getSubject().getSession().getAttribute(UserSession.userInfo); + info.protectInfos(); + mallUserActionService.saveActionInfo(info, EnumMallUserAction.CONTROLLER.getCode(), ipaddress, info.getId(), "用户手机号登录"); + + String cookieName = URLEncoder.encode(info.getUsername(), "utf-8"); + Cookie unameCookie = new Cookie("uname", cookieName); + unameCookie.setPath("/"); + unameCookie.setMaxAge(3600); + response.addCookie(unameCookie); + + return new ResultData(); + } catch (MallinkException e) { + return new ResultData(e.getErrorCode(), e.getMessage()); + } catch (Exception e) { + return new ResultData(ErrorCode.USER_PASSWD_ERR); + } + } else { + return new ResultData(ErrorCode.MSG_VERIFY_CODE_NOT_FOUND); + } + } else { + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + } + + //分页查询用户 + public ResultData listAsPage(MallUserInfo userInfo, Integer pageNum, Integer pageSize,EnumProject projectType) { + userInfo.updateTenantInfo(getTenantInfo()); + userInfo.setSortColumns(BaseEntity.SortField.CreateTime_DESC,BaseEntity.SortField.Id_DESC); + userInfo.setProjectType(projectType.getCode()); + final PageInfo page = userInfoService.listAsPage(userInfo, pageNum, pageSize); + for (MallUserInfo u : page.getList()) { + MallUserRole r = new MallUserRole(); + r.setUid(u.getId()); + PageInfo ur = userRoleService.listAsPage(r, 1, 1); + if (ur.getSize() > 0) { + MallRole role = mallRoleService.getById(ur.getList().get(0).getRoleId()); + if (role != null) { + u.setRoleName(role.getName()); + u.setRoleId(role.getId()); + } + } + // 保密 + u.setPassword(null); + u.setBopenId(null); + if(StringUtils.isNotBlank(u.getWebOpenId())) { + u.setWebOpenId("保密"); + } + } + return new ResultData(page); + } + + //新增用户 + public ResultData doCreateUser(MallUserInfo userInfo,EnumProject projectType) { + MallUserInfo currentUser = getUser(); + if(currentUser.getIsAdmin().equals(EnumUserAdmin.Normal.getCode())) { + return new ResultData(ErrorCode.USER_NOT_ADMIN.getCode(), "只有系统管理员才能添加用户"); + } + +// if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ +// return new ResultData(ErrorCode.USER_NO_PERMISSION); +// } + + if(checkUniqueName(userInfo.getUsername(),projectType) > 0){ + return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); + } + if(checkUniquePhone(userInfo.getPhone(),projectType) > 0){ + return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); + } + Assert.notNull(userInfo.getPassword(), "密码不能为空"); + PasswordHelper passwordHelper = new PasswordHelper(); + passwordHelper.encryptPassword(userInfo); + userInfo.updateTenantInfo(currentUser); + // 无法创建超管 + userInfo.setIsAdmin(EnumUserAdmin.Normal.getCode()); + userInfo.setProjectType(projectType.getCode()); + userInfoService.saveOrUpdate(userInfo); + if (userInfo.getRoleId() != null) { + MallUserRole r = new MallUserRole(); + r.setRoleId(userInfo.getRoleId()); + r.setUid(userInfo.getId()); + userRoleService.saveOrUpdate(r); + } + return new ResultData(userInfo); + } + + //修改用户 + public ResultData doUpdateUser(MallUserInfo userInfo,EnumProject projectType) { + boolean bChangedPhone = false; + MallUserInfo currentUser = getUser(); + // 只有超管和自己能更新信息 + if (!(currentUser.getId().equals(userInfo.getId()) || + currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode()))) { + return new ResultData(ErrorCode.USER_NO_PERMISSION.getCode(), "系统管理员和自己才能修改信息"); + } +// if(!getTenantInfo().getTenantId().equals(currentUser.getTenantId())){ +// return new ResultData(ErrorCode.USER_NO_PERMISSION); +// } + MallUserInfo oldUser = userInfoService.getById(userInfo.getId()); + if (!oldUser.getUsername().equals(userInfo.getUsername())) { + if(checkUniqueName(userInfo.getUsername(),projectType) > 0){ + return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); + } + } + if (!oldUser.getPhone().equals(userInfo.getPhone())) { + if(checkUniquePhone(userInfo.getPhone(),projectType) > 0){ + return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); + } + bChangedPhone = true; + } + + userInfo.updateTenantInfo(currentUser); + if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() > 0) { + PasswordHelper passwordHelper = new PasswordHelper(); + passwordHelper.encryptPassword(userInfo); + } + // 系统内人员不能设置系统管理员 + userInfo.setIsAdmin(EnumUserAdmin.Normal.getCode()); + /* + if (!currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode())) { + // 只有系统管理员才能设置系统管理员 + userInfo.setIsAdmin(null); + } + */ + + if (currentUser.getIsAdmin().equals(EnumUserAdmin.ADMIN.getCode()) && + currentUser.getId().equals(userInfo.getId())) { + // 超管 + MallUserInfo adminUser = new MallUserInfo(); + adminUser.setEmail(userInfo.getEmail()); + adminUser.setId(userInfo.getId()); + if (StringUtils.isNotBlank(userInfo.getPassword()) && userInfo.getPassword().length() > 0) { + adminUser.setPassword(userInfo.getPassword()); + } + if (StringUtils.isNotBlank(userInfo.getNickName())) { + adminUser.setNickName(userInfo.getNickName()); + } + if (StringUtils.isNotBlank(userInfo.getPhone())) { + adminUser.setPhone(userInfo.getPhone()); + } + adminUser.setInvestRule(userInfo.getInvestRule()); + userInfoService.saveOrUpdate(adminUser); + } else { + userInfoService.saveOrUpdate(userInfo); + if (userInfo.getRoleId() != null) { + userRoleService.deleteByUserId(userInfo.getId()); + MallUserRole r = new MallUserRole(); + r.setRoleId(userInfo.getRoleId()); + r.setUid(userInfo.getId()); + userRoleService.saveOrUpdate(r); + } + } + if(bChangedPhone) { + // 手机号修改,清除bopen_id, 清除web_open_id + userInfoService.cleanAllOpenId(userInfo); + } + + return new ResultData(); + } + + public int checkUniqueName(String userName,EnumProject projectType) { + return userInfoService.cntByUserName(userName,projectType.getCode()); + } + + public int checkUniquePhone(String phone,EnumProject projectType) { + return userInfoService.cntByUserPhone(phone,projectType.getCode()); + } + + //向用户发送验证码 + public ResultData doSendvalidationcode(String userName, Integer type,EnumProject projectType) { + MallUserInfo userQ = new MallUserInfo(); + userQ.setUsername(userName); + + MallUserInfo user = userInfoService.getByUsername(userName,projectType.getCode()); + if (user==null) { + logger.error("用户不存在, userName: " + userName); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + + if(user.getStatus() == EnumMallUserStatus.NOT_VALID.getCode()){ + logger.error("用户已停用, userName: " + userName); + return new ResultData(ErrorCode.USER_IS_LOCKED); + } + + if (StringUtils.isBlank(user.getPhone())) { + logger.error("用户手机号为空, userName: " + userName); + return new ResultData(ErrorCode.USER_PHONE_IS_NOT_FOUND); + } + + WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); + wxMsgValidationcode.updateTenantInfo(user); + wxMsgValidationcode.setPhone(user.getPhone()); + wxMsgValidationcode.setType(type); + return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode,projectType.getCode()); + } + + //更改用户密码 + public ResultData doUpdatepwd(Map params,EnumProject projectType) { + // String phone,String code,String pwd + String userName = params.get("userName"); +// String code = params.get("code"); + String pwd = params.get("pwd"); + + if (StringUtils.isBlank(userName)) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "userName不能为空"); + } +// if (StringUtils.isBlank(code)) { +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "验证码不能为空"); +// } + if (StringUtils.isBlank(pwd)) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "密码不能为空"); + } + + MallUserInfo userQ = new MallUserInfo(); + userQ.setUsername(userName); + MallUserInfo user = userInfoService.getByUsername(userName,projectType.getCode()); + if (user==null) { + logger.error("用户不存在, userName: " + userName); + return new ResultData(ErrorCode.USER_IS_EMPTY); + } + + user.setPassword(pwd); + + PasswordHelper passwordHelper = new PasswordHelper(); + passwordHelper.encryptPassword(user); + + + try { + //return userInfoService.updatepwd(user, code); + return userInfoService.updatepwd(user, null); + } catch (Exception e) { + return new ResultData(Result.ERROR, e.getMessage()); + } + } + +} \ No newline at end of file diff --git a/suimangAdmin/src/main/java/com/iformall/shiro/MyShiroRealm.java b/suimangAdmin/src/main/java/com/iformall/shiro/MyShiroRealm.java index 2689cc3..cb0e8c6 100644 --- a/suimangAdmin/src/main/java/com/iformall/shiro/MyShiroRealm.java +++ b/suimangAdmin/src/main/java/com/iformall/shiro/MyShiroRealm.java @@ -3,6 +3,7 @@ package com.iformall.shiro; import javax.annotation.Resource; import com.iformall.common.ErrorCode; +import com.iformall.config.MyAuthenticationToken; import com.iformall.enums.EnumMallUserStatus; import com.iformall.service.MallUserInfoService; import org.apache.commons.lang3.StringUtils; @@ -27,7 +28,13 @@ public class MyShiroRealm extends AuthorizingRealm { @Resource private MallUserInfoService userService; - //授权 + //识别自定义token + @Override + public boolean supports(AuthenticationToken token) { + return token != null && token instanceof MyAuthenticationToken; + } + + //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { MallUserInfo user= (MallUserInfo) SecurityUtils.getSubject().getPrincipal(); @@ -40,17 +47,13 @@ public class MyShiroRealm extends AuthorizingRealm { //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + MyAuthenticationToken mytoken = (MyAuthenticationToken) token; //获取用户的输入的账号. - String username = (String)token.getPrincipal(); - MallUserInfo user = userService.getByUsername(username); + //String username = (String)token.getPrincipal(); + MallUserInfo user = userService.getByUsername(mytoken.getUsername(),mytoken.getProjectType()); if(user == null) { throw new UnknownAccountException(ErrorCode.USER_IS_EMPTY.getMessage()); } - // 租户1为预留系统管理端 -// if(user.getTenantId().equals("1")) { -// // 只支持租户为1的用户 -// throw new UnknownAccountException("租户不支持"); -// } if(user.getStatus()==null || !EnumMallUserStatus.VALID.getCode().equals(user.getStatus())) {//用户被禁用 @@ -59,7 +62,7 @@ public class MyShiroRealm extends AuthorizingRealm { SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( user, //用户 user.getPassword(), //密码 - ByteSource.Util.bytes(username), + ByteSource.Util.bytes(mytoken.getUsername()), getName() //realm name ); // 当验证都通过后,把用户信息放在session里 @@ -67,16 +70,6 @@ public class MyShiroRealm extends AuthorizingRealm { session.setAttribute(UserSession.userInfo, user); session.setAttribute(UserSession.userId, user.getId()); session.setAttribute(UserSession.tenantId, user.getTenantId()); - if (StringUtils.isNotBlank(user.getParentTenantId())) { - session.setAttribute(UserSession.parentTenantId, user.getParentTenantId()); - }else{ - session.setAttribute(UserSession.parentTenantId, null); -// String parentTenantId = (String)session.getAttribute(UserSession.parentTenantId); -// if(StringUtils.isNotBlank(parentTenantId)){ -// session.removeAttribute(UserSession.parentTenantId); -// } - } - return authenticationInfo; } diff --git a/suimangAdmin/src/main/java/com/iformall/shiro/PasswordHelper.java b/suimangAdmin/src/main/java/com/iformall/shiro/PasswordHelper.java index 73b38e4..2f4f409 100644 --- a/suimangAdmin/src/main/java/com/iformall/shiro/PasswordHelper.java +++ b/suimangAdmin/src/main/java/com/iformall/shiro/PasswordHelper.java @@ -23,8 +23,8 @@ public class PasswordHelper { public static void main(String[] args) { MallUserInfo user = new MallUserInfo(); - user.setUsername("fmoperator"); - user.setPassword("fm202008admin"); + user.setUsername("localtest"); + user.setPassword("123456"); PasswordHelper passwordHelper = new PasswordHelper(); passwordHelper.encryptPassword(user); System.out.println(user); diff --git a/suimangAdmin/src/main/resources/application-dev.yml b/suimangAdmin/src/main/resources/application-dev.yml index 7cc67eb..4d7128f 100644 --- a/suimangAdmin/src/main/resources/application-dev.yml +++ b/suimangAdmin/src/main/resources/application-dev.yml @@ -200,4 +200,32 @@ ueditor: logging: level: com.iformall: debug - path: ./logs/admin \ No newline at end of file + path: ./logs/admin + +suimang: + oral_broadcasting: http://nas.pucao.cn:50014 + callbackUrl: https://mtest.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://nas.pucao.cn:50015 + photo_speak_hy: http://nas.pucao.cn:50013 + digital_avatar: http://nas.pucao.cn:2005 + digital_avatar_hy: http://nas.pucao.cn:2003 + local_deploy: true + token: fm2023 +sdk: + sm: + base-url: https://mtest.metavatar.cc/public +swagger: + base-package: com.iformall.controller + title: 遂芒_metavatar_接口文档 + description: 前后端联调 + version: 1.0 + license: Apache + license-url: https://mtest.metavatar.cc/ + terms-of-service-url: https://mtest.metavatar.cc/ + host: localhost:8888 + contact: + name: 张三 + url: https://mtest.metavatar.cc/ + email: zhangsan@163.com \ No newline at end of file diff --git a/suimangAdmin/src/main/resources/application-prod.yml b/suimangAdmin/src/main/resources/application-prod.yml index f2849f4..1cc280a 100644 --- a/suimangAdmin/src/main/resources/application-prod.yml +++ b/suimangAdmin/src/main/resources/application-prod.yml @@ -156,4 +156,19 @@ ueditor: logging: level: com.iformall.mapper: debug - path: ./logs/admin \ No newline at end of file + path: ./logs/admin + +suimang: + oral_broadcasting: http://111.198.0.15:22266 + callbackUrl: https://neuver.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://111.198.0.15:22299 + photo_speak_hy: http://111.198.0.15:22288 + digital_avatar: http://111.198.0.15:22200 + digital_avatar_hy: http://*****:2003 + local_deploy: false + token: fm2023 +sdk: + sm: + base-url: https://test.metavatar.cc/public \ No newline at end of file diff --git a/suimangAdmin/src/main/resources/application.yml b/suimangAdmin/src/main/resources/application.yml index 8a81cd8..85d85e6 100644 --- a/suimangAdmin/src/main/resources/application.yml +++ b/suimangAdmin/src/main/resources/application.yml @@ -1,7 +1,7 @@ server: port: 9500 servlet: - context-path: / + context-path: /A spring: application: diff --git a/suimangAdmin/src/main/resources/db/migration/V2023101600001_update.sql b/suimangAdmin/src/main/resources/db/migration/V2023101600001_update.sql new file mode 100644 index 0000000..a7034a5 --- /dev/null +++ b/suimangAdmin/src/main/resources/db/migration/V2023101600001_update.sql @@ -0,0 +1,2 @@ +ALTER TABLE `mallink_suimang`.`wx_third_party_api` +ADD COLUMN `phone` varchar(11) NOT NULL COMMENT '用户会员手机号' AFTER `parent_tenant_id`; \ No newline at end of file diff --git a/suimangAdmin/src/main/resources/db/migration/V2023110300001_personmould.sql b/suimangAdmin/src/main/resources/db/migration/V2023110300001_personmould.sql new file mode 100644 index 0000000..8d66f86 --- /dev/null +++ b/suimangAdmin/src/main/resources/db/migration/V2023110300001_personmould.sql @@ -0,0 +1,80 @@ +ALTER TABLE `person_mould` +ADD COLUMN customized int(1) NOT NULL DEFAULT 0 COMMENT '是否私人定制EnumYesOrNo' AFTER `is_del`; + +##更新这几个表 +apimenu,apiguide,apidetail,thirdpartyapi + +ALTER TABLE `voice_language` +ADD COLUMN customized int(1) NOT NULL DEFAULT 0 COMMENT '是否私人定制EnumYesOrNo' AFTER `is_del`; + + +ALTER TABLE `user_mould_video` +ADD COLUMN cost_points int(11) NOT NULL DEFAULT 0 COMMENT '消耗金币' ; +ALTER TABLE `user_mould_video` +ADD COLUMN cost_points_detail varchar(500) COMMENT '消耗金币明细' ; + + +ALTER TABLE `service_info` +ADD COLUMN mall_user_info bigint COMMENT '登录用户编号' ; + + +ALTER TABLE `mall_user_info` +ADD COLUMN project_type int(1) NOT NULL COMMENT '所属项目EnumProject' ; + + +ALTER TABLE wx_msg_validationcode +ADD COLUMN project_type int(1) NOT NULL COMMENT '所属项目EnumProject' ; + +ALTER TABLE service_info +ADD COLUMN remaining_times bigint NOT NULL DEFAULT 0 COMMENT '剩余时长(秒)' ; + +CREATE TABLE `service_person_mould` ( + `id` bigint NOT NULL COMMENT '主键ID', + `person_mould_id` bigint NOT NULL COMMENT 'PersonMould编号', + `service_id` bigint NOT NULL COMMENT 'ServiceInfo编码', + `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间' + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `id_UNIQUE` (`id`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='接入方关联模板'; + +ALTER TABLE `service_video_record` +ADD COLUMN video_url varchar(300) COMMENT '视频链接'; + + +#wx_c_author 新增了user_name + +CREATE TABLE `user_person_mould` ( + `id` bigint NOT NULL COMMENT '主键ID', + `person_mould_id` bigint NOT NULL COMMENT 'PersonMould编号', + `c_user_id` bigint NOT NULL COMMENT 'WxCuserBasicInfo编码', + `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间' + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `id_UNIQUE` (`id`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户定制关联模板'; + +CREATE TABLE `user_voice_language` ( + `id` bigint NOT NULL COMMENT '主键ID', + `voice_language_id` bigint NOT NULL COMMENT 'VocieLanguage编码', + `c_user_id` bigint NOT NULL COMMENT 'WxCuserBasicInfo编码', + `create_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + `update_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (`id`) USING BTREE, + UNIQUE KEY `id_UNIQUE` (`id`) USING BTREE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户定制关联声纹'; + +ALTER TABLE `service_video_record` +ADD COLUMN user_mould_video_id bigint NOT NULL COMMENT '视频记录ID'; + +ALTER TABLE `voice_language` +ADD COLUMN trial_text varchar(100) COMMENT '试听文本内容'; + +UPDATE voice_language SET trial_text = '遂芒数字人,用人工智能创造无限可能!' WHERE id IN (38,39,43,45,55,77,96,107,123,140) +UPDATE voice_language SET trial_text = 'Metavatar, AI to create infinite possibilities!' WHERE id IN (144,26,86,118,29) +UPDATE voice_language SET trial_text = ' ¡¡ el hombre digital suimang crea infinitas posibilidades con inteligencia artificial!' WHERE id IN (61) +UPDATE voice_language SET trial_text = 'Manusia Digital Suimang, Membuat kemungkinan tak terhingga dengan Intelijen Seni!' WHERE id IN (11) +UPDATE voice_language SET trial_text = 'Manusia Digital Suimang, Mencipta kemungkinan tak terbatas dengan Intelligence Artificial!' WHERE id IN (5) + +ALTER TABLE `api_menu` +ADD COLUMN content text COMMENT '内容'; diff --git a/suimangCApi/.gitignore b/suimangCApi/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangCApi/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangCApi/src/main/java/com/iformall/CApplication.java b/suimangCApi/src/main/java/com/iformall/CApplication.java index d916e1b..32fda08 100644 --- a/suimangCApi/src/main/java/com/iformall/CApplication.java +++ b/suimangCApi/src/main/java/com/iformall/CApplication.java @@ -1,5 +1,6 @@ package com.iformall; +import com.iformall.annotation.BaseEnableSwagger; import org.mybatis.spring.annotation.MapperScan; import org.rocketmq.starter.annotation.EnableRocketMQ; import org.springframework.beans.factory.annotation.Value; @@ -15,6 +16,7 @@ import org.springframework.scheduling.annotation.EnableAsync; * @author chenkx * @date 2017-12-26 */ +@BaseEnableSwagger @SpringBootApplication @MapperScan(basePackages = {"com.iformall.mapper"}) @EnableEncryptableProperties diff --git a/suimangCApi/src/main/java/com/iformall/config/Swagger2Config.java b/suimangCApi/src/main/java/com/iformall/config/Swagger2Config.java index 2118b9d..6d22331 100644 --- a/suimangCApi/src/main/java/com/iformall/config/Swagger2Config.java +++ b/suimangCApi/src/main/java/com/iformall/config/Swagger2Config.java @@ -1,61 +1,61 @@ -package com.iformall.config; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.ParameterBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.schema.ModelRef; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.service.Parameter; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.paths.RelativePathProvider; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -import javax.servlet.ServletContext; -import java.util.ArrayList; -import java.util.List; - -//参考:http://blog.csdn.net/catoop/article/details/50668896 -@Configuration -@EnableSwagger2 -public class Swagger2Config { - - @Autowired - private ServletContext servletContext; - - @Bean - public Docket createRestApi() { - ParameterBuilder tokenPar = new ParameterBuilder(); - List pars = new ArrayList(); - //增加一个request的header参数 - tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); - pars.add(tokenPar.build()); - return new Docket(DocumentationType.SWAGGER_2) - .apiInfo(apiInfo()) - .select() - .apis(RequestHandlerSelectors.basePackage("com.iformall.controller")) - .paths(PathSelectors.any()) - .build() - .globalOperationParameters(pars) - .pathProvider(new RelativePathProvider(servletContext) { - @Override - public String getApplicationBasePath() { - return "/api"; - } - }); - } - - private ApiInfo apiInfo() { - return new ApiInfoBuilder() - .title("c端 api") - .description("c api") - .termsOfServiceUrl("http://localhost:7000") - .version("2.0") - .build(); - } - -} \ No newline at end of file +//package com.iformall.config; +// +//import org.springframework.beans.factory.annotation.Autowired; +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import springfox.documentation.builders.ApiInfoBuilder; +//import springfox.documentation.builders.ParameterBuilder; +//import springfox.documentation.builders.PathSelectors; +//import springfox.documentation.builders.RequestHandlerSelectors; +//import springfox.documentation.schema.ModelRef; +//import springfox.documentation.service.ApiInfo; +//import springfox.documentation.service.Parameter; +//import springfox.documentation.spi.DocumentationType; +//import springfox.documentation.spring.web.paths.RelativePathProvider; +//import springfox.documentation.spring.web.plugins.Docket; +//import springfox.documentation.swagger2.annotations.EnableSwagger2; +// +//import javax.servlet.ServletContext; +//import java.util.ArrayList; +//import java.util.List; +// +////参考:http://blog.csdn.net/catoop/article/details/50668896 +//@Configuration +//@EnableSwagger2 +//public class Swagger2Config { +// +// @Autowired +// private ServletContext servletContext; +// +// @Bean +// public Docket createRestApi() { +// ParameterBuilder tokenPar = new ParameterBuilder(); +// List pars = new ArrayList(); +// //增加一个request的header参数 +// tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); +// pars.add(tokenPar.build()); +// return new Docket(DocumentationType.SWAGGER_2) +// .apiInfo(apiInfo()) +// .select() +// .apis(RequestHandlerSelectors.basePackage("com.iformall.controller")) +// .paths(PathSelectors.any()) +// .build() +// .globalOperationParameters(pars) +// .pathProvider(new RelativePathProvider(servletContext) { +// @Override +// public String getApplicationBasePath() { +// return "/api"; +// } +// }); +// } +// +// private ApiInfo apiInfo() { +// return new ApiInfoBuilder() +// .title("c端 api") +// .description("c api") +// .termsOfServiceUrl("http://localhost:7000") +// .version("2.0") +// .build(); +// } +// +//} \ No newline at end of file diff --git a/suimangCApi/src/main/java/com/iformall/config/WebMvcConfig.java b/suimangCApi/src/main/java/com/iformall/config/WebMvcConfig.java index c406405..66deea2 100644 --- a/suimangCApi/src/main/java/com/iformall/config/WebMvcConfig.java +++ b/suimangCApi/src/main/java/com/iformall/config/WebMvcConfig.java @@ -54,7 +54,9 @@ public class WebMvcConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html") +// registry.addResourceHandler("swagger-ui.html") +// .addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("doc.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); diff --git a/suimangCApi/src/main/java/com/iformall/controller/ApiGuideController.java b/suimangCApi/src/main/java/com/iformall/controller/ApiGuideController.java new file mode 100644 index 0000000..3ff2abf --- /dev/null +++ b/suimangCApi/src/main/java/com/iformall/controller/ApiGuideController.java @@ -0,0 +1,32 @@ +package com.iformall.controller; + +import com.iformall.annotation.ApiVersion; +import com.iformall.annotation.AuthIgnore; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.domain.po.sm.ApiGuide; +import com.iformall.service.sm.ApiGuideService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/apiGuide") +@Api(tags = "api指南接口") +public class ApiGuideController { + + @Autowired + private ApiGuideService apiGuideService; + + @AuthIgnore + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询api指南") + @GetMapping("/getAvailableApiGuide") + public R getAvailableApiGuide() { + return R.ok(apiGuideService.getAvailableApiGuide()); + } +} diff --git a/suimangCApi/src/main/java/com/iformall/controller/ApiMenuController.java b/suimangCApi/src/main/java/com/iformall/controller/ApiMenuController.java new file mode 100644 index 0000000..2ebc8f0 --- /dev/null +++ b/suimangCApi/src/main/java/com/iformall/controller/ApiMenuController.java @@ -0,0 +1,46 @@ +package com.iformall.controller; + +import com.iformall.annotation.ApiVersion; +import com.iformall.annotation.AuthIgnore; +import com.iformall.common.ErrorCode; +import com.iformall.common.R; +import com.iformall.common.ResultData; +import com.iformall.constant.SwaggerConstant; +import com.iformall.domain.po.sm.ApiMenu; +import com.iformall.domain.vo.sm.ListApiSubmenuVO; +import com.iformall.exception.BizException; +import com.iformall.service.sm.ApiMenuService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/api/apiMenu") +@Api(tags = "api菜单接口") +public class ApiMenuController { + + @Autowired + private ApiMenuService apiMenuService; + + @AuthIgnore + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("全查询api菜单") + @GetMapping("/list") + public R> listApiMenu() { + return R.ok(apiMenuService.listMenu()); + } + + @AuthIgnore + @ApiVersion(group = SwaggerConstant.V_1_0_0) + @ApiOperation("单个查询菜单详情") + @GetMapping("/get") + public R getApiMenu(Long id) { + if (id == null) { + throw new BizException(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + return R.ok(apiMenuService.getApiMenu(id)); + } +} diff --git a/suimangCApi/src/main/java/com/iformall/controller/BaiduController.java b/suimangCApi/src/main/java/com/iformall/controller/BaiduController.java index 8a68a7b..dac5d0a 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/BaiduController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/BaiduController.java @@ -10,7 +10,7 @@ import com.iformall.enums.EnumMouldSendType; import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.PersonPhotoService; -import com.iformall.utils.BaiduImageCheckUtil; +import com.iformall.utils.BaiduCheckUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -45,7 +45,18 @@ public class BaiduController extends BaseController { if (size > length) { return new ResultData(ErrorCode.PICTURE_FOUR_SIZE_EXCEED); } - return BaiduImageCheckUtil.photoCheck(file); + return BaiduCheckUtil.photoCheck(file); + } + + @AuthIgnore + @ApiOperation("百度文字审核接口") + @PostMapping(value = "checkText") + @ApiImplicitParam(name = "text", value = "text", dataType = "String", paramType = "query", required = true) + public ResultData baiduCheckPhoto(@RequestBody String text) { + if (StringUtils.isBlank(text)) { + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "内容为空"); + } + return BaiduCheckUtil.textCheck(text); } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/BaseController.java b/suimangCApi/src/main/java/com/iformall/controller/BaseController.java index 571c475..02a9ece 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/BaseController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/BaseController.java @@ -130,4 +130,12 @@ public class BaseController { return ipaddress; } + public Integer getPoins() { + WxCUserBasicInfo cuser = getCUser(); + WxCUserBasicInfo newcuser = wxCUserBasicInfoService.getById(cuser.getId(), cuser.getFinalTenantId()); + if (newcuser == null) { + throw new MallinkException(ErrorCode.USER_IS_EMPTY); + } + return newcuser.getPoins(); + } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/CallbackPayController.java b/suimangCApi/src/main/java/com/iformall/controller/CallbackPayController.java index ac407fc..53a1966 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/CallbackPayController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/CallbackPayController.java @@ -5,9 +5,13 @@ import com.github.binarywang.wxpay.v3.util.AesUtils; import com.iformall.annotation.AuthIgnore; import com.iformall.common.ErrorCode; import com.iformall.domain.po.ProductOrder; +import com.iformall.domain.po.ProductOrderPay; import com.iformall.domain.po.WxAppinfo; import com.iformall.domain.po.WxPayAccount; import com.iformall.enums.EnumAppPlat; +import com.iformall.enums.EnumProductOrderPayVendor; +import com.iformall.interceptor.BodyReaderHttpServletRequestWrapper; +import com.iformall.service.ProductOrderPayService; import com.iformall.service.ProductOrderService; import com.iformall.service.WxAppinfoService; import com.iformall.service.WxPayAccountService; @@ -15,6 +19,7 @@ import com.iformall.service.pay.PayServiceFactory; import com.iformall.service.pay.service.pay.PayAdapterService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import org.apache.commons.lang3.StringUtils; import org.jdom2.JDOMException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,8 +28,12 @@ import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; import java.util.HashMap; +import java.util.Iterator; import java.util.Map; @@ -41,7 +50,7 @@ public class CallbackPayController extends BaseController { private WxPayAccountService wxPayAccountService; @Autowired - private ProductOrderService productOrderService; + private ProductOrderPayService productOrderPayService; @Autowired private PayServiceFactory payServiceFactory; @@ -49,7 +58,8 @@ public class CallbackPayController extends BaseController { @AuthIgnore @ApiOperation("支付回调") @PostMapping(value = "{projectType}/pay/v3") - public void _payV3Notify(@PathVariable Integer projectType,@RequestBody Map paranMap, HttpServletResponse response) { + public void _payV3Notify(@PathVariable Integer projectType, @RequestBody Map paranMap, + HttpServletRequest request, HttpServletResponse response) { logger.debug("[" + getIpAddr() + "] CallbackPayController::_payV3Notify"); logger.info("微信支付回调结果通知{}"+JSONObject.toJSONString(paranMap)); /** @@ -69,14 +79,34 @@ public class CallbackPayController extends BaseController { logger.info("微信支付回调解密数据{}"+decryptString); JSONObject jsonObject = JSONObject.parseObject(decryptString); String out_order_no = jsonObject.getString("out_trade_no"); + /** + * 交易类型,枚举值: + * JSAPI:公众号支付 + * NATIVE:扫码支付 + * App:App支付 + * MICROPAY:付款码支付 + * MWEB:H5支付 + * FACEPAY:刷脸支付 + */ + String trade_type = jsonObject.getString("trade_type"); + EnumProductOrderPayVendor payVendorEnum = null; + if("JSAPI".equals(trade_type)){ + payVendorEnum = EnumProductOrderPayVendor.PAY_WAY_WECHAT; + }else if("NATIVE".equals(trade_type)){ + payVendorEnum = EnumProductOrderPayVendor.PAY_WAY_WECHAT_NATIVE; + } + if(payVendorEnum == null){ + logger.error("微信支付回调处理支付方式异常{}"+trade_type); + response.setStatus(ErrorCode.SYS_SERVER_ERROR.getCode()); + } - ProductOrder productOrder = productOrderService.getById(Long.parseLong(out_order_no)); + ProductOrderPay orderPay = productOrderPayService.getByOrder(Long.parseLong(out_order_no), payVendorEnum); - PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(productOrder.getPayVendor()); - productOrderService.handleProductOrderByQuery(appInfo,payAccount,productOrder,payAdapterService); + PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(payVendorEnum.getCode()); + productOrderPayService.handleProductOrderByQuery(appInfo,payAccount,orderPay,payAdapterService); response.setStatus(200); }catch(Exception e){ - logger.error("微信支付回调处理异常"+e); + logger.error("微信支付回调处理异常{}"+e); response.setStatus(ErrorCode.SYS_SERVER_ERROR.getCode()); } @@ -84,8 +114,9 @@ public class CallbackPayController extends BaseController { @AuthIgnore @ApiOperation("支付回调") - @PostMapping(value = "/ttNotify") - public Map _ttNotify(@RequestBody Map paranMap, HttpServletRequest request, HttpServletResponse response) { + @PostMapping(value = "{projectType}/ttNotify") + public Map _ttNotify(@PathVariable Integer projectType, @RequestBody Map paranMap, + HttpServletRequest request, HttpServletResponse response) { logger.debug("[" + getIpAddr() + "] CallbackPayController::_ttNotify"); Map resultMap = new HashMap<>(); logger.info("抖音支付回调结果通知{}"+JSONObject.toJSONString(paranMap)); @@ -93,30 +124,91 @@ public class CallbackPayController extends BaseController { * ----效验数据来源合法 */ try{ - String msg = (String) paranMap.get("msg"); - String type = (String) paranMap.get("type"); +// String msg = (String) paranMap.get("msg"); +// String type = (String) paranMap.get("type"); +// +// Map pMap = JSONObject.parseObject(msg, Map.class); +//// String appid = (String) pMap.get("appid"); +//// WxAppinfo appInfo = wxAppinfoService.getOnlyByAppIdFromRedis(appid); +// WxAppinfo appInfo = wxAppinfoService.getProjectCAppInfoFromRedis(projectType, EnumAppPlat.TOUTIAO.getCode()); +// WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); +// if("payment".equals(type)){ +// String out_order_no = (String)pMap.get("cp_orderno"); +// +// EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.PAY_WAY_TT; +// ProductOrderPay orderPay = productOrderPayService.getByOrder(Long.parseLong(out_order_no), payVendorEnum); +// +// PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(payVendorEnum.getCode()); +// productOrderPayService.handleProductOrderByQuery(appInfo,payAccount,orderPay,payAdapterService); +// +// resultMap.put("err_no",0); +// resultMap.put("err_tips","success"); +// } + resultMap.put("err_no",0); + resultMap.put("err_tips","success"); + }catch(Exception e){ + logger.error("抖音支付回调处理异常"+e); + resultMap.put("err_no",ErrorCode.SYS_SERVER_ERROR.getCode()); + resultMap.put("err_tips","抖音支付回调处理异常"); + } + return resultMap; + } - Map pMap = JSONObject.parseObject(msg, Map.class); - String appid = (String) pMap.get("appid"); - WxAppinfo appInfo = wxAppinfoService.getOnlyByAppIdFromRedis(appid); - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); - if("payment".equals(type)){ - String out_order_no = (String)pMap.get("cp_orderno"); + @AuthIgnore + @ApiOperation("支付回调") + @PostMapping(value = "{projectType}/aliNotify") + public String _aliNotify(@PathVariable Integer projectType, + HttpServletRequest request, HttpServletResponse response) { + logger.debug("[" + getIpAddr() + "] CallbackPayController::_aliNotify"); + + String body = ((BodyReaderHttpServletRequestWrapper) request).getBody(); + + logger.info("ali支付回调结果通知 body{}"+body); + + Map resultMap = new HashMap<>(); - ProductOrder productOrder = productOrderService.getById(Long.parseLong(out_order_no)); + /** + * ----效验数据来源合法 + */ + try{ + Map paranMap = handBody(body); + logger.info("ali支付回调结果通知 paranMap{}"+JSONObject.toJSONString(paranMap)); - PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(productOrder.getPayVendor()); - productOrderService.handleProductOrderByQuery(appInfo,payAccount,productOrder,payAdapterService); +// String app_id = paranMap.get("app_id"); +// WxAppinfo appInfo = wxAppinfoService.getOnlyByAppIdFromRedis(app_id); + WxAppinfo appInfo = wxAppinfoService.getProjectCAppInfoFromRedis(projectType, EnumAppPlat.ALI.getCode()); + WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); + + String out_trade_no = paranMap.get("out_trade_no"); + String trade_status = paranMap.get("trade_status"); + if("TRADE_SUCCESS".equals(trade_status)){ + EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.PAY_WAY_ALIPAY_WAP; + ProductOrderPay orderPay = productOrderPayService.getByOrder(Long.parseLong(out_trade_no), payVendorEnum); - resultMap.put("err_no",0); - resultMap.put("err_tips","success"); + PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(payVendorEnum.getCode()); + productOrderPayService.handleProductOrderByQuery(appInfo,payAccount,orderPay,payAdapterService); } + return "success"; }catch(Exception e){ - logger.error("抖音支付回调处理异常"+e); - resultMap.put("err_no",ErrorCode.SYS_SERVER_ERROR.getCode()); - resultMap.put("err_tips","抖音支付回调处理异常"); + logger.error("ali支付回调处理异常"+e); } - return resultMap; + return "fail"; + } + + + + private Map handBody(String body){ + Map map = new HashMap<>(); + if(StringUtils.isNotBlank(body)){ + String[] key_value = body.split("&"); + if(key_value.length > 0){ + for (String kv: key_value) { + String[] split = kv.split("="); + map.put(split[0],split[1]); + } + } + } + return map; } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/CallbackSmController.java b/suimangCApi/src/main/java/com/iformall/controller/CallbackSmController.java index 89b0d23..b5dc908 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/CallbackSmController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/CallbackSmController.java @@ -1,6 +1,7 @@ package com.iformall.controller; import com.alibaba.fastjson.JSONObject; +import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON; import com.iformall.annotation.AuthIgnore; import com.iformall.common.ErrorCode; import com.iformall.common.ResultData; @@ -20,6 +21,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.io.InputStream; +import java.math.BigDecimal; import java.util.*; @@ -63,11 +65,10 @@ public class CallbackSmController extends BaseController { videoUnd.setId(userMouldVideo.getId()); if("1000".equals(code)){ Map data = (Map) paranMap.get("data"); - Map data1 = (Map) data.get("data"); - Map video = (Map) data1.get("video"); + Map video = (Map) data.get("video"); String url = (String) video.get("url"); - Double duration = (Double) video.get("duration"); - + //Double duration = (Double) video.get("duration"); + Object duration = video.get("duration"); videoUnd.setVideoStatus(EnumVideoStatus.success.getCode()); videoUnd.setVideoMsg("success"); videoUnd.setVideoPath(url); @@ -84,7 +85,7 @@ public class CallbackSmController extends BaseController { userMouldVideoService.uploadVideo(videoUnd); return new ResultData(); } - + @AuthIgnore @ApiOperation("照片说话 视频回调") @PostMapping(value = "/photo/speak") diff --git a/suimangCApi/src/main/java/com/iformall/controller/MiniAppUserController.java b/suimangCApi/src/main/java/com/iformall/controller/MiniAppUserController.java index b5444c1..deccb1d 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/MiniAppUserController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/MiniAppUserController.java @@ -89,22 +89,17 @@ public class MiniAppUserController extends BaseController { public ResultData login(@RequestBody Map map) { String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] MiniAppUserController::login"); - logger.info("login >>>>>>>>>>>>>>>>>"+map.toString()); Map resultMap = new HashMap(); - + String project = map.get("projectType"); String appId = map.get("appId"); String code = map.get("code"); - //登录凭证不能为空 - if (StringUtils.isBlank(appId)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId不能为空"); - } + if (StringUtils.isBlank(code)) { return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "code不能为空"); } - - WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appId); + WxAppinfo wxAppinfo = getAppInfo(appId,project); if(wxAppinfo == null){ return new ResultData(ErrorCode.APP_ID_NOT_FOUND); } @@ -176,21 +171,19 @@ public class MiniAppUserController extends BaseController { public ResultData loginPhone(@RequestBody Map map) { String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] MiniAppUserController::loginPhone"); - logger.info("loginPhone >>>>>>>>>>>>>>>>>"+map.toString()); + + String project = map.get("projectType"); String appId = map.get("appId"); String openId = map.get("openId"); String encryptedData = map.get("encryptedData"); String iv = map.get("iv"); - if(StringUtils.isBlank(appId)){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); - } if(StringUtils.isBlank(openId)){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "openId 不能为空"); } - WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appId); + WxAppinfo wxAppinfo = getAppInfo(appId,project); if(wxAppinfo == null){ return new ResultData(ErrorCode.APP_ID_NOT_FOUND); } @@ -252,23 +245,20 @@ public class MiniAppUserController extends BaseController { public ResultData loginPhoneCode(@RequestBody Map map, HttpServletResponse response) { String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] MiniAppUserController::loginPhoneCode"); - logger.info("loginPhoneCode >>>>>>>>>>>>>>>>>"+map.toString()); // String phone,String code,String pwd + String project = map.get("projectType"); String appId = map.get("appId"); String openId = map.get("openId"); String phone = map.get("phone"); String code = map.get("code"); - if(StringUtils.isBlank(appId)){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); - } if(StringUtils.isBlank(openId)){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "openId 不能为空"); } - WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appId); + WxAppinfo wxAppinfo = getAppInfo(appId,project); if(wxAppinfo == null){ return new ResultData(ErrorCode.APP_ID_NOT_FOUND); } @@ -290,7 +280,7 @@ public class MiniAppUserController extends BaseController { // check 验证码正确 boolean isValidCode = false; try { - isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code); + isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code,0); } catch (Exception e) { return new ResultData(Result.ERROR, e.getMessage()); } @@ -334,15 +324,13 @@ public class MiniAppUserController extends BaseController { @PostMapping("/getUserQrcode") @ApiOperation(value = "获取二维码", notes = "{\"encryptedData\":\"string\",\"iv\":\"string\"}") public ResultData getUserQrcode(@RequestBody Map map) { - logger.info(map.toString()); + logger.info("getUserQrcode >>>>>>>>>>>>>>>>>"+map.toString()); + + String project = map.get("projectType"); String appId = map.get("appId"); String img = map.get("img"); - if(StringUtils.isBlank(appId)){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); - } - - WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(appId); + WxAppinfo wxAppinfo = getAppInfo(appId,project); if(wxAppinfo == null){ return new ResultData(ErrorCode.APP_ID_NOT_FOUND); } @@ -369,4 +357,21 @@ public class MiniAppUserController extends BaseController { } } + private WxAppinfo getAppInfo(String appId,String project){ + if (StringUtils.isBlank(appId)) { + return null; + } + Integer projectType = null; + if(StringUtils.isNotBlank(project)){ + try{ + projectType = Integer.parseInt(project); + }catch(Exception e){} + } + //兼容处理 + if(projectType == null){ + projectType = EnumProject.PROJECT_5.getCode(); + } + return wxAppinfoService.getProjectCAppInfo(appId,projectType); + } + } diff --git a/suimangCApi/src/main/java/com/iformall/controller/PersonMouldController.java b/suimangCApi/src/main/java/com/iformall/controller/PersonMouldController.java index dcc98a5..a59dccc 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/PersonMouldController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/PersonMouldController.java @@ -11,6 +11,7 @@ import com.iformall.domain.po.sm.UserMouldVideo; import com.iformall.enums.EnumLanguages; import com.iformall.enums.EnumMouldPatchType; import com.iformall.enums.EnumMouldSendType; +import com.iformall.enums.EnumYesOrNo; import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.language.LanguageDetect; import com.iformall.service.sm.MouldPatchService; @@ -20,6 +21,10 @@ import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; + +import java.util.ArrayList; +import java.util.List; + import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -46,7 +51,6 @@ public class PersonMouldController extends BaseController { @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) public ResultData list(@ModelAttribute PersonMould record, Integer pageNum, Integer pageSize) { - logger.debug("[" + getIpAddr() + "] MouldPatchController::list"); if (record == null) record = new PersonMould(); if(record.getVideoType() != null && record.getVideoType().intValue() == -1){ record.setVideoType(null); @@ -60,6 +64,27 @@ public class PersonMouldController extends BaseController { final PageInfo page = personMouldService.cListAsPage(record, pageNum, pageSize); return new ResultData(page); } + + @ApiOperation("分页列表接口") + @GetMapping("loginList") + @ApiImplicitParams({ + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData loginList(@ModelAttribute PersonMould record, Integer pageNum, Integer pageSize) { + if (record == null) record = new PersonMould(); + if(record.getVideoType() != null && record.getVideoType().intValue() == -1){ + record.setVideoType(null); + } + if(record.getSex() != null && record.getSex().intValue() == -1){ + record.setSex(null); + } + record.setStatus(EnumaMouldPatchStatus.put_on.getCode()); + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + record.setCustomizedQuery(EnumYesOrNo.YES.getCode()); + record.setCuserId(getMemberId()); + final PageInfo page = personMouldService.cListAsPage(record, pageNum, pageSize); + return new ResultData(page); + } @AuthIgnore @ApiOperation("根据id查询接口") @@ -71,5 +96,6 @@ public class PersonMouldController extends BaseController { return new ResultData(personMould); } + } diff --git a/suimangCApi/src/main/java/com/iformall/controller/PersonPhotoController.java b/suimangCApi/src/main/java/com/iformall/controller/PersonPhotoController.java index 3ed4fe7..647e89c 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/PersonPhotoController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/PersonPhotoController.java @@ -11,7 +11,7 @@ import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.PersonPhotoService; import com.iformall.sm.AiBaiduCheckResult; -import com.iformall.utils.BaiduImageCheckUtil; +import com.iformall.utils.BaiduCheckUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -109,7 +109,7 @@ public class PersonPhotoController extends BaseController { if (size > length) { return new ResultData(ErrorCode.PICTURE_FOUR_SIZE_EXCEED); } - return BaiduImageCheckUtil.photoCheck(file); + return BaiduCheckUtil.photoCheck(file); } diff --git a/suimangCApi/src/main/java/com/iformall/controller/ProductController.java b/suimangCApi/src/main/java/com/iformall/controller/ProductController.java index abe8dbd..34d6a31 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/ProductController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/ProductController.java @@ -8,11 +8,13 @@ import com.iformall.domain.po.Product; import com.iformall.domain.po.base.BaseEntity; import com.iformall.domain.po.sm.PersonPhoto; import com.iformall.enums.EnumMouldSendType; +import com.iformall.enums.EnumProductType; +import com.iformall.enums.EnumProject; import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.service.ProductService; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.PersonPhotoService; -import com.iformall.utils.BaiduImageCheckUtil; +import com.iformall.utils.BaiduCheckUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -25,6 +27,8 @@ import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import java.util.List; + @RestController @RequestMapping("/api/product") @@ -36,7 +40,7 @@ public class ProductController extends BaseController { private ProductService productService; @AuthIgnore - @ApiOperation("分页列表接口") + @ApiOperation("分页列表接口(仅智象小程序用)") @GetMapping("list") @ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), @@ -50,4 +54,26 @@ public class ProductController extends BaseController { } + @AuthIgnore + @ApiOperation("获取商品列表(通用,将来替换list)") + @GetMapping("list_v1") + @ApiImplicitParams({}) + public ResultData list_v1(@ModelAttribute Product record) { + logger.debug("[" + getIpAddr() + "] ProductController::list_v1"); + if(record.getType() == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"type为空"); + } + Integer projectType = record.getProjectType(); + if(projectType == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"projectType为空"); + } +// if(EnumProductType.product_2.getCode().equals(record.getType())){ +// record.setProjectType(EnumProject.PROJECT_0.getCode()); +// } + record.setSortColumns(BaseEntity.SortField.UpdateDate_DESC); + List listDetail = productService.findListDetail(record, projectType); + return new ResultData(listDetail); + } + + } diff --git a/suimangCApi/src/main/java/com/iformall/controller/ProductOrderController.java b/suimangCApi/src/main/java/com/iformall/controller/ProductOrderController.java index 5a460df..1968d31 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/ProductOrderController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/ProductOrderController.java @@ -1,28 +1,14 @@ package com.iformall.controller; -import com.github.pagehelper.PageInfo; import com.iformall.annotation.AuthIgnore; -import com.iformall.annotation.TenantIgnore; import com.iformall.common.ErrorCode; -import com.iformall.common.Result; import com.iformall.common.ResultData; -import com.iformall.domain.dto.OrderComposeSaveDto; -import com.iformall.domain.dto.OrderSaveDto; import com.iformall.domain.po.*; -import com.iformall.domain.po.base.BaseEntity; -import com.iformall.domain.po.sm.PersonPhoto; +import com.iformall.domain.po.base.BaseEntity.SortField; import com.iformall.enums.*; -import com.iformall.exception.MallinkException; import com.iformall.service.*; import com.iformall.service.pay.PayServiceFactory; -import com.iformall.service.pay.entity.PayExtraParam; import com.iformall.service.pay.service.pay.PayAdapterService; -import com.iformall.sm.AiDigitalAvatarHelper; -import com.iformall.sm.ShareImgParam; -import com.iformall.sm.ShareImgResult; -import com.iformall.utils.Base64Util; -import com.iformall.utils.Constant; -import com.iformall.utils.DateUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; @@ -33,12 +19,6 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - @RestController @RequestMapping("/api/productOrder") @@ -49,6 +29,9 @@ public class ProductOrderController extends BaseController { @Autowired private ProductOrderService productOrderService; + @Autowired + private ProductOrderPayService productOrderPayService; + @Autowired private ProductService productService; @@ -105,10 +88,9 @@ public class ProductOrderController extends BaseController { return new ResultData(record.getOrderNumber()); } - @AuthIgnore @ApiOperation("根据id查询接口") @GetMapping("/findByNumber") - @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true) + @ApiImplicitParam(name = "orderNumber", value = "orderNumber", dataType = "String", paramType = "query", required = true) public ResultData findByNumber(String orderNumber) { logger.debug("[" + getIpAddr() + "] ProductOrderController::findByNumber"); @@ -129,10 +111,9 @@ public class ProductOrderController extends BaseController { return new ResultData(productOrder); } - @AuthIgnore @ApiOperation(value = "创建支付", notes = "") @PostMapping("createPay") - public ResultData createPay(@RequestBody ProductOrder record){ + public ResultData createPay(@RequestBody ProductOrderPay record){ logger.debug("[" + getIpAddr() + "] ProductOrderController::createPay"); String orderNumber = record.getOrderNumber(); String openId = record.getOpenId(); @@ -154,58 +135,60 @@ public class ProductOrderController extends BaseController { } } - Long id = null; + Long orderId = null; try{ - id = Long.parseLong(orderNumber); + orderId = Long.parseLong(orderNumber); }catch (Exception e){ } - if(id == null){ + if(orderId == null){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"订单号异常"); } - ProductOrder productOrder = productOrderService.getById(id); - if(productOrder == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未查询到订单"); - } - - productOrder.setOpenId(openId); - productOrder.setPayVendor(payVendor); - - ResultData resultData = productOrderService.createPay(productOrder); + ResultData resultData = productOrderPayService.createPay(orderId, payVendorEnum, openId); return resultData; + } - @AuthIgnore @ApiOperation("根据id查询接口") @GetMapping("/findStatus") - @ApiImplicitParam(name = "id", value = "id", dataType = "String", paramType = "query", required = true) - public ResultData findStatus(String orderNumber) { + @ApiImplicitParams({ + @ApiImplicitParam(name = "orderNumber", value = "orderNumber", dataType = "String", paramType = "query", required = true), + @ApiImplicitParam(name = "payVendor", value = "payVendor", dataType = "int", paramType = "query", required = true)}) + public ResultData findStatus(String orderNumber,Integer payVendor) { logger.debug("[" + getIpAddr() + "] ProductOrderController::findStatus"); if(StringUtils.isBlank(orderNumber)){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"订单号为空"); } - Long id = null; + Long orderId = null; try{ - id = Long.parseLong(orderNumber); + orderId = Long.parseLong(orderNumber); }catch (Exception e){ } - if(id == null){ + if(orderId == null){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"订单号异常"); } - ProductOrder productOrder = productOrderService.getById(id); - if(productOrder == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未查询到订单"); + //todo 临时兼容处理 该字段不能为空 + if(payVendor == null){ + payVendor = EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode(); +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式为空"); } - if(productOrder.getPayVendor() == null){ - return new ResultData(productOrder); + EnumProductOrderPayVendor payVendoEnum = EnumProductOrderPayVendor.getEnum(payVendor); + if(payVendoEnum == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_TYPE_ERROR.getCode(),"支付方式异常"); } - if(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ - PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(productOrder.getPayVendor()); + + ProductOrderPay orderPay = productOrderPayService.getByOrder(orderId, payVendoEnum); + if(orderPay == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"未查询到支付订单"); + } + + if(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(orderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENTING.getCode().equals(orderPay.getPayOrderStatus())){ + PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(payVendor); if(payAdapterService == null){ return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"该订单不支持当前支付"); } - EnumProductOrderPayVendor payVendoEnum = EnumProductOrderPayVendor.getEnum(productOrder.getPayVendor()); - WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(productOrder.getProjectType(), payVendoEnum.getPlat()); + WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(orderPay.getProjectType(), payVendoEnum.getPlat()); if(appinfo == null){ return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付应用"); } @@ -214,108 +197,131 @@ public class ProductOrderController extends BaseController { return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付密钥"); } - ResultData resultData = productOrderService.handleProductOrderByQuery(appinfo,payAccount,productOrder,payAdapterService); + ResultData resultData = productOrderPayService.handleProductOrderByQuery(appinfo,payAccount,orderPay,payAdapterService); } + ProductOrder order = productOrderService.getById(orderId); - return new ResultData(productOrder); + return new ResultData(order); } - - - @AuthIgnore - @ApiOperation(value = "获取详情链接", notes = "") - @PostMapping("getPayUrl") - public ResultData getPayUrl(@RequestBody ProductOrder record) { - logger.debug("[" + getIpAddr() + "] ProductOrderController::getPayUrl"); - if(StringUtils.isBlank(record.getAppId())){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); - } - WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(record.getAppId()); - if(wxAppinfo == null){ - return new ResultData(ErrorCode.APP_ID_NOT_FOUND); - } - - if(record.getUserId() == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); - } - WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); - if(basicUser == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); - } - - if(record.getProductId() == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); - } - Product product = productService.getById(record.getProductId()); - if(product == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); + + @ApiOperation("根据id查询接口") + @GetMapping("/myPaiedOrders") + @ApiImplicitParams({ + @ApiImplicitParam(name = "projectType", value = "projectType", dataType = "String", paramType = "query", required = true), + @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true), + @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)}) + public ResultData myPaiedOrders(Integer projectType,Integer pageNum,Integer pageSize) { + if(projectType == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_TYPE_ERROR.getCode(),"projectType参数错误"); } - - if(!wxAppinfo.getProjectType().equals(product.getProjectType())){ - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"商品数据异常"); - } - - try { - EnumProject project = EnumProject.getEnum(wxAppinfo.getProjectType()); - EnumAppPlat plat = EnumAppPlat.getByCode(wxAppinfo.getPlat()); - String productScheme = Constant.mainPageUrl; - String sceneParam = "t:dt_p:"+record.getProductId()+"_u:"+record.getUserId(); - Date timeAfterDays = DateUtils.getTimeAfterDays(1, new Date()); - Long expireTime = timeAfterDays.getTime()/1000; - return schemeService.generateScheme(project,plat,productScheme,sceneParam,expireTime); - } catch (MallinkException e) { - return new ResultData(e.getErrorCode(), e.getMessage()); - }catch (Exception e) { - this.logger.error(e.getMessage(), e); - return new ResultData(ErrorCode.SYS_SERVER_ERROR); + EnumProject projectTypeEnum = EnumProject.getEnum(projectType); + if(projectTypeEnum == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_TYPE_ERROR.getCode(),"projectType参数错误"); } + ProductOrder po = new ProductOrder(); + po.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode()); + po.setProjectType(projectType); + po.setUserId(getMemberId()); + po.setSortColumns(SortField.CreateDate_DESC); + return new ResultData(productOrderService.listAsPage(po, pageNum, pageSize)); } - @AuthIgnore - @ApiOperation(value = "创建支付(不验证用户)", notes = "") - @PostMapping("pay") - public ResultData pay(@RequestBody ProductOrder record) { - logger.debug("[" + getIpAddr() + "] ProductOrderController::pay"); - if(record.getPayVendor() == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式为空"); - } - EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.getEnum(record.getPayVendor()); - if(payVendorEnum == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式参数错误"); - } - - if(EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode().equals(record.getPayVendor())){ - if(StringUtils.isBlank(record.getOpenId())){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"openId为空"); - } - } - record.setProfitSharing(payVendorEnum.getProfitSharing()); - - if(record.getUserId() == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); - } - WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); - if(basicUser == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); - } - - if(record.getProductId() == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); - } - Product product = productService.getById(record.getProductId()); - if(product == null){ - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); - } +// @AuthIgnore +// @ApiOperation(value = "获取详情链接", notes = "") +// @PostMapping("getPayUrl") +// public ResultData getPayUrl(@RequestBody ProductOrder record) { +// logger.debug("[" + getIpAddr() + "] ProductOrderController::getPayUrl"); +// if(StringUtils.isBlank(record.getAppId())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "appId 不能为空"); +// } +// WxAppinfo wxAppinfo = wxAppinfoService.getOnlyByAppIdFromRedis(record.getAppId()); +// if(wxAppinfo == null){ +// return new ResultData(ErrorCode.APP_ID_NOT_FOUND); +// } +// +// if(record.getUserId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); +// } +// WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); +// if(basicUser == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); +// } +// +// if(record.getProductId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); +// } +// Product product = productService.getById(record.getProductId()); +// if(product == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); +// } +// +// if(!wxAppinfo.getProjectType().equals(product.getProjectType())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"商品数据异常"); +// } +// +// try { +// EnumProject project = EnumProject.getEnum(wxAppinfo.getProjectType()); +// EnumAppPlat plat = EnumAppPlat.getByCode(wxAppinfo.getPlat()); +// String productScheme = Constant.mainPageUrl; +// String sceneParam = "t:dt_p:"+record.getProductId()+"_u:"+record.getUserId(); +// Date timeAfterDays = DateUtils.getTimeAfterDays(1, new Date()); +// Long expireTime = timeAfterDays.getTime()/1000; +// return schemeService.generateScheme(project,plat,productScheme,sceneParam,expireTime); +// } catch (MallinkException e) { +// return new ResultData(e.getErrorCode(), e.getMessage()); +// }catch (Exception e) { +// this.logger.error(e.getMessage(), e); +// return new ResultData(ErrorCode.SYS_SERVER_ERROR); +// } +// } - record.setProductTitle(product.getTitle()); - record.setProductEnTitle(product.getEnTitle()); - record.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - record.setProjectType(product.getProjectType()); - record.setOrderPrice(product.getSellPriceRmb()); - productOrderService.saveOrUpdate(record); - return productOrderService.createPay(record); - } +// @AuthIgnore +// @ApiOperation(value = "创建支付(不验证用户)", notes = "") +// @PostMapping("pay") +// public ResultData pay(@RequestBody ProductOrder record) { +// logger.debug("[" + getIpAddr() + "] ProductOrderController::pay"); +// if(record.getPayVendor() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式为空"); +// } +// EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.getEnum(record.getPayVendor()); +// if(payVendorEnum == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"支付方式参数错误"); +// } +// +// if(EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode().equals(record.getPayVendor())){ +// if(StringUtils.isBlank(record.getOpenId())){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"openId为空"); +// } +// } +//// record.setProfitSharing(payVendorEnum.getProfitSharing()); +// +// if(record.getUserId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"用户编号为空"); +// } +// WxCUserBasicInfo basicUser = wxCUserBasicInfoService.getById(record.getUserId()); +// if(basicUser == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到用户"); +// } +// +// if(record.getProductId() == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"商品编号为空"); +// } +// Product product = productService.getById(record.getProductId()); +// if(product == null){ +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(),"未查询到商品"); +// } +// +// record.setProductTitle(product.getTitle()); +// record.setProductEnTitle(product.getEnTitle()); +// record.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); +// record.setProjectType(product.getProjectType()); +// record.setOrderPrice(product.getSellPriceRmb()); +// productOrderService.saveOrUpdate(record); +// +// return productOrderService.createPay(record); +// } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/SDKController.java b/suimangCApi/src/main/java/com/iformall/controller/SDKController.java index ffa7031..d53b70d 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/SDKController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/SDKController.java @@ -1,14 +1,9 @@ package com.iformall.controller; -import com.alibaba.fastjson.JSONArray; - import com.alibaba.fastjson.JSONObject; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonObject; import com.iformall.annotation.AuthIgnore; import com.iformall.common.ErrorCode; import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCVoiceTable; import com.iformall.domain.po.sm.PhotoSpeakVideo; import com.iformall.domain.po.sm.PreviewParam; import com.iformall.enums.EnumVideoStatus; @@ -82,7 +77,7 @@ public class SDKController extends BaseController { param.setVoice_style(previewParam.getVoiceStyle()); param.setGen_txt(previewParam.getGenTxt()); param.setGender(previewParam.getGender()); - return new ResultData(voiceInfoService.voicePreview(param)); + return new ResultData(voiceInfoService.previewVoice(param)); } @ApiOperation("生成视频") diff --git a/suimangCApi/src/main/java/com/iformall/controller/UserLiveController.java b/suimangCApi/src/main/java/com/iformall/controller/UserLiveController.java index 3b58187..dcf8ebf 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/UserLiveController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/UserLiveController.java @@ -77,6 +77,7 @@ public class UserLiveController extends BaseController { @Autowired private WxCUserAuthorityService wxCUserAuthorityService; + @Autowired private VoiceInfoService voiceInfoService; @@ -85,43 +86,44 @@ public class UserLiveController extends BaseController { @PostMapping("/login") @ApiOperation(value = "用户登录", notes = "{\"username\":\"string\",\"password\":\"string\",\"code\":\"string\",\"status\":\"int\"}") public Map login(@RequestBody Map map, HttpServletResponse response) { - Map wxCLiveLoginVos = new HashMap<>(); String ipAddr = getIpAddr(); logger.debug("[" + ipAddr + "] WxUserGrantController::login"); + + Map resultMap = new HashMap<>(); + HashMap status = new HashMap<>(); + + String code = map.get("code"); String phone = map.get("username"); String password = map.get("password"); + if (StringUtils.isBlank(phone) || StringUtils.isBlank(password)) { - HashMap status = new HashMap<>(); status.put("code", ErrorCode.SYS_PARAMETER_ERROR.getCode()); status.put("message", "手机号或密码为空"); - wxCLiveLoginVos.put("status", status); - return wxCLiveLoginVos; + resultMap.put("status", status); + return resultMap; } WxCUserBasicInfo basicInfo = wxCUserBasicInfoService.findInfoByPhone(getTenantInfo(), phone); if (basicInfo == null) { - HashMap status = new HashMap<>(); status.put("code", ErrorCode.USER_IS_EMPTY); status.put("message", "用户不存在"); - wxCLiveLoginVos.put("status", status); - return wxCLiveLoginVos; + resultMap.put("status", status); + return resultMap; } String encryptPassword = new PasswordHelper().encryptPassword(password); if (!encryptPassword.equals(basicInfo.getPassword())) { - HashMap status = new HashMap<>(); status.put("code", ErrorCode.USER_PASSWD_ERR.getCode()); status.put("message", "手机号或密码错误"); - wxCLiveLoginVos.put("status", status); - return wxCLiveLoginVos; + resultMap.put("status", status); + return resultMap; } int statu = Integer.parseInt(map.get("status")); if (statu == 0) { WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(basicInfo.getId()); - if (basicLiveInfo.getCode() != null && !map.get("code").equals(basicLiveInfo.getCode())) { - HashMap status = new HashMap<>(); + if (basicLiveInfo.getCode() != null && !basicLiveInfo.getCode().equals(code)) { status.put("code", ErrorCode.USER_ALREADY_LOGIN.getCode()); status.put("message", "用户已在其他设备登录"); - wxCLiveLoginVos.put("status", status); - return wxCLiveLoginVos; + resultMap.put("status", status); + return resultMap; } if (basicLiveInfo.getCode() == null) { wxCLiveUserBasicInfoService.updateCode(basicInfo.getId(), map.get("code")); @@ -130,37 +132,28 @@ public class UserLiveController extends BaseController { if (statu == -1) { wxCLiveUserBasicInfoService.updateCode(basicInfo.getId(), null); basicInfo.setStatus(-2); - HashMap status = new HashMap<>(); status.put("code", ErrorCode.USER_CANCEL_MCODE.getCode()); status.put("message", "设备已注销"); - wxCLiveLoginVos.put("status", status); - return wxCLiveLoginVos; + resultMap.put("status", status); + return resultMap; } wxCUserBasicInfoService.handleLoginUser(basicInfo); WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(basicInfo.getId()); - WxCLiveLoginVo wxCLiveLoginVo = new WxCLiveLoginVo(); - wxCLiveLoginVo.setCode(map.get("code")); - wxCLiveLoginVo.setUsername(map.get("username")); - Map info = new HashMap(); + Map data = new HashMap(); - Map status = new HashMap<>(); - status.put("code", 1000); - status.put("message", "success"); - data.put("token", basicInfo.getToken()); + data.put("username",basicInfo.getPhone()); data.put("status", 0); data.put("version", basicLiveInfo.getVersion()); data.put("current_time", new Date(System.currentTimeMillis() / 1000)); data.put("expire_time", basicLiveInfo.getExpireTime().getTime() / 1000); - info.put("log_id", basicInfo.getId()); - info.put("server_type", "user login"); - info.put("username", basicInfo.getPhone()); - wxCLiveLoginVos.put("data", data); - wxCLiveLoginVos.put("info", info); - wxCLiveLoginVo.setData(data); - wxCLiveLoginVo.setInfo(info); - wxCLiveLoginVos.put("status", status); - System.out.println("wxCLiveLoginVo.getToken() = " + wxCLiveLoginVo.getToken()); - return wxCLiveLoginVos; + data.put("token", basicInfo.getToken()); + resultMap.put("data", data); + + status.put("code", 1000); + status.put("message", "success"); + resultMap.put("status", status); + + return resultMap; } /** @@ -170,24 +163,30 @@ public class UserLiveController extends BaseController { @PostMapping("/avatarList") @ApiOperation(value = "视频模板列表", notes = "{\"username\",\"string\",\"code\",\"string\"}") public Map avatarList(@RequestBody Map params) throws Exception { - Map avatarVos = new HashMap<>(); String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] WxUserGrantController::getAvatarList"); - Long id = getMemberId(); + + Map resultMap = new HashMap<>(); + HashMap status = new HashMap<>(); + + String code = params.get("code"); + Long userId = getMemberId(); //鉴权 - WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(id); - if (basicLiveInfo.getCode() != null && !params.get("code").equals(basicLiveInfo.getCode())) { - HashMap status = new HashMap<>(); + WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(userId); + if (basicLiveInfo.getCode() != null && !basicLiveInfo.getCode().equals(code)) { status.put("code", ErrorCode.USER_ALREADY_LOGIN.getCode()); status.put("message", "用户已在其他设备登录"); - avatarVos.put("status", status); - return avatarVos; + resultMap.put("status", status); + return resultMap; } - Map status = new HashMap<>(); + + Map data = wxCVideoService.getById(userId); + resultMap.put("data", data); + status.put("code", 1000); status.put("msg", "success"); - avatarVos.put("status", status); - return wxCVideoService.getById(id); + resultMap.put("status", status); + return resultMap; } @@ -198,77 +197,134 @@ public class UserLiveController extends BaseController { @PostMapping("/audioList") @ApiOperation(value = "音频模板列表", notes = "{\"username\",\"string\",\"code\",\"string\"}") public Map audioList(@RequestBody Map params) { - Map resultMap = new HashMap<>(); String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] WxUserGrantController::getAudioList"); - Long id = getMemberId(); - WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(id); - if (basicLiveInfo.getCode() != null && !params.get("code").equals(basicLiveInfo.getCode())) { - HashMap status = new HashMap<>(); + + Map resultMap = new HashMap<>(); + HashMap status = new HashMap<>(); + + String code = params.get("code"); + + Long userId = getMemberId(); + WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(userId); + if (basicLiveInfo.getCode() != null && !basicLiveInfo.getCode().equals(code)) { status.put("code", ErrorCode.USER_ALREADY_LOGIN.getCode()); status.put("message", "用户已在其他设备登录"); resultMap.put("status", status); return resultMap; } - return wxCVoiceService.getById(id,null); + Map data = wxCVoiceService.getById(userId); + resultMap.put("data", data); + + status.put("code", 1000); + status.put("msg", "success"); + resultMap.put("status", status); + return resultMap; } /** * 资源权限查询 */ - - @ApiOperation(value = "资源权限查询", notes = "{\"username\",\"string\",\"code\",\"string\",\"type\",\"int\",\"resource_id\",\"long\"}") @PostMapping("/author") public Map getAuthor(@RequestBody Map params) { - Map resultMap = new HashMap<>(); String ipaddress = getIpAddr(); logger.debug("[" + ipaddress + "] WxUserGrantController::getAuthor"); - Long id = getMemberId(); - WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(id); - if (basicLiveInfo.getCode() != null && !params.get("code").equals(basicLiveInfo.getCode())) { - HashMap status = new HashMap<>(); + + Map resultMap = new HashMap<>(); + HashMap status = new HashMap<>(); + + String code = params.get("code"); + Integer type = Integer.parseInt(params.get("type")); + Long resourceId = Long.valueOf(params.get("resource_id")); + + if(type == null){ + status.put("code", ErrorCode.SYS_PARAMETER_NOT_NULL.getCode()); + status.put("message", "type 为空"); + resultMap.put("status", status); + return resultMap; + } + if(resourceId == null){ + status.put("code", ErrorCode.SYS_PARAMETER_NOT_NULL.getCode()); + status.put("message", "资源ID 为空"); + resultMap.put("status", status); + return resultMap; + } + + Long userId = getMemberId(); + WxCUserBasicInfo basicLiveInfo = wxCLiveUserBasicInfoService.getById(userId); + if (basicLiveInfo.getCode() != null && !basicLiveInfo.getCode().equals(code)) { status.put("code", ErrorCode.USER_ALREADY_LOGIN.getCode()); status.put("message", "用户已在其他设备登录"); resultMap.put("status", status); return resultMap; } - String code = params.get("code"); - Integer type = Integer.parseInt(params.get("type")); - Long resourceId = Long.valueOf(params.get("resource_id")); - return wxCUserAuthorityService.getAuthor(id, code, type, resourceId); + + Map data = wxCUserAuthorityService.getAuthor(userId, code, type, resourceId); + if(data != null){ + resultMap.put("data", data); + + status.put("code", 1000); + status.put("msg", "success"); + resultMap.put("status", status); + return resultMap; + } + + status.put("code", ErrorCode.SYS_NULLPOINTER_ERROR.getCode()); + status.put("msg", "未查询到资源权限"); + resultMap.put("status", status); + return resultMap; } @ApiOperation(value = "tts", notes = "{\"username\",\"string\",\"gen_txt\",\"string\",\"voice_id\",\"string\",\"voice_style\",\"string\",\"speed\",\"int\"}") @PostMapping("/audiotts") public Map voicePreview(@RequestBody Map params) { logger.debug("[" + getIpAddr() + "] UserLiveController::voicePreview"); - Long id = getMemberId(); - AiPreviewParam param = new AiPreviewParam(); - if (params.get("voice_id") == null) { - Map status = new HashMap<>(); - status.put("code", ErrorCode.SYS_SERVER_ERROR.getCode()); + Map resultMap = new HashMap<>(); + HashMap status = new HashMap<>(); + + String voice_id = params.get("voice_id"); + String voiceStyle = params.get("voice_style"); + if (StringUtils.isBlank(voice_id)) { + status.put("code", ErrorCode.SYS_PARAMETER_NOT_NULL.getCode()); status.put("msg", "音色ID不能为空"); - return status; + resultMap.put("status", status); + return resultMap; } - if (StringUtils.isBlank(params.get("gen_txt"))) { - Map status = new HashMap<>(); - status.put("code", ErrorCode.SYS_SERVER_ERROR.getCode()); - status.put("msg", "需要生成的文字不能为空"); - return status; + Long voiceId = null; + try{ + voiceId = Long.parseLong(voice_id); + }catch(Exception e){ + status.put("code", ErrorCode.SYS_PARAMETER_ERROR.getCode()); + status.put("msg", "音色ID参数异常"); + resultMap.put("status", status); + return resultMap; + } + + String text = params.get("gen_txt"); + if (StringUtils.isBlank(text)) { + resultMap.put("code", ErrorCode.SYS_PARAMETER_NOT_NULL.getCode()); + resultMap.put("msg", "需要生成的文字不能为空"); + return resultMap; } - if (Integer.parseInt(params.get("speed")) == -1) { - param.setSpeed(0); + String speedStr = params.get("speed"); + Integer speed = null; + try{ + speed = Integer.parseInt(speedStr); + }catch(Exception e){} + + Map data = wxCVoiceService.voicePreview(voiceId,voiceStyle,text,speed); + if(data != null){ + resultMap.put("data", data); + + status.put("code", 1000); + status.put("msg", "success"); + resultMap.put("status", status); + return resultMap; } - param.setSpeed(Integer.parseInt(params.get("speed"))); - param.setVoice_id(params.get("voice_id")); - param.setVoice_style(params.get("voice_style")); - param.setGen_txt(params.get("gen_txt")); - Map resultMap = wxCVoiceService.voicePreview(param); - Map info = new HashMap<>(); - info.put("log_id", id); - info.put("server_type", "audio tts"); - resultMap.put("info", info); + status.put("code", ErrorCode.SYS_PARAMETER_NOT_NULL.getCode()); + status.put("msg", "获取tts 异常"); + resultMap.put("status", status); return resultMap; } @@ -330,7 +386,6 @@ public class UserLiveController extends BaseController { public ResultData chooseType(Long id) { logger.debug("[" + getIpAddr() + "] MouldPatchController::chooseType"); List voiceInfos = wxCVoiceService.chooseType(id); - System.out.println("voiceInfos = " + voiceInfos); - return new ResultData(wxCVoiceService.chooseType(id)); + return new ResultData(voiceInfos); } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/UserMouldVideoController.java b/suimangCApi/src/main/java/com/iformall/controller/UserMouldVideoController.java index 8598513..d532391 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/UserMouldVideoController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/UserMouldVideoController.java @@ -5,6 +5,7 @@ import com.github.pagehelper.PageInfo; import com.iformall.annotation.AuthIgnore; import com.iformall.common.ErrorCode; import com.iformall.common.ResultData; +import com.iformall.domain.po.WxCUserBasicInfo; import com.iformall.domain.po.base.BaseEntity; import com.iformall.domain.po.sm.MouldPatch; import com.iformall.domain.po.sm.MouldPatchSign; @@ -12,6 +13,7 @@ import com.iformall.domain.po.sm.UserMouldVideo; import com.iformall.domain.po.sm.VoiceInfo; import com.iformall.domain.vo.WxCouponOrderBVo; import com.iformall.enums.EnumMouldSendType; +import com.iformall.enums.EnumProject; import com.iformall.enums.EnumVideoStatus; import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.exception.MallinkException; @@ -19,6 +21,10 @@ import com.iformall.service.sm.MouldPatchService; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.UserMouldVideoService; import com.iformall.service.sm.VoiceInfoService; +import com.iformall.smsdk.SmGenerateVideoDTO; +import com.iformall.smsdk.SmPreviewVideoDTO; +import com.iformall.smsdk.SmSdkUtils; +import com.iformall.utils.BaiduCheckUtil; import com.iformall.video.VideoFactory; import com.iformall.video.entity.VideUploadResult; import io.swagger.annotations.Api; @@ -152,13 +158,26 @@ public class UserMouldVideoController extends BaseController { return userMouldVideoService.saveOrUpdate(record); } - @ApiOperation("生成视频") + + /** + * 私有化部署不使用该接口 + * + * @param record + * @return {@link ResultData} + */ + @ApiOperation("慧影项目生成视频") @PostMapping("createVideo") public ResultData create(@RequestBody UserMouldVideo record) { logger.debug("[" + getIpAddr() + "] MouldPatchController::saveOrUpdate"); if(record.getId() == null){ return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL); } + + //判断当前用户是有金币 + if (this.getPoins() <= 0 ) { + return new ResultData(ErrorCode.MEMBER_NO_POINTS); + } + UserMouldVideo mouldVideo = userMouldVideoService.getById(record.getId()); logger.info("TEST--"+ JSONObject.toJSONString(mouldVideo)); @@ -187,10 +206,40 @@ public class UserMouldVideoController extends BaseController { mouldVideoUpd.setCreateVideoDate(new Date()); userMouldVideoService.saveOrUpdate(mouldVideoUpd); + userMouldVideoService.createVideo(mouldVideo); return new ResultData(); } + + /** + * 校验 + * + * @param record + * @return {@link ResultData} + */ + @ApiOperation("慧影项目生成视频") + @GetMapping("/checkVideo") + @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true) + public ResultData checkVideo(Long id) { + if(id == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL); + } + UserMouldVideo mouldVideo = userMouldVideoService.getById(id); + if(mouldVideo == null){ + return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),"id无效"); + } + //校验文本 + return BaiduCheckUtil.textCheck(mouldVideo.getPaperwork()); + } + +// @AuthIgnore +// @ApiOperation("生成视频") +// @PostMapping("createVideo") +// public ResultData createVideo(@RequestBody UserMouldVideo record) { +// SmSdkUtils.generateVideo(SmGenerateVideoDTO.mapping(record)); +// return new ResultData(); +// } @ApiOperation("根据id查询接口") @GetMapping("/findVideo") @@ -307,5 +356,12 @@ public class UserMouldVideoController extends BaseController { } } + + @ApiOperation("获取视频是否生成成功") + @GetMapping("/checkVideoStatus") + @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true) + public ResultData checkVideoStatus(@RequestParam("list") List list) { + return userMouldVideoService.checkVideoStatus(getMemberId(),list); + } } diff --git a/suimangCApi/src/main/java/com/iformall/controller/VoiceLanguageController.java b/suimangCApi/src/main/java/com/iformall/controller/VoiceLanguageController.java new file mode 100644 index 0000000..8be1722 --- /dev/null +++ b/suimangCApi/src/main/java/com/iformall/controller/VoiceLanguageController.java @@ -0,0 +1,25 @@ +package com.iformall.controller; + +import com.iformall.common.ResultData; +import com.iformall.domain.dto.sm.GetLanguageDTO; +import com.iformall.service.sm.VoiceLanguageService; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/VoiceLanguage") +public class VoiceLanguageController { + + @Autowired + private VoiceLanguageService voiceLanguageService; + + @ApiOperation("根据文案获取语种") + @PostMapping("getLanguage") + public ResultData getLanguage(@RequestBody GetLanguageDTO dto) { + return new ResultData(voiceLanguageService.getLanguage(dto.getPaperwork())); + } +} diff --git a/suimangCApi/src/main/java/com/iformall/controller/VoiceMouldController.java b/suimangCApi/src/main/java/com/iformall/controller/VoiceMouldController.java index 1183855..1dfc5b1 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/VoiceMouldController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/VoiceMouldController.java @@ -3,24 +3,28 @@ package com.iformall.controller; import com.github.pagehelper.PageInfo; import com.iformall.annotation.AuthIgnore; import com.iformall.common.ErrorCode; +import com.iformall.common.Result; import com.iformall.common.ResultData; +import com.iformall.domain.po.ProductOrder; import com.iformall.domain.po.base.BaseEntity; -import com.iformall.domain.po.sm.MouldPatch; import com.iformall.domain.po.sm.PersonMould; import com.iformall.domain.po.sm.UserMouldVideo; +import com.iformall.domain.po.sm.VoiceLanguage; import com.iformall.domain.po.sm.VoiceMould; +import com.iformall.domain.vo.sm.PreviewVoiceVO; import com.iformall.enums.*; import com.iformall.language.LanguageDetect; -import com.iformall.mapper.VoiceLanguageMapper; +import com.iformall.service.ProductOrderService; import com.iformall.service.WxCVoiceService; import com.iformall.service.sm.*; import com.iformall.sm.AiPreviewParam; +import com.iformall.smsdk.SmPreviewVideoDTO; +import com.iformall.smsdk.SmSdkUtils; 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.checkerframework.checker.units.qual.A; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -28,7 +32,6 @@ import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; -import java.util.Map; @RestController @@ -55,6 +58,9 @@ public class VoiceMouldController extends BaseController { @Autowired private WxCVoiceService wxCVoiceService; + @Autowired + private ProductOrderService productOrderService; + @AuthIgnore @ApiOperation("获取语种") @GetMapping("getLanguages") @@ -147,8 +153,17 @@ public class VoiceMouldController extends BaseController { @GetMapping("/voiceTotal") @ApiImplicitParams({}) public ResultData voiceTotal() { - logger.debug("[" + getIpAddr() + "] MouldPatchController::voiceTotal"); - return new ResultData(voiceLanguageService.voiceTotal()); + return new ResultData(voiceLanguageService.voiceTotal(new VoiceLanguage())); + } + + @ApiOperation("登录状态下语言选择下拉框") + @GetMapping("/loginVoiceTotal") + @ApiImplicitParams({}) + public ResultData loginVoiceTotal() { + VoiceLanguage vl = new VoiceLanguage(); + vl.setCustomizedQuery(EnumYesOrNo.YES.getCode()); + vl.setCUserId(getMemberId()); + return new ResultData(voiceLanguageService.voiceTotal(vl)); } @AuthIgnore @@ -166,8 +181,28 @@ public class VoiceMouldController extends BaseController { @ApiImplicitParams({}) public ResultData voicePreview(@RequestBody AiPreviewParam aiPreviewParam) { logger.debug("[" + getIpAddr() + "] MouldPatchController::voicePreview"); - return new ResultData(voiceInfoService.voicePreview(aiPreviewParam)); + return new ResultData(voiceInfoService.previewVoice(aiPreviewParam)); + } + + @ApiOperation("TTS音色预览") + @PostMapping("/loginPreview") + @ApiImplicitParams({}) + public ResultData loginPreview(@RequestBody AiPreviewParam aiPreviewParam) { + logger.debug("[" + getIpAddr() + "] MouldPatchController::voicePreview"); + PreviewVoiceVO pv = voiceInfoService.previewVoice(aiPreviewParam); + Double time = pv.getTime();//秒 + if (time > 5*60 ) { + return new ResultData(Result.ERROR,"视频最大时长为300秒,当前时长为"+time+"秒"); + } + //如果用户未支付,则只能1分钟以内,如果已支付,则可以5分钟以内 + ProductOrder po = new ProductOrder(); + po.setUserId(getMemberId()); + Integer paidCount = productOrderService.findPaidCount(po); + if (null == paidCount || paidCount <= 0 ) { + if (time > 60) { + return new ResultData(Result.ERROR,"视频最大时长为60秒,当前时长为"+time+"秒"); + } + } + return new ResultData(pv); } - - } diff --git a/suimangCApi/src/main/java/com/iformall/controller/WxUserGrantController.java b/suimangCApi/src/main/java/com/iformall/controller/WxUserGrantController.java index 1c8e580..f186552 100644 --- a/suimangCApi/src/main/java/com/iformall/controller/WxUserGrantController.java +++ b/suimangCApi/src/main/java/com/iformall/controller/WxUserGrantController.java @@ -3,6 +3,7 @@ package com.iformall.controller; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; +import com.google.code.kaptcha.Constants; import com.google.code.kaptcha.Producer; import com.iformall.annotation.AuthIgnore; import com.iformall.annotation.TenantIgnore; @@ -14,6 +15,7 @@ import com.iformall.domain.po.sm.InviteCodeInfo; import com.iformall.enums.*; import com.iformall.service.*; import com.iformall.service.cuser.CUserServiceFactory; +import com.iformall.service.project.ProjectFactory; import com.iformall.service.sm.InviteCodeInfoService; import com.iformall.service.sm.InviteCodeService; import com.iformall.service.sm.UserConsumptionPackageService; @@ -42,6 +44,7 @@ import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Date; @@ -110,12 +113,14 @@ public class WxUserGrantController extends BaseController { @Autowired private WxCUserAuthorityService wxCUserAuthorityService; - - + + @Autowired + private ProjectFactory projectFactory; + @AuthIgnore @ApiOperation("验证码") @GetMapping("/captcha.jpg") - public void captcha(HttpServletResponse response) { + public void captcha(HttpServletRequest request, HttpServletResponse response) { logger.debug("[" + getIpAddr() + "] WxUserGrantController::captcha"); response.setHeader("Cache-Control", "no-store, no-cache"); response.setContentType("image/jpeg"); @@ -126,9 +131,11 @@ public class WxUserGrantController extends BaseController { BufferedImage image = producer.createImage(text); //保存到redis - String ipAddr = getIpAddr(); - String key = Constant.captchaPrev + ":" + ipAddr; - RedisCacheUtils.cache(redisTemplate, key, text, 60); +// String ipAddr = getIpAddr(); +// String key = Constant.captchaPrev + ":" + ipAddr; +// RedisCacheUtils.cache(redisTemplate, key, text, 60); + HttpSession session = request.getSession(); + session.setAttribute(Constants.KAPTCHA_SESSION_KEY, text); ServletOutputStream out = null; try { @@ -152,7 +159,7 @@ public class WxUserGrantController extends BaseController { @AuthIgnore @PostMapping("/login") @ApiOperation(value = "用户登录", notes = "{\"phone\":\"string\",\"password\":\"string\",\"code\":\"string\"}") - public ResultData loginByPhone(@RequestBody Map map) { + public ResultData loginByPhone(@RequestBody Map map, HttpServletRequest request) { String ipAddr = getIpAddr(); logger.debug("[" + ipAddr + "] WxUserGrantController::loginByPhone"); String code = map.get("code"); @@ -160,8 +167,19 @@ public class WxUserGrantController extends BaseController { return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "请输入验证码"); } - String key = Constant.captchaPrev + ":" + ipAddr; - String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); + HttpSession session = request.getSession(); + Object kaptcha = session.getAttribute(Constants.KAPTCHA_SESSION_KEY); + if(kaptcha == null){ + return new ResultData(ErrorCode.KAPCHA_NOT_VALID); + } + session.removeAttribute(Constants.KAPTCHA_SESSION_KEY); + if(!kaptcha.toString().equals(code)){ + return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); + } + + +// String key = Constant.captchaPrev + ":" + ipAddr; +// String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); // if (StringUtils.isBlank(code1)) { // return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); // } @@ -188,6 +206,10 @@ public class WxUserGrantController extends BaseController { if (!encryptPassword.equals(basicInfo.getPassword())) { return new ResultData(ErrorCode.USER_PASSWD_ERR.getCode(), "手机号或密码错误"); } + + if (EnumCUserBasicInfoStatus.LOCKED.getCode().equals(basicInfo.getStatus())) { + return new ResultData(ErrorCode.MEMBER_IS_LOCKED.getCode(), "用户已被封禁"); + } wxCUserBasicInfoService.handleLoginUser(basicInfo); Map resultMap = new HashMap(); // resultMap.put("phone", basicInfo.getPhone()); @@ -205,23 +227,32 @@ public class WxUserGrantController extends BaseController { @AuthIgnore @PostMapping("/loginByEmail") @ApiOperation(value = "用户登录", notes = "{\"email\":\"string\",\"password\":\"string\",\"code\":\"string\"}") - public ResultData loginByEmail(@RequestBody Map map) { + public ResultData loginByEmail(@RequestBody Map map, HttpServletRequest request) { String ipAddr = getIpAddr(); logger.debug("[" + ipAddr + "] WxUserGrantController::loginByEmail"); String code = map.get("code"); if (StringUtils.isBlank(code)) { return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "请输入验证码"); } - - String key = Constant.captchaPrev + ":" + ipAddr; - String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); - if (StringUtils.isBlank(code1)) { - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); + HttpSession session = request.getSession(); + Object kaptcha = session.getAttribute(Constants.KAPTCHA_SESSION_KEY); + if(kaptcha == null){ + return new ResultData(ErrorCode.KAPCHA_NOT_VALID); } - if (!code1.equals(code)) { + session.removeAttribute(Constants.KAPTCHA_SESSION_KEY); + if(!kaptcha.toString().equals(code)){ return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); } +// String key = Constant.captchaPrev + ":" + ipAddr; +// String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); +// if (StringUtils.isBlank(code1)) { +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); +// } +// if (!code1.equals(code)) { +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); +// } + String email = map.get("email"); String password = map.get("password"); if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) { @@ -275,7 +306,7 @@ public class WxUserGrantController extends BaseController { // check 验证码正确 boolean isValidCode = false; try { - isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code); + isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code,0); } catch (Exception e) { return new ResultData(Result.ERROR, e.getMessage()); } @@ -322,7 +353,7 @@ public class WxUserGrantController extends BaseController { WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); wxMsgValidationcode.setPhone(phone); wxMsgValidationcode.setType(EnumMsgModel.VALIDATION_CODE.getCode()); - return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode); + return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode,0); } @@ -337,7 +368,7 @@ public class WxUserGrantController extends BaseController { @GetMapping("sendPhoneCode") @ApiImplicitParams({ @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query", required = true)}) - public ResultData sendPhoneCode(String phone, String code) { + public ResultData sendPhoneCode(String phone, String code, HttpServletRequest request) { String ipAddr = getIpAddr(); logger.debug("[" + ipAddr + "] WxUserGrantController::sendPhoneCode"); if (StringUtils.isBlank(phone)) { @@ -346,15 +377,24 @@ public class WxUserGrantController extends BaseController { if (StringUtils.isBlank(code)) { return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "请输入验证码"); } - - String key = Constant.captchaPrev + ":" + ipAddr; - String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); - if (StringUtils.isBlank(code1)) { - return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); + HttpSession session = request.getSession(); + Object kaptcha = session.getAttribute(Constants.KAPTCHA_SESSION_KEY); + if(kaptcha == null){ + return new ResultData(ErrorCode.KAPCHA_NOT_VALID); } - if (!code1.equals(code)) { + session.removeAttribute(Constants.KAPTCHA_SESSION_KEY); + if(!kaptcha.toString().equals(code)){ return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); } + +// String key = Constant.captchaPrev + ":" + ipAddr; +// String code1 = RedisCacheUtils.getCacheString(redisTemplate, key); +// if (StringUtils.isBlank(code1)) { +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码已过期"); +// } +// if (!code1.equals(code)) { +// return new ResultData(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "验证码不正确"); +// } WxCUserBasicInfo basicInfo = wxCUserBasicInfoService.findInfoByPhone(getTenantInfo(), phone); if (basicInfo == null) { return new ResultData(ErrorCode.USER_IS_EMPTY.getCode(), "该手机号未注册"); @@ -363,7 +403,7 @@ public class WxUserGrantController extends BaseController { WxMsgValidationcode wxMsgValidationcode = new WxMsgValidationcode(); wxMsgValidationcode.setPhone(phone); wxMsgValidationcode.setType(EnumMsgModel.VALIDATION_CODE.getCode()); - return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode); + return wxMsgValidationcodeService.sendvalidationcode(wxMsgValidationcode,0); } @@ -407,6 +447,9 @@ public class WxUserGrantController extends BaseController { if (!aBoolean) { return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "初始化创建视频时间表失败"); } + + //慧影注册送金币 + projectFactory.getProjectService(EnumProject.PROJECT_2.getCode()).handleAfterRegeister(basicInfo); return new ResultData(); // } else { // return new ResultData(ErrorCode.MSG_VERIFY_CODE_NOT_FOUND); @@ -560,7 +603,7 @@ public class WxUserGrantController extends BaseController { // check 验证码正确 boolean isValidCode = false; try { - isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code); + isValidCode = wxMsgValidationcodeService.checkCodeValid(phone, code,0); } catch (Exception e) { return new ResultData(Result.ERROR, e.getMessage()); } @@ -755,9 +798,25 @@ public class WxUserGrantController extends BaseController { @AuthIgnore @ApiOperation("套餐档次查询") @GetMapping("/getPackageInfo") + @Deprecated public ResultData getPackageInfo() { logger.debug("[" + getIpAddr() + "] WxUserGrantController::getPackageInfo"); return new ResultData(userConsumptionPackageService.getPackageInfo()); } - + + @ApiOperation("获取用户币值") + @GetMapping("/getUserPoins") + public ResultData getUserPoins() { + WxCUserBasicInfo userBasicInfo = wxCUserBasicInfoService.getById(getMemberId()); + return new ResultData(userBasicInfo.getPoins()); + } + + @ApiOperation("扣减获取用户币值") + @GetMapping("/reduceUserPoins") + public ResultData reduceUserPoins() { + WxCUserBasicInfo user = this.getCUser(); + wxCUserBasicInfoService.reducePoints(user.getId(), user.getFinalTenantId(), 1); + return new ResultData(); + } + } diff --git a/suimangCApi/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java b/suimangCApi/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java index e9f4182..c8a3a83 100644 --- a/suimangCApi/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java +++ b/suimangCApi/src/main/java/com/iformall/interceptor/AuthorizationInterceptor.java @@ -44,7 +44,7 @@ public class AuthorizationInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - + AuthIgnore annotation; if(handler instanceof HandlerMethod) { annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class); diff --git a/suimangCApi/src/main/java/com/iformall/utils/BaiduImageCheckUtil.java b/suimangCApi/src/main/java/com/iformall/utils/BaiduCheckUtil.java similarity index 80% rename from suimangCApi/src/main/java/com/iformall/utils/BaiduImageCheckUtil.java rename to suimangCApi/src/main/java/com/iformall/utils/BaiduCheckUtil.java index 35e75e0..c0d95f5 100644 --- a/suimangCApi/src/main/java/com/iformall/utils/BaiduImageCheckUtil.java +++ b/suimangCApi/src/main/java/com/iformall/utils/BaiduCheckUtil.java @@ -22,9 +22,10 @@ import java.util.HashMap; */ @Slf4j @Component -public class BaiduImageCheckUtil { +public class BaiduCheckUtil { // 百度图片审核接口地址 private final static String photo_check_url = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined"; + private final static String text_check_url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined"; // 获取token private final static String auth_url = "https://aip.baidubce.com/oauth/2.0/token?"; // 百度API Key @@ -33,6 +34,32 @@ public class BaiduImageCheckUtil { // 百度Secret Key private final static String secretKey = "eGmeQkP3Opzph0GB4Y2voiOkGOlwbeWd"; + + public static ResultData textCheck(String text) { + try { + String param = "text=" + URLEncoder.encode(text, "utf-8");; + String accessToken = getAuth(); + String result = BaiDuHttpUtil.post(text_check_url, accessToken, param); + log.info("图片检测"+result); + JSONObject jsonObject = JSON.parseObject(result); + //1:合规,2:不合规,3:疑似,4:审核失败 + Integer type = jsonObject.getInteger("conclusionType"); + if (type == 1) { + return new ResultData(); + } else if (type == 2 || type == 3) { + return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),"文字内容不合规"); + } else if (type == 4) { + return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),"文字内容审核失败"); + } else { + return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),"文字内容不合规"); + } + } catch (Exception e) { + e.printStackTrace(); + return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),"文字内容审核失败"); + } + + } + public static ResultData photoCheck(MultipartFile file) { try { byte[] fileBytes = file.getBytes(); diff --git a/suimangCApi/src/main/resources/application-dev.yml b/suimangCApi/src/main/resources/application-dev.yml index 63c7645..d9eb49d 100644 --- a/suimangCApi/src/main/resources/application-dev.yml +++ b/suimangCApi/src/main/resources/application-dev.yml @@ -189,9 +189,29 @@ logging: path: ./logs/c suimang: - oral_broadcasting: http://nas.pucao.cn:2001 - photo_speak: http://111.198.0.15:22299 - photo_speak_hy: http://111.198.0.15:22288 - digital_avatar: http://111.198.0.15:22200 + oral_broadcasting: http://nas.pucao.cn:50014 + callbackUrl: https://mtest.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://nas.pucao.cn:50015 + photo_speak_hy: http://nas.pucao.cn:50013 + digital_avatar: http://nas.pucao.cn:2005 digital_avatar_hy: http://nas.pucao.cn:2003 - callbackUrl: https://test.metavatar.cc/C + local_deploy: true + token: fm2023 +sdk: + sm: + base-url: https://mtest.metavatar.cc/public +swagger: + base-package: com.iformall.controller + title: 遂芒_metavatar_接口文档 + description: 前后端联调 + version: 1.0 + license: Apache + license-url: https://mtest.metavatar.cc/ + terms-of-service-url: https://mtest.metavatar.cc/ + host: localhost:8888 + contact: + name: 张三 + url: https://mtest.metavatar.cc/ + email: zhangsan@163.com \ No newline at end of file diff --git a/suimangCApi/src/main/resources/application-prod.yml b/suimangCApi/src/main/resources/application-prod.yml index 8ba888b..9f710b1 100644 --- a/suimangCApi/src/main/resources/application-prod.yml +++ b/suimangCApi/src/main/resources/application-prod.yml @@ -145,8 +145,15 @@ logging: suimang: oral_broadcasting: http://111.198.0.15:22266 + callbackUrl: https://neuver.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 photo_speak: http://111.198.0.15:22299 photo_speak_hy: http://111.198.0.15:22288 digital_avatar: http://111.198.0.15:22200 - digital_avatar_hy: http://nas.pucao.cn:2003 - callbackUrl: https://metavatar.cc/C + digital_avatar_hy: http://****:2003 + local_deploy: false + token: fm2023 +sdk: + sm: + base-url: https://neuver.metavatar.cc/public \ No newline at end of file diff --git a/suimangCallback/.gitignore b/suimangCallback/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangCallback/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangCallback/src/main/java/com/iformall/shiro/MyRetryLimitCredentialsMatcher.java b/suimangCallback/src/main/java/com/iformall/shiro/MyRetryLimitCredentialsMatcher.java index e71e52c..a6d8d70 100644 --- a/suimangCallback/src/main/java/com/iformall/shiro/MyRetryLimitCredentialsMatcher.java +++ b/suimangCallback/src/main/java/com/iformall/shiro/MyRetryLimitCredentialsMatcher.java @@ -26,7 +26,7 @@ public class MyRetryLimitCredentialsMatcher extends HashedCredentialsMatcher { if(tk.getType().equals(EnumLoginType.NOPASSWD)){ // 获取用户的输入的账号. String username = (String)tk.getPrincipal(); - MallUserInfo user = userService.getByUsername(username); + MallUserInfo user = userService.getByUsername(username,tk.getProjectType()); if(user == null) { throw new UnknownAccountException(ErrorCode.USER_IS_EMPTY.getMessage()); } diff --git a/suimangCallback/src/main/java/com/iformall/shiro/MyShiroRealm.java b/suimangCallback/src/main/java/com/iformall/shiro/MyShiroRealm.java index 520d5db..0c7fcf2 100644 --- a/suimangCallback/src/main/java/com/iformall/shiro/MyShiroRealm.java +++ b/suimangCallback/src/main/java/com/iformall/shiro/MyShiroRealm.java @@ -39,7 +39,7 @@ public class MyShiroRealm extends AuthorizingRealm { protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //获取用户的输入的账号. String username = (String)token.getPrincipal(); - MallUserInfo user = userService.getByUsername(username); + MallUserInfo user = userService.getByUsername(username,0); if(user == null) { throw new UnknownAccountException(ErrorCode.USER_IS_EMPTY.getMessage()); } diff --git a/suimangCallback/src/main/java/com/iformall/shiro/UseriFormallToken.java b/suimangCallback/src/main/java/com/iformall/shiro/UseriFormallToken.java index 04f525a..1513fdf 100644 --- a/suimangCallback/src/main/java/com/iformall/shiro/UseriFormallToken.java +++ b/suimangCallback/src/main/java/com/iformall/shiro/UseriFormallToken.java @@ -7,14 +7,16 @@ public class UseriFormallToken extends UsernamePasswordToken { private static final long serialVersionUID = -2564928913725078138L; private EnumLoginType type; + private int projectType; public UseriFormallToken() { super(); } - public UseriFormallToken(String username, String password, EnumLoginType type, boolean rememberMe, String host) { + public UseriFormallToken(String username, String password, EnumLoginType type, boolean rememberMe, String host,int projectType) { super(username, password, rememberMe, host); this.type = type; + this.projectType = projectType; } /** 免密登录 */ @@ -36,4 +38,13 @@ public class UseriFormallToken extends UsernamePasswordToken { public void setType(EnumLoginType type) { this.type = type; } + + public int getProjectType() { + return projectType; + } + + public void setProjectType(int projectType) { + this.projectType = projectType; + } + } diff --git a/suimangMQConsumer/.gitignore b/suimangMQConsumer/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangMQConsumer/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangMQConsumer/src/main/java/com/iformall/mq/MqBaseConsumer.java b/suimangMQConsumer/src/main/java/com/iformall/mq/MqBaseConsumer.java index 1511c3f..45b094d 100644 --- a/suimangMQConsumer/src/main/java/com/iformall/mq/MqBaseConsumer.java +++ b/suimangMQConsumer/src/main/java/com/iformall/mq/MqBaseConsumer.java @@ -51,8 +51,6 @@ public class MqBaseConsumer { //@Autowired //private FmInsideNotifyPaySuccessMsgServiceImpl fmInsideNotifyPaySuccessMsgService; - @Autowired - private FmInsideNotifyRefundSuccessMsgServiceImpl fmInsideNotifyRefundSuccessMsgService; //@Autowired //UpdateCouponStockMsgServiceImpl updateCouponStockMsgService; @@ -160,8 +158,6 @@ public class MqBaseConsumer { //} else if(EnumMsgRecordType.INSIDE_NOTIFY_REFUND_SUCCESS.getCode().equals(baseMsg.getMsgType())) { // 内部消息 - 微信退款通知 - FmInsideNotifyRefundSuccessMsg msg = (FmInsideNotifyRefundSuccessMsg)JsonUtil.readValue(message,FmInsideNotifyRefundSuccessMsg.class); - fmInsideNotifyRefundSuccessMsgService.send(msg); } else if(EnumMsgRecordType.CASH_OUT.getCode().equals(baseMsg.getMsgType())) { // 内部消息 - 商户提现通知 diff --git a/suimangOcr/.gitignore b/suimangOcr/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangOcr/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangSchedule/.gitignore b/suimangSchedule/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangSchedule/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangSchedule/src/main/java/com/iformall/schedule/PhotoSpeakSchedule.java b/suimangSchedule/src/main/java/com/iformall/schedule/PhotoSpeakSchedule.java index 2a4d4d5..85cd3ae 100644 --- a/suimangSchedule/src/main/java/com/iformall/schedule/PhotoSpeakSchedule.java +++ b/suimangSchedule/src/main/java/com/iformall/schedule/PhotoSpeakSchedule.java @@ -96,12 +96,13 @@ public class PhotoSpeakSchedule { try { VideUploadResult videoDetail = videoFactory.getExcutor(videoType).getVideoDetailWithCache(video.getVideoId(),false); logger.info("userVideoDetailSchedule" + videoDetail); - if (videoDetail.isSuccess() - && StringUtils.isNotBlank(videoDetail.getDuration()) - && !"0.0".equals(videoDetail.getDuration())) { + if (videoDetail.isSuccess() && StringUtils.isNotBlank(videoDetail.getDuration()) && StringUtils.isNotBlank(videoDetail.getVideoUrl())) { video.setCoverImg(videoDetail.getCoverURL()); video.setVideoPlayUrl(videoDetail.getVideoUrl()); - video.setVideoTime(videoDetail.getDuration()); + Double _vt = Double.valueOf(videoDetail.getDuration()); + if (null != _vt && _vt > 0) { + video.setVideoTime(videoDetail.getDuration()); + } video.setVideoSize(videoDetail.getSize()); if (video.getVideoStatus() <= 5){ video.setVideoStatus(EnumVideoStatus.upload_success.getCode()); diff --git a/suimangSchedule/src/main/java/com/iformall/schedule/ProductOrderSchedule.java b/suimangSchedule/src/main/java/com/iformall/schedule/ProductOrderSchedule.java index 96d7aff..8369861 100644 --- a/suimangSchedule/src/main/java/com/iformall/schedule/ProductOrderSchedule.java +++ b/suimangSchedule/src/main/java/com/iformall/schedule/ProductOrderSchedule.java @@ -28,7 +28,7 @@ public class ProductOrderSchedule { @Autowired private ProductOrderSharingService productOrderSharingService; - @Scheduled(cron = "0 3/5 * * * *?") + //@Scheduled(cron = "0 */5 * * * *?") public void productOrderSharingSchedule() { ProductOrder productOrderQ = new ProductOrder(); productOrderQ.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); diff --git a/suimangSchedule/src/main/java/com/iformall/schedule/VideoSchedule.java b/suimangSchedule/src/main/java/com/iformall/schedule/VideoSchedule.java index 1b89d8d..52d0131 100644 --- a/suimangSchedule/src/main/java/com/iformall/schedule/VideoSchedule.java +++ b/suimangSchedule/src/main/java/com/iformall/schedule/VideoSchedule.java @@ -1,10 +1,15 @@ package com.iformall.schedule; +import com.alibaba.fastjson.JSON; import com.iformall.domain.po.sm.UserMouldVideo; import com.iformall.domain.po.sm.VideoTrans; +import com.iformall.enums.EnumProject; import com.iformall.enums.EnumVideoStatus; +import com.iformall.enums.EnumYesOrNo; import com.iformall.enums.EnumaVideoTransStatus; import com.iformall.mapper.VideoTransMapper; +import com.iformall.service.project.ProjectFactory; +import com.iformall.service.project.entity.CreateBilling; import com.iformall.service.sm.UserMouldVideoService; import com.iformall.utils.DateUtils; import com.iformall.video.VideoFactory; @@ -39,6 +44,9 @@ public class VideoSchedule { @Autowired String videoType; + + @Autowired + ProjectFactory projectFactory; /** * 生成视频 @@ -48,6 +56,7 @@ public class VideoSchedule { UserMouldVideo userVideo = new UserMouldVideo(); userVideo.setVideoStartDate(DateUtils.getHourDateBefore(2,new Date())); userVideo.setVideoStatus(EnumVideoStatus.fail.getCode()); + userVideo.setIsDel(EnumYesOrNo.NO.getCode()); List list = userMouldVideoService.findList(userVideo); if (list != null && list.size() > 0) { for (UserMouldVideo video : list) { @@ -81,7 +90,7 @@ public class VideoSchedule { /** * 获取时长和大小 */ - @Scheduled(cron = "0 1/5 * * * *?") // 每五分钟检查一次 + @Scheduled(cron = "0 0/5 * * * *?") // 每五分钟检查一次 public void userVideoDetailSchedule() { List videos = userMouldVideoService.getNotHaveUrl(); if (videos != null && videos.size() > 0) { @@ -90,12 +99,28 @@ public class VideoSchedule { VideUploadResult videoDetail = videoFactory.getExcutor(videoType).getVideoDetailWithCache(video.getVideoId(),false); if (videoDetail.isSuccess() && StringUtils.isNotBlank(videoDetail.getDuration()) - && !"0.0".equals(videoDetail.getDuration())) { + && StringUtils.isNotBlank(videoDetail.getVideoUrl())) { video.setCoverImg(videoDetail.getCoverURL()); video.setVideoPlayUrl(videoDetail.getVideoUrl()); - video.setVideoTime(videoDetail.getDuration()); + Double _vt = Double.valueOf(videoDetail.getDuration()); + if (null != _vt && _vt > 0) { + video.setVideoTime(videoDetail.getDuration()); + } video.setVideoSize(videoDetail.getSize()); video.setVideoStatus(EnumVideoStatus.upload_success.getCode()); + video.setVideoMsg("视频上传成功"); + video.setUpdateDate(new Date()); + //设置扣费,当前方法是慧影项目专用的 + if (StringUtils.isBlank(video.getVideoTime())) { + break; + } + CreateBilling cb = projectFactory.getProjectService(EnumProject.PROJECT_2.getCode()) + .handleCreateVideoBilling(video.getUserId(), video.getFinalTenantId(), video.getVideoTime(), video.getVideoSize()); + if (null != cb) { + logger.info("createBilling result:"+JSON.toJSONString(cb)); + video.setCostPoints(cb.getTotalCostPoins()); + video.setCostPointsDetail(cb.getDetail()); + } userMouldVideoService.updateById(video); } } catch (Exception e) { diff --git a/suimangSchedule/src/main/resources/application-dev.yml b/suimangSchedule/src/main/resources/application-dev.yml index d075af1..c8cbf4b 100644 --- a/suimangSchedule/src/main/resources/application-dev.yml +++ b/suimangSchedule/src/main/resources/application-dev.yml @@ -192,9 +192,13 @@ logging: path: ./logs/s suimang: - oral_broadcasting: http://nas.pucao.cn:2001 - photo_speak: http://111.198.0.15:22299 - photo_speak_hy: http://111.198.0.15:22288 - digital_avatar: http://111.198.0.15:22200 + oral_broadcasting: http://nas.pucao.cn:50014 + callbackUrl: https://mtest.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 + photo_speak: http://nas.pucao.cn:50015 + photo_speak_hy: http://nas.pucao.cn:50013 + digital_avatar: http://nas.pucao.cn:2005 digital_avatar_hy: http://nas.pucao.cn:2003 - callbackUrl: https://test.metavatar.cc/C \ No newline at end of file + local_deploy: true + token: fm2023 \ No newline at end of file diff --git a/suimangSchedule/src/main/resources/application-prod.yml b/suimangSchedule/src/main/resources/application-prod.yml index 83e1c3f..62d8b7d 100644 --- a/suimangSchedule/src/main/resources/application-prod.yml +++ b/suimangSchedule/src/main/resources/application-prod.yml @@ -149,8 +149,12 @@ logging: suimang: oral_broadcasting: http://111.198.0.15:22266 + callbackUrl: https://neuver.metavatar.cc/C + video_tts: http://111.198.0.15:22299 + huibo_tts_wav: http://111.198.0.15:22222 photo_speak: http://111.198.0.15:22299 photo_speak_hy: http://111.198.0.15:22288 digital_avatar: http://111.198.0.15:22200 - digital_avatar_hy: http://nas.pucao.cn:2003 - callbackUrl: https://metavatar.cc/C \ No newline at end of file + digital_avatar_hy: http://*****:2003 + local_deploy: false + token: fm2023 \ No newline at end of file diff --git a/suimangService/.gitignore b/suimangService/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangService/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangService/pom.xml b/suimangService/pom.xml index 7839808..60d406e 100644 --- a/suimangService/pom.xml +++ b/suimangService/pom.xml @@ -20,6 +20,11 @@ compile --> + + com.iformall + suimang-swagger + 1.0 + com.iformall suimangVideo @@ -40,11 +45,12 @@ suimang-mybatis 1.0 + - com.alipay.sdk - alipay-easysdk - 2.2.0 - + com.alipay.sdk + alipay-sdk-java + 4.38.98.ALL + \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/common/CommonConstants.java b/suimangService/src/main/java/com/iformall/common/CommonConstants.java new file mode 100644 index 0000000..86bb909 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/common/CommonConstants.java @@ -0,0 +1,29 @@ +package com.iformall.common; + +public interface CommonConstants { + /** + * 接口响应码:200:成功 500:失败 + */ + Integer SUCCESS = 200; + Integer FAILED = 500; + + /** + * 状态(0:正常,1:锁定) + */ + Integer STATUS_NORMAL = 0; + Integer STATUS_ABNORMAL = 1; + + /** + * 是否:0:否,1:是 + * 是否删除状态(0:未删除,1:已删除) + */ + Integer FLAG_TRUE = 1; + Integer FLAG_FALSE = 0; + + /** + * 通用数字 + */ + int NUM_0 = 0; + int NUM_1 = 1; + int NUM_2 = 2; +} diff --git a/suimangService/src/main/java/com/iformall/common/ErrorCode.java b/suimangService/src/main/java/com/iformall/common/ErrorCode.java index 5fde228..8da03d7 100644 --- a/suimangService/src/main/java/com/iformall/common/ErrorCode.java +++ b/suimangService/src/main/java/com/iformall/common/ErrorCode.java @@ -676,7 +676,16 @@ public enum ErrorCode{ * mould */ ORDER_CREAT_OVERRUN(64000, "重复生成次数超限"), + MEMBER_NO_POINTS(64001,"当前账户无足额金币"), + CODE_ALREADY_EXISTS(71000, "该code已存在"), + + SECRET_NOT_EXISTS(71001, "该秘钥不存在"), + SERVICE_LOCKED(71002, "合作商被锁定,无法修改"), + + NAME_REPEAT(81000, "名称重复"), + EXIST_AVAILABLE_GUIDE(81001, "存在可用指南"), + ; private int code; diff --git a/suimangService/src/main/java/com/iformall/common/GlobalDefultExceptionHandler.java b/suimangService/src/main/java/com/iformall/common/GlobalDefultExceptionHandler.java index c79922b..ec62053 100644 --- a/suimangService/src/main/java/com/iformall/common/GlobalDefultExceptionHandler.java +++ b/suimangService/src/main/java/com/iformall/common/GlobalDefultExceptionHandler.java @@ -1,6 +1,7 @@ package com.iformall.common; +import com.iformall.exception.BizException; import com.iformall.exception.MallinkException; import com.iformall.service.MailService; import org.apache.shiro.authz.AuthorizationException; @@ -71,17 +72,23 @@ public class GlobalDefultExceptionHandler { } } + @ResponseBody + @ExceptionHandler(value = BizException.class) + public ResultData bizExceptionHandler(BizException e, HttpServletRequest request) { + log(e, request); + return new ResultData(e.getCode(), e.getMsg()); + } private void log(Exception ex, HttpServletRequest request) { logger.error("************************异常开始*******************************"); if(checkExceptionType(ex)) { // 特殊异常不打印堆栈 - logger.error(ex.getMessage()); + logger.error("message:" + ex); logger.error("************************异常结束*******************************"); return; } logger.error("请求地址:" + request.getRequestURL()); - logger.error("message:"+ ex.getMessage()); + logger.error("message:"+ ex); Enumeration enumeration = request.getParameterNames(); logger.error("请求参数"); while (enumeration.hasMoreElements()) { diff --git a/suimangService/src/main/java/com/iformall/common/R.java b/suimangService/src/main/java/com/iformall/common/R.java new file mode 100644 index 0000000..04b81d4 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/common/R.java @@ -0,0 +1,76 @@ +package com.iformall.common; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.io.Serializable; + +/** + * 响应信息主体 + * + * @author xmzhao71 + * @date 2023-10-26 + */ +@ApiModel(description = "响应信息主体") +@Data +public class R implements Serializable { + private static final long serialVersionUID = 1L; + + @ApiModelProperty(value = "返回标记:成功=0,失败=1") + private int code; + + @ApiModelProperty(value = "返回信息") + private String message; + + @ApiModelProperty(value = "数据") + private T data; + + public Boolean isOk() { + return code == 200; + } + + public static R ok() { + return restResult(null, CommonConstants.SUCCESS, null); + } + + public static R ok(T data) { + return restResult(data, CommonConstants.SUCCESS, null); + } + + public static R ok(T data, String msg) { + return restResult(data, CommonConstants.SUCCESS, msg); + } + + public static R failed() { + return restResult(null, CommonConstants.FAILED, null); + } + + public static R failed(String msg) { + return restResult(null, CommonConstants.FAILED, msg); + } + + public static R failed(T data) { + return restResult(data, CommonConstants.FAILED, null); + } + + public static R failed(T data, String msg) { + return restResult(data, CommonConstants.FAILED, msg); + } + + public static R failed(T data, int code, String msg) { + return restResult(data, code, msg); + } + + public static R failed(int code, String msg) { + return restResult(null, code, msg); + } + + private static R restResult(T data, int code, String msg) { + R apiResult = new R<>(); + apiResult.setCode(code); + apiResult.setData(data); + apiResult.setMessage(msg); + return apiResult; + } +} \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/config/RestTemplateConfig.java b/suimangService/src/main/java/com/iformall/config/RestTemplateConfig.java new file mode 100644 index 0000000..d8e6c44 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/config/RestTemplateConfig.java @@ -0,0 +1,14 @@ +package com.iformall.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +@Configuration +public class RestTemplateConfig { + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/GetLanguageDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/GetLanguageDTO.java new file mode 100644 index 0000000..1ad0784 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/GetLanguageDTO.java @@ -0,0 +1,12 @@ +package com.iformall.domain.dto.sm; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "获取语种") +@Data +public class GetLanguageDTO { + @ApiModelProperty(value = "文案") + private String paperwork; +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiGuideDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiGuideDTO.java new file mode 100644 index 0000000..03c13d5 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiGuideDTO.java @@ -0,0 +1,36 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.CommonConstants; +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ApiGuide; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "新增API指南") +@Data +public class SaveApiGuideDTO { + @ApiModelProperty("指南名称") + private String name; + @ApiModelProperty("指南内容") + private String content; + @ApiModelProperty("状态(0:正常,1:锁定)") + private Integer status; + + public static ApiGuide mapping(SaveApiGuideDTO dto) { + ApiGuide apiGuide = new ApiGuide(); + apiGuide.setId(IdWorker.get().nextId()); + apiGuide.setCreateTime(new Date()); + apiGuide.setUpdateTime(new Date()); + if (CommonConstants.STATUS_NORMAL.equals(dto.getStatus())) { + apiGuide.setReleaseTime(new Date()); + } + apiGuide.setName(dto.getName()); + apiGuide.setContent(dto.getContent()); + apiGuide.setStatus(dto.getStatus()); + apiGuide.setDeleteFlag(CommonConstants.FLAG_FALSE); + return apiGuide; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiMenuDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiMenuDTO.java new file mode 100644 index 0000000..7b80a0d --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveApiMenuDTO.java @@ -0,0 +1,74 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.CommonConstants; +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ApiDetail; +import com.iformall.domain.po.sm.ApiMenu; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "新增API菜单") +@Data +public class SaveApiMenuDTO { + @ApiModelProperty("菜单名称") + private String name; + @ApiModelProperty("父菜单id") + private Long parentId; + @ApiModelProperty("状态(0:正常,1:锁定)") + private Integer status; + @ApiModelProperty("是否付费(0:否,1:是)") + private Integer chargeFlag; + @ApiModelProperty("是否需用户授权(0:否,1:是)") + private Integer authFlag; + @ApiModelProperty("接口描述") + private String description; + @ApiModelProperty("平台地址") + private String platformUrl; + @ApiModelProperty("系统参数") + private String publicParam; + @ApiModelProperty("请求参数") + private String requestParam; + @ApiModelProperty("响应参数") + private String responseParam; + @ApiModelProperty("请求示例") + private String requestSample; + @ApiModelProperty("响应示例") + private String responseSample; + @ApiModelProperty("异常示例") + private String exceptionSample; + + public static ApiMenu mapping(SaveApiMenuDTO dto) { + ApiMenu apiMenu = new ApiMenu(); + apiMenu.setId(IdWorker.get().nextId()); + apiMenu.setCreateTime(new Date()); + apiMenu.setUpdateTime(new Date()); + apiMenu.setName(dto.getName()); + apiMenu.setParentId(dto.getParentId()); + apiMenu.setStatus(dto.getStatus()); + apiMenu.setDeleteFlag(CommonConstants.FLAG_FALSE); + return apiMenu; + } + + public static ApiDetail mappingApiDetail(SaveApiMenuDTO dto, ApiMenu apiMenu) { + ApiDetail apiDetail = new ApiDetail(); + apiDetail.setId(IdWorker.get().nextId()); + apiDetail.setCreateTime(new Date()); + apiDetail.setUpdateTime(new Date()); + apiDetail.setMenuId(apiMenu.getId()); + apiDetail.setMenuName(apiMenu.getName()); + apiDetail.setChargeFlag(dto.getChargeFlag()); + apiDetail.setAuthFlag(dto.getAuthFlag()); + apiDetail.setDescription(dto.getDescription()); + apiDetail.setPlatformUrl(dto.getPlatformUrl()); + apiDetail.setPublicParam(dto.getPublicParam()); + apiDetail.setRequestParam(dto.getRequestParam()); + apiDetail.setResponseParam(dto.getResponseParam()); + apiDetail.setRequestSample(dto.getRequestSample()); + apiDetail.setResponseSample(dto.getResponseSample()); + apiDetail.setExceptionSample(dto.getExceptionSample()); + return apiDetail; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceInfoDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceInfoDTO.java new file mode 100644 index 0000000..b43bca8 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceInfoDTO.java @@ -0,0 +1,37 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.CommonConstants; +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ServiceInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "新增接入商") +@Data +public class SaveServiceInfoDTO { + @ApiModelProperty("客户名称") + private String name; + @ApiModelProperty("所在地址") + private String address; + @ApiModelProperty("客户唯一凭证") + private String code; + @ApiModelProperty("接入方式(1:api接入,2:私有化接入)") + private Integer type; + + + public static ServiceInfo mapping(SaveServiceInfoDTO dto) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setId(IdWorker.get().nextId()); + serviceInfo.setCreateTime(new Date()); + serviceInfo.setUpdateTime(new Date()); + serviceInfo.setName(dto.getName()); + serviceInfo.setAddress(dto.getAddress()); + serviceInfo.setCode(dto.getCode()); + serviceInfo.setType(dto.getType()); + serviceInfo.setStatus(CommonConstants.STATUS_NORMAL); + return serviceInfo; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceVideoRecordDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceVideoRecordDTO.java new file mode 100644 index 0000000..7a3fb5f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveServiceVideoRecordDTO.java @@ -0,0 +1,40 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Date; + +@ApiModel(value = "新增生成视频时长记录") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SaveServiceVideoRecordDTO { + @ApiModelProperty("接入商标识") + private Long serviceId; + @ApiModelProperty("视频时长") + private String videoTime; + @ApiModelProperty("视频链接") + private String videoUrl; + @ApiModelProperty("记录ID") + private Long userMouldVideoId; + + public static ServiceVideoRecord mapping(SaveServiceVideoRecordDTO dto) { + ServiceVideoRecord serviceVideoRecord = new ServiceVideoRecord(); + serviceVideoRecord.setId(IdWorker.get().nextId()); + serviceVideoRecord.setCreateTime(new Date()); + serviceVideoRecord.setUpdateTime(new Date()); + serviceVideoRecord.setServiceId(dto.getServiceId()); + serviceVideoRecord.setVideoTime(dto.getVideoTime()); + serviceVideoRecord.setVideoUrl(dto.getVideoUrl()); + serviceVideoRecord.setUserMouldVideoId(dto.getUserMouldVideoId()); + return serviceVideoRecord; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveThirdPartyApiDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveThirdPartyApiDTO.java new file mode 100644 index 0000000..a1ee443 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/SaveThirdPartyApiDTO.java @@ -0,0 +1,22 @@ +package com.iformall.domain.dto.sm; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@ApiModel(value = "新增开放接口秘钥") +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class SaveThirdPartyApiDTO { + @ApiModelProperty("第三方类型(1:API接入,2:私有化接入)") + private Integer type; + @ApiModelProperty("名称") + private String name; + @ApiModelProperty("接入商id") + private Long serviceId; +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiGuideDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiGuideDTO.java new file mode 100644 index 0000000..74e98e2 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiGuideDTO.java @@ -0,0 +1,36 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.CommonConstants; +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ApiGuide; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "修改API指南") +@Data +public class UpdateApiGuideDTO { + @ApiModelProperty("id") + private Long id; + @ApiModelProperty("api名称") + private String name; + @ApiModelProperty("指南内容") + private String content; + @ApiModelProperty("状态(0:正常,1:锁定)") + private Integer status; + + public static ApiGuide mapping(UpdateApiGuideDTO dto) { + ApiGuide apiGuide = new ApiGuide(); + apiGuide.setId(dto.getId()); + apiGuide.setUpdateTime(new Date()); + if (CommonConstants.STATUS_NORMAL.equals(dto.getStatus())) { + apiGuide.setReleaseTime(new Date()); + } + apiGuide.setName(dto.getName()); + apiGuide.setContent(dto.getContent()); + apiGuide.setStatus(dto.getStatus()); + return apiGuide; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiMenuDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiMenuDTO.java new file mode 100644 index 0000000..98903ae --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateApiMenuDTO.java @@ -0,0 +1,74 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.common.CommonConstants; +import com.iformall.common.IdWorker; +import com.iformall.domain.po.sm.ApiDetail; +import com.iformall.domain.po.sm.ApiMenu; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "修改API菜单") +@Data +public class UpdateApiMenuDTO { + @ApiModelProperty(value = "菜单id",required = true) + private Long id; + @ApiModelProperty(value = "详情id") + private Long detailId; + @ApiModelProperty("菜单名称") + private String name; + @ApiModelProperty("父菜单id") + private Long parentId; + @ApiModelProperty("状态(0:正常,1:锁定)") + private Integer status; + @ApiModelProperty("是否付费(0:否,1:是)") + private Integer chargeFlag; + @ApiModelProperty("是否需用户授权(0:否,1:是)") + private Integer authFlag; + @ApiModelProperty("接口描述") + private String description; + @ApiModelProperty("平台地址") + private String platformUrl; + @ApiModelProperty("系统参数") + private String publicParam; + @ApiModelProperty("请求参数") + private String requestParam; + @ApiModelProperty("响应参数") + private String responseParam; + @ApiModelProperty("请求示例") + private String requestSample; + @ApiModelProperty("响应示例") + private String responseSample; + @ApiModelProperty("异常示例") + private String exceptionSample; + + public static ApiMenu mapping(UpdateApiMenuDTO dto) { + ApiMenu apiMenu = new ApiMenu(); + apiMenu.setId(dto.getId()); + apiMenu.setUpdateTime(new Date()); + apiMenu.setName(dto.getName()); + apiMenu.setParentId(dto.getParentId()); + apiMenu.setStatus(dto.getStatus()); + return apiMenu; + } + + public static ApiDetail mappingApiDetail(UpdateApiMenuDTO dto) { + ApiDetail apiDetail = new ApiDetail(); + apiDetail.setUpdateTime(new Date()); + apiDetail.setMenuId(dto.getId()); + apiDetail.setMenuName(dto.getName()); + apiDetail.setChargeFlag(dto.getChargeFlag()); + apiDetail.setAuthFlag(dto.getAuthFlag()); + apiDetail.setDescription(dto.getDescription()); + apiDetail.setPlatformUrl(dto.getPlatformUrl()); + apiDetail.setPublicParam(dto.getPublicParam()); + apiDetail.setRequestParam(dto.getRequestParam()); + apiDetail.setResponseParam(dto.getResponseParam()); + apiDetail.setRequestSample(dto.getRequestSample()); + apiDetail.setResponseSample(dto.getResponseSample()); + apiDetail.setExceptionSample(dto.getExceptionSample()); + return apiDetail; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoDTO.java new file mode 100644 index 0000000..c14355b --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoDTO.java @@ -0,0 +1,28 @@ +package com.iformall.domain.dto.sm; + +import com.iformall.domain.po.sm.ServiceInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; + +@ApiModel(value = "修改接入商") +@Data +public class UpdateServiceInfoDTO { + @ApiModelProperty("id") + private Long id; + @ApiModelProperty("客户名称") + private String name; + @ApiModelProperty("所在地址") + private String address; + + public static ServiceInfo mapping(UpdateServiceInfoDTO dto) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setId(dto.getId()); + serviceInfo.setUpdateTime(new Date()); + serviceInfo.setName(dto.getName()); + serviceInfo.setAddress(dto.getAddress()); + return serviceInfo; + } +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoStatusDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoStatusDTO.java new file mode 100644 index 0000000..53b66a2 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateServiceInfoStatusDTO.java @@ -0,0 +1,14 @@ +package com.iformall.domain.dto.sm; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "更新接入商状态") +@Data +public class UpdateServiceInfoStatusDTO { + @ApiModelProperty("接入商id") + private Long id; + @ApiModelProperty("状态(0:正常,1:失效)") + private Integer status; +} diff --git a/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateThirdPartyApiStatusDTO.java b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateThirdPartyApiStatusDTO.java new file mode 100644 index 0000000..64debcd --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/dto/sm/UpdateThirdPartyApiStatusDTO.java @@ -0,0 +1,14 @@ +package com.iformall.domain.dto.sm; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "更新开放接口秘钥状态") +@Data +public class UpdateThirdPartyApiStatusDTO { + @ApiModelProperty("开放接口秘钥id") + private Long id; + @ApiModelProperty("状态(0:正常,1:失效)") + private Integer status; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/MallUserInfo.java b/suimangService/src/main/java/com/iformall/domain/po/MallUserInfo.java index 3f46e2d..234477d 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/MallUserInfo.java +++ b/suimangService/src/main/java/com/iformall/domain/po/MallUserInfo.java @@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.annotation.TableName; import com.iformall.domain.po.base.TenantEntity; import com.iformall.enums.EnumUserAdmin; import com.iformall.enums.EnumUserWechat; +import com.iformall.sm.AiVideoHelper; import com.iformall.utils.Constant; import lombok.Data; import lombok.EqualsAndHashCode; @@ -78,7 +79,13 @@ public class MallUserInfo extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value = "邮箱", name = "email") private String email; - + + @io.swagger.annotations.ApiModelProperty(value = "所属项目EnumProject", name = "projectType") + private Integer projectType; + + @TableField(exist = false) + private Long serviceId; + public Integer getWithWechatNotFormat() { return this.withWechat; } @@ -120,9 +127,9 @@ public class MallUserInfo extends TenantEntity { * @return */ public boolean checkAdmin() { - if(StringUtils.isBlank(getTenantId())) { - return false; - } +// if(StringUtils.isBlank(getTenantId())) { +// return false; +// } if(isAdmin.equals(EnumUserAdmin.ADMIN.getCode())) { return true; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/Product.java b/suimangService/src/main/java/com/iformall/domain/po/Product.java index f6f7afb..6317d8d 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/Product.java +++ b/suimangService/src/main/java/com/iformall/domain/po/Product.java @@ -23,6 +23,11 @@ public class Product extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="EnumProductType",name="type") private Integer type; + @io.swagger.annotations.ApiModelProperty(value="每个项目套餐表ID,",name="extraId") + private Long extraId; + @TableField(exist = false) + private Object extraInfo; + @io.swagger.annotations.ApiModelProperty(value="",name="coverImg") private String coverImg; @io.swagger.annotations.ApiModelProperty(value="标题",name="title") diff --git a/suimangService/src/main/java/com/iformall/domain/po/ProductOrder.java b/suimangService/src/main/java/com/iformall/domain/po/ProductOrder.java index d980f32..c8b54bf 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/ProductOrder.java +++ b/suimangService/src/main/java/com/iformall/domain/po/ProductOrder.java @@ -47,9 +47,6 @@ public class ProductOrder extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="",name="remark") private String remark; - @io.swagger.annotations.ApiModelProperty(value="支付侧的订单号",name="orderId") - private String orderId; - @io.swagger.annotations.ApiModelProperty(value="支付者",name="openId") private String openId; @@ -100,5 +97,14 @@ public class ProductOrder extends TenantEntity { @TableField(exist = false) private Integer isOrderStatus; + + @TableField(exist = false) + private String phone; + + @TableField(exist = false) + private List cUserIds; + + @TableField(exist = false) + private WxCUserBasicInfo cUserInfo; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/ProductOrderPay.java b/suimangService/src/main/java/com/iformall/domain/po/ProductOrderPay.java new file mode 100644 index 0000000..ae4e391 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/ProductOrderPay.java @@ -0,0 +1,90 @@ +package com.iformall.domain.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.math.BigDecimal; +import java.util.Date; + +@TableName(value = "product_order_pay") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class ProductOrderPay extends TenantEntity { + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="系统订单号",name="orderId") + private Long orderId; + @io.swagger.annotations.ApiModelProperty(value="系统订单号",name="orderNumber") + private String orderNumber; + @io.swagger.annotations.ApiModelProperty(value="订单金额(分)",name="payAmount") + private Integer payAmount; + @io.swagger.annotations.ApiModelProperty(value="用户id",name="userId") + private Long userId; + + @io.swagger.annotations.ApiModelProperty(value="",name="orderDetail") + private String orderDetail; + + @io.swagger.annotations.ApiModelProperty(value="支付者",name="openId") + private String openId; + + @io.swagger.annotations.ApiModelProperty(value="EnumProject",name="projectType") + private Integer projectType; + @io.swagger.annotations.ApiModelProperty(value = "EnumProductOrderPayVendor", name = "payVendor") + private Integer payVendor; + + @io.swagger.annotations.ApiModelProperty(value="",name="ip") + private String ip; + + @io.swagger.annotations.ApiModelProperty(value="第三方订单号",name="transactionId") + private String transactionId; + + + @io.swagger.annotations.ApiModelProperty(value="EnumPayOrderStatus",name="payOrderStatus") + private Integer payOrderStatus; + @io.swagger.annotations.ApiModelProperty(value="支付时间",name="payTime") + private Date payTime; + + @io.swagger.annotations.ApiModelProperty(value="支付失败原因",name="failReason") + private String failReason; + + @io.swagger.annotations.ApiModelProperty(value="支付渠道",name="payWay") + private Integer payWay; + + + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + + @io.swagger.annotations.ApiModelProperty(value="EnumProfitSharing",name="profitSharing") + private Integer profitSharing; + + + @TableField(exist = false) + private String payAmountStr; + public String getPayAmountStr() { + return payAmount != null ? new BigDecimal(payAmount).divide(new BigDecimal(100)).toPlainString() : payAmountStr; + } + + @TableField(exist = false) + private Date startDate; + + @TableField(exist = false) + private Date endDate; + + @TableField(exist = false) + private Date payStartDate; + + @TableField(exist = false) + private Date payEndDate; + + @TableField(exist = false) + private Integer isOrderStatus; + +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/ProductOrderRefund.java b/suimangService/src/main/java/com/iformall/domain/po/ProductOrderRefund.java new file mode 100644 index 0000000..c98be75 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/ProductOrderRefund.java @@ -0,0 +1,84 @@ +package com.iformall.domain.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.math.BigDecimal; +import java.util.Date; + +@TableName(value = "product_order_refund") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class ProductOrderRefund extends TenantEntity { + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="系统订单号",name="orderId") + private Long orderId; + @io.swagger.annotations.ApiModelProperty(value="系统订单号",name="orderNumber") + private String orderNumber; + + @io.swagger.annotations.ApiModelProperty(value="EnumProject",name="projectType") + private Integer projectType; + @io.swagger.annotations.ApiModelProperty(value = "EnumProductOrderPayVendor", name = "payVendor") + private Integer payVendor; + + @io.swagger.annotations.ApiModelProperty(value="用户id",name="userId") + private Long userId; + + @io.swagger.annotations.ApiModelProperty(value="支付id",name="payId") + private Long payId; + + @io.swagger.annotations.ApiModelProperty(value="第三方订单号",name="transactionId") + private String transactionId; + + @io.swagger.annotations.ApiModelProperty(value="订单金额(分)",name="payAmount") + private Integer payAmount; + + @io.swagger.annotations.ApiModelProperty(value="退款金额(分)",name="refundAmount") + private Integer refundAmount; + + @io.swagger.annotations.ApiModelProperty(value="EnumRefundOrderStatus",name="refundOrderStatus") + private Integer refundOrderStatus; + + @io.swagger.annotations.ApiModelProperty(value="失败原因",name="failReason") + private String failReason; + + @io.swagger.annotations.ApiModelProperty(value="",name="refundId") + private String refundId; + + @io.swagger.annotations.ApiModelProperty(value="退款原因",name="refundReason") + private String refundReason; + + @io.swagger.annotations.ApiModelProperty(value="退款补充原因",name="refundDescription") + private String refundDescription; + + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + + @TableField(exist = false) + private String payAmountStr; + public String getPayAmountStr() { + return payAmount != null ? new BigDecimal(payAmount).divide(new BigDecimal(100)).toPlainString() : payAmountStr; + } + + @TableField(exist = false) + private String refundAmountStr; + public String getRefundAmountStr() { + return refundAmount != null ? new BigDecimal(refundAmount).divide(new BigDecimal(100)).toPlainString() : refundAmountStr; + } + + @TableField(exist = false) + private Date startDate; + + @TableField(exist = false) + private Date endDate; + +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/ProjectPackageDetail.java b/suimangService/src/main/java/com/iformall/domain/po/ProjectPackageDetail.java new file mode 100644 index 0000000..6c24111 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/ProjectPackageDetail.java @@ -0,0 +1,121 @@ +package com.iformall.domain.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; +import com.iformall.enums.sm.EnumAiTemplateType; +import com.iformall.enums.sm.EnumLanguageType; +import com.iformall.enums.sm.EnumSoundType; +import com.iformall.enums.sm.EnumVideoFormatType; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.util.Date; + +@TableName(value = "project_package_detail") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class ProjectPackageDetail extends TenantEntity { + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="项目",name="projectType") + private Integer projectType; + + @io.swagger.annotations.ApiModelProperty(value="套餐ID",name="packageId") + private Long packageId; + + @io.swagger.annotations.ApiModelProperty(value="邀请用户加积分数量",name="inviteUserCredit") + private Integer inviteUserCredit; + + @io.swagger.annotations.ApiModelProperty(value="ai生成照片价格",name="aiPhotoPrice") + private Integer aiPhotoPrice; + + @io.swagger.annotations.ApiModelProperty(value="ai生成脚本价格",name="aiScriptPrice") + private Integer aiScriptPrice; + + @io.swagger.annotations.ApiModelProperty(value="生成视频价格",name="videoPrice") + private Integer videoPrice; + + @io.swagger.annotations.ApiModelProperty(value="是否有水印",name="isVideoWatermark") + private Integer isVideoWatermark; + + @io.swagger.annotations.ApiModelProperty(value="EnumLanguageType",name="language") + private Integer language; + @TableField(exist = false) + private String languageDesc; + public String getLanguageDesc(){ + if(this.language != null){ + EnumLanguageType languageEnum = EnumLanguageType.getEnum(language); + if(languageEnum != null){ + languageDesc = languageEnum.getMessage(); + } + } + return languageDesc; + } + + @io.swagger.annotations.ApiModelProperty(value="EnumSoundType",name="sound") + private Integer sound; + @TableField(exist = false) + private String soundDesc; + public String getSoundDesc(){ + if(this.sound != null){ + EnumSoundType soundEnum = EnumSoundType.getEnum(sound); + if(soundEnum != null){ + soundDesc = soundEnum.getMessage(); + } + } + return soundDesc; + } + + @io.swagger.annotations.ApiModelProperty(value="生成视频最大时长(s)",name="videoTime") + private Integer videoTime; + + @io.swagger.annotations.ApiModelProperty(value="可生成照片的次数",name="aiPhoto") + private Integer aiPhoto; + @io.swagger.annotations.ApiModelProperty(value="是否可唱歌",name="isSing") + private Integer isSing; + @io.swagger.annotations.ApiModelProperty(value="可生成脚本的次数",name="aiScript") + private Integer aiScript; + + @io.swagger.annotations.ApiModelProperty(value="EnumVideoFormatType",name="videoFormat") + private Integer videoFormat; + @TableField(exist = false) + private String videoFormatDesc; + public String getVideoFormatDesc(){ + if(this.videoFormat != null){ + EnumVideoFormatType videoFormatEnum = EnumVideoFormatType.getEnum(videoFormat); + if(videoFormatEnum != null){ + videoFormatDesc = videoFormatEnum.getMessage(); + } + } + return videoFormatDesc; + } + @io.swagger.annotations.ApiModelProperty(value="EnumAiTemplateType",name="template") + private Integer template; + @TableField(exist = false) + private String templateDesc; + public String getTemplateDesc(){ + if(this.template != null){ + EnumAiTemplateType templateEnum = EnumAiTemplateType.getEnum(template); + if(templateEnum != null){ + templateDesc = templateEnum.getMessage(); + } + } + return templateDesc; + } + + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="",name="updateDate") + private Date updateDate; + + @TableField(exist = false) + private Date startDate; + + @TableField(exist = false) + private Date endDate; + +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/UserLevelCreditLog.java b/suimangService/src/main/java/com/iformall/domain/po/UserLevelCreditLog.java new file mode 100644 index 0000000..0f9430f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/UserLevelCreditLog.java @@ -0,0 +1,61 @@ +package com.iformall.domain.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.util.Date; +import java.util.List; + +@TableName(value = "user_level_credit_log") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class UserLevelCreditLog extends TenantEntity { + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="",name="userId") + private Long userId; + + @io.swagger.annotations.ApiModelProperty(value="EnumProject ",name="projectType") + private Integer projectType; + + @io.swagger.annotations.ApiModelProperty(value="EnumPropertyLogType ",name="type") + private Integer type; + + @io.swagger.annotations.ApiModelProperty(value="",name="befourCredit") + private Integer befourCredit; + + @io.swagger.annotations.ApiModelProperty(value="",name="cieditNum") + private Integer creditNum; + + @io.swagger.annotations.ApiModelProperty(value="",name="afterCredit") + private Integer afterCredit; + + @io.swagger.annotations.ApiModelProperty(value="记录对应的业务ID",name="extraId") + private Long extraId; + + @io.swagger.annotations.ApiModelProperty(value="",name="remark") + private String remark; + + @io.swagger.annotations.ApiModelProperty(value="",name="detail") + private String detail; + + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + + @TableField(exist = false) + @io.swagger.annotations.ApiModelProperty(value="",name="extraIds") + private List extraIds; + + @TableField(exist = false) + private Date startDate; + + @TableField(exist = false) + private Date endDate; + +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/UserLevelPackage.java b/suimangService/src/main/java/com/iformall/domain/po/UserLevelPackage.java new file mode 100644 index 0000000..f54e851 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/UserLevelPackage.java @@ -0,0 +1,52 @@ +package com.iformall.domain.po; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.util.Date; + +@TableName(value = "user_level_package") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class UserLevelPackage extends TenantEntity { + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="套餐ID",name="packageId") + private Long packageId; + @io.swagger.annotations.ApiModelProperty(value="套餐等级",name="packageLevel") + private Integer packageLevel; + @io.swagger.annotations.ApiModelProperty(value="套餐色",name="packageColor") + private String packageColor; + + @io.swagger.annotations.ApiModelProperty(value="用户总积分",name="userCredits") + private Integer userCredits; + + @io.swagger.annotations.ApiModelProperty(value="剩余积分",name="residueCredits") + private Integer residueCredits; + + @io.swagger.annotations.ApiModelProperty(value="到期时间",name="expiresDate") + private Date expiresDate; + + @io.swagger.annotations.ApiModelProperty(value="",name="createDate") + private Date createDate; + + @io.swagger.annotations.ApiModelProperty(value="",name="updateDate") + private Date updateDate; + + + @TableField(exist = false) + private Integer addCredits; + + @TableField(exist = false) + private Integer addSumCredits; + + @TableField(exist = false) + private Integer reduceCredits; + +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxCUserBasicInfo.java b/suimangService/src/main/java/com/iformall/domain/po/WxCUserBasicInfo.java index 13144c2..0e84aa1 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxCUserBasicInfo.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxCUserBasicInfo.java @@ -107,8 +107,8 @@ public class WxCUserBasicInfo extends TenantEntityWithoutFinalTenantId { @io.swagger.annotations.ApiModelProperty(value="登录次数",name="loginCount") private Integer loginCount; - @Excel(name="成长值",width = 20, orderNum = "11") - @io.swagger.annotations.ApiModelProperty(value="成长值",name="poins") + @Excel(name="金币",width = 20, orderNum = "11") + @io.swagger.annotations.ApiModelProperty(value="金币",name="poins") private Integer poins; @io.swagger.annotations.ApiModelProperty(value="地址",name="address") diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxCVideoTable.java b/suimangService/src/main/java/com/iformall/domain/po/WxCVideoTable.java index e268447..0cea27e 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxCVideoTable.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxCVideoTable.java @@ -49,6 +49,8 @@ public class WxCVideoTable extends TenantEntityWithoutFinalTenantId { private String modelMd5; @io.swagger.annotations.ApiModelProperty(value = "数字人模板预处理信息md文件校验码", name = "preinfo_md5") private String preInfoMd5; + @io.swagger.annotations.ApiModelProperty(value = "", name = "mask") + private String mask; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxCVoiceTable.java b/suimangService/src/main/java/com/iformall/domain/po/WxCVoiceTable.java index 22d1a4e..5c83f2c 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxCVoiceTable.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxCVoiceTable.java @@ -54,6 +54,8 @@ public class WxCVoiceTable { private String styleDisplayName; @io.swagger.annotations.ApiModelProperty(value = "声纹风格样例文件链接", name = "style_demo") private String styleDemo; + @io.swagger.annotations.ApiModelProperty(value = "试听内容", name = "trialText") + private String trialText; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxMsgValidationcode.java b/suimangService/src/main/java/com/iformall/domain/po/WxMsgValidationcode.java index 8f7c1e7..3626803 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxMsgValidationcode.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxMsgValidationcode.java @@ -30,6 +30,8 @@ public class WxMsgValidationcode extends TenantEntity { private String signature; @io.swagger.annotations.ApiModelProperty(value="",name="code") private String code; + @io.swagger.annotations.ApiModelProperty(value="所属项目EnumProject",name="projectType") + private Integer projectType; @TableField(exist = false) private String createtimeStr; diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxPayAccount.java b/suimangService/src/main/java/com/iformall/domain/po/WxPayAccount.java index 32fe025..20205c2 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxPayAccount.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxPayAccount.java @@ -77,22 +77,6 @@ public class WxPayAccount extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="销售提点",name="sellRate") private Integer sellRate; - public String getPayNotifyV3Url(Integer projectType) { - if(projectType == null){ - return notifyUrl + "/pay/v3"; - } - return notifyUrl + "/" + projectType + "/pay/v3"; - } - public String getPayNotifyUrl() { - return notifyUrl + "/pay"; - } - public String getRefundNotifyV3Url() { - return notifyUrl + "/refund/v3"; - } - public String getRefundNotifyUrl() { - return notifyUrl + "/refund"; - } - @io.swagger.annotations.ApiModelProperty(value="微信支付分serviceId",name="serviceId") private String serviceId; @io.swagger.annotations.ApiModelProperty(value="微信支付分回调地址",name="payScoreNotifyUrl") diff --git a/suimangService/src/main/java/com/iformall/domain/po/WxThirdPartyApi.java b/suimangService/src/main/java/com/iformall/domain/po/WxThirdPartyApi.java index 337f4c6..b80617d 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/WxThirdPartyApi.java +++ b/suimangService/src/main/java/com/iformall/domain/po/WxThirdPartyApi.java @@ -2,6 +2,7 @@ package com.iformall.domain.po; import com.baomidou.mybatisplus.annotation.TableName; import com.iformall.domain.po.base.TenantEntity; +import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; @@ -29,21 +30,12 @@ public class WxThirdPartyApi extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="加密key",name="signKey") private String signKey; - @io.swagger.annotations.ApiModelProperty(value="",name="apiUrl") - private String apiUrl; - @io.swagger.annotations.ApiModelProperty(value="token",name="token") private String token; @io.swagger.annotations.ApiModelProperty(value="",name="tokenExpiredTime") private Date tokenExpiredTime; - @io.swagger.annotations.ApiModelProperty(value="登陆username",name="userName") - private String userName; - - @io.swagger.annotations.ApiModelProperty(value="登陆password",name="password") - private String password; - @io.swagger.annotations.ApiModelProperty(value="",name="version") private String version; @@ -52,5 +44,10 @@ public class WxThirdPartyApi extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="",name="tpId") private String tpId; - + + @ApiModelProperty("接入商id") + private Long serviceId; + + @ApiModelProperty("状态(0:正常,1:失效)") + private Integer status; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ApiDetail.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiDetail.java new file mode 100644 index 0000000..bb3cd25 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiDetail.java @@ -0,0 +1,95 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import java.util.Date; +import lombok.Data; + +/** + * + * @TableName api_detail + */ +@TableName(value ="api_detail") +@Data +public class ApiDetail extends BaseEntity { + /** + * 详情id + */ + @TableId + private Long id; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 修改时间 + */ + private Date updateTime; + + /** + * 菜单id + */ + private Long menuId; + + /** + * 菜单名称 + */ + private String menuName; + + /** + * 是否付费(0:否,1:是) + */ + private Integer chargeFlag; + + /** + * 是否需用户授权(0:否,1:是) + */ + private Integer authFlag; + + /** + * 描述 + */ + private String description; + + /** + * 平台地址 + */ + private String platformUrl; + + /** + * 系统参数 + */ + private String publicParam; + + /** + * 请求参数 + */ + private String requestParam; + + /** + * 响应参数 + */ + private String responseParam; + + /** + * 请求示例 + */ + private String requestSample; + + /** + * 响应示例 + */ + private String responseSample; + + /** + * 异常示例 + */ + private String exceptionSample; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ApiGuide.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiGuide.java new file mode 100644 index 0000000..07a750f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiGuide.java @@ -0,0 +1,60 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import java.util.Date; +import lombok.Data; + +/** + * + * @TableName api_guide + */ +@TableName(value ="api_guide") +@Data +public class ApiGuide extends BaseEntity { + /** + * 主键id + */ + @TableId + private Long id; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 修改时间 + */ + private Date updateTime; + + /** + * 发布时间 + */ + private Date releaseTime; + + /** + * 指南名称 + */ + private String name; + + /** + * 指南内容 + */ + private String content; + + /** + * 状态(0:正常,1:锁定) + */ + private Integer status; + + /** + * 删除(0:未删除,1:删除) + */ + private Integer deleteFlag; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ApiMenu.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiMenu.java new file mode 100644 index 0000000..3ce00cd --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ApiMenu.java @@ -0,0 +1,65 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import java.util.Date; +import lombok.Data; + +/** + * + * @TableName api_menu + */ +@TableName(value ="api_menu") +@Data +public class ApiMenu extends BaseEntity { + /** + * 菜单id + */ + @TableId + private Long id; + + /** + * 创建时间 + */ + private Date createTime; + + /** + * 修改时间 + */ + private Date updateTime; + + /** + * 菜单名称 + */ + private String name; + + /** + * 父菜单id + */ + private Long parentId; + + /** + * 状态(0:正常,1:锁定) + */ + private Integer status; + + /** + * 是否叶子节点(0:否,1:是) + */ + private Integer leafFlag; + + /** + * 是否删除(0:未删除,1:删除) + */ + private Integer deleteFlag; + + /** + * 是否删除(0:未删除,1:删除) + */ + private String content; + + @TableField(exist = false) + private static final long serialVersionUID = 1L; +} \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCode.java b/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCode.java index 549f533..dc495d6 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCode.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCode.java @@ -2,6 +2,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import io.swagger.models.auth.In; import lombok.Data; @@ -15,7 +17,7 @@ import java.util.Date; */ @Data @TableName("invite_code") -public class InviteCode implements Serializable { +public class InviteCode extends TenantEntity { private static final long serialVersionUID = 6951051673755053615L; /** @@ -23,14 +25,6 @@ public class InviteCode implements Serializable { */ @TableId private Long id; - /** - * 租户ID - */ - private String tenantId; - /** - * 父租户ID - */ - private String parentTenantId; /** * 用户id(wx_c_user_basic_info.id) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCodeInfo.java b/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCodeInfo.java index bf74252..b57b18c 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCodeInfo.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/InviteCodeInfo.java @@ -3,6 +3,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import io.swagger.models.auth.In; import lombok.Data; import lombok.ToString; @@ -17,7 +19,7 @@ import java.util.Date; */ @Data @TableName("invite_code_info") -public class InviteCodeInfo implements Serializable { +public class InviteCodeInfo extends TenantEntity { private static final long serialVersionUID = 5349786757453017803L; /** @@ -25,14 +27,6 @@ public class InviteCodeInfo implements Serializable { */ @TableId private Long id; - /** - * 租户ID - */ - private String tenantId; - /** - * 父租户ID - */ - private String parentTenantId; /** * 邀请的用户id(wx_c_user_basic_info.id) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/PersonMould.java b/suimangService/src/main/java/com/iformall/domain/po/sm/PersonMould.java index 40aa8e7..915aa92 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/PersonMould.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/PersonMould.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.iformall.common.SortColumn; +import com.iformall.domain.po.WxCUserBasicInfo; import com.iformall.domain.po.base.TenantEntity; import lombok.Data; import lombok.EqualsAndHashCode; @@ -107,6 +108,8 @@ public class PersonMould extends TenantEntity { @io.swagger.annotations.ApiModelProperty(value="模板第三方Id",name="mouldSmId") private String mouldSmId; + @TableField(exist = false) + private String mouldSmIdLike; @io.swagger.annotations.ApiModelProperty(value="素材",name="material") private String material; @@ -124,7 +127,28 @@ public class PersonMould extends TenantEntity { private Date createDate; @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") private Date updateDate; - + @io.swagger.annotations.ApiModelProperty(value="isDel",name="isDel") + private Integer isDel; + + + @TableField(exist = false) + private Integer customizedQuery; + @io.swagger.annotations.ApiModelProperty(value="是否私人定制EnumYesOrNo",name="customized") + private Integer customized; + @TableField(exist = false) + private List customPersonMouldIds; + + @TableField(exist = false) + private Long cuserId; + + @TableField(exist = false) + private String phone; + + @TableField(exist = false) + private Integer onlyCustomizedQuery = 0; + + @TableField(exist = false) + private List wxCUserBasicInfoList; public String getSalePriceStr() { if(salePrice!=null) { diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceInfo.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceInfo.java new file mode 100644 index 0000000..7e5bc53 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceInfo.java @@ -0,0 +1,72 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import com.iformall.domain.po.base.TenantEntity; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; + +import java.util.Date; +import java.util.List; + +/** + * 接入商实体 + * + * @author xmzhao71 + * @date 2023-10-19 + */ +@TableName(value = "service_info") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class ServiceInfo extends BaseEntity{ + + private Long id; + /** + * 创建时间 + */ + private Date createTime; + /** + * 更新时间 + */ + private Date updateTime; + /** + * 客户名称 + */ + private String name; + /** + * 所在地址 + */ + private String address; + /** + * 客户唯一凭证 + */ + private String code; + /** + * 接入方式(1:api接入,2:私有化接入) + */ + private Integer type; + /** + * 状态(0:正常,1:锁定) + */ + private Integer status; + /** + * 删除状态(0:未删除,1:已删除) + */ + private Integer delFlag; + + /** + * 登录用户 + */ + private Long mallUserInfo; + + /** + * 剩余时长 + */ + private Long remainingTimes; + @TableField(exist = false) + private Long times; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ServicePersonMould.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ServicePersonMould.java new file mode 100644 index 0000000..fc46cba --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ServicePersonMould.java @@ -0,0 +1,32 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; +import java.util.Date; +import java.util.List; + +@TableName(value = "service_person_mould") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class ServicePersonMould extends BaseEntity { + + private static final long serialVersionUID = 5153174991543978589L; + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="PersonMould编号",name="personMouldId") + private Long personMouldId; + @io.swagger.annotations.ApiModelProperty(value="ServiceInfo编码",name="serviceId") + private Long serviceId; + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + @TableField(exist = false) + private List mouldIds; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceVideoRecord.java b/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceVideoRecord.java new file mode 100644 index 0000000..ccab4fb --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/ServiceVideoRecord.java @@ -0,0 +1,55 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; + +import lombok.Data; + +import java.util.Date; + +/** + * @author xmzhao71 + * @date 2023-10-19 + */ +@TableName(value = "service_video_record") +@Data +public class ServiceVideoRecord extends BaseEntity{ + /** + * 主键id + */ + @TableField("id") + private Long id; + /** + * 创建时间 + */ + @TableField("create_time") + private Date createTime; + /** + * 更新时间 + */ + @TableField("update_time") + private Date updateTime; + /** + * 接入商标识 + */ + @TableField("service_id") + private Long serviceId; + /** + * 视频时长 + */ + @TableField("video_time") + private String videoTime; + + /** + * 视频链接 + */ + @TableField("video_url") + private String videoUrl; + + /** + * 视频记录ID + */ + @TableField("user_mould_video_id") + private Long userMouldVideoId; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserConsumptionPackage.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserConsumptionPackage.java index 707b3c0..4eb7ead 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserConsumptionPackage.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserConsumptionPackage.java @@ -3,6 +3,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import java.util.Date; import java.io.Serializable; import lombok.Data; @@ -17,7 +19,7 @@ import java.util.List; */ @Data @TableName("user_consumption_package" ) -public class UserConsumptionPackage implements Serializable { +public class UserConsumptionPackage extends TenantEntity { private static final long serialVersionUID = 7987400196899039170L; @@ -27,16 +29,6 @@ public class UserConsumptionPackage implements Serializable { @TableId private Integer id; - /** - * 租户ID - */ - private String tenantId; - - /** - * 父租户ID - */ - private String parentTenantId; - /** * 套餐类型(1、基础版,2、专业版,3、加强版) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreateVideoNum.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreateVideoNum.java index 2730523..06e7bf0 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreateVideoNum.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreateVideoNum.java @@ -2,6 +2,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import java.util.Date; import java.io.Serializable; import lombok.Data; @@ -14,7 +16,7 @@ import lombok.Data; */ @Data @TableName("user_create_video_num" ) -public class UserCreateVideoNum implements Serializable { +public class UserCreateVideoNum extends TenantEntity { private static final long serialVersionUID = 4995993777308528646L; @@ -24,16 +26,6 @@ public class UserCreateVideoNum implements Serializable { @TableId private Long id; - /** - * 租户ID - */ - private String tenantId; - - /** - * 父租户ID - */ - private String parentTenantId; - /** * 用户id(wx_c_user_basic_info.id) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreditLog.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreditLog.java index 650d038..b4d002e 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreditLog.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserCreditLog.java @@ -2,6 +2,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import java.util.Date; import java.io.Serializable; @@ -16,7 +18,7 @@ import lombok.Data; */ @Data @TableName("user_credit_log" ) -public class UserCreditLog implements Serializable { +public class UserCreditLog extends TenantEntity { private static final long serialVersionUID = 8595480777599856051L; @@ -26,16 +28,6 @@ public class UserCreditLog implements Serializable { @TableId private Long id; - /** - * 租户ID - */ - private String tenantId; - - /** - * 父租户ID - */ - private String parentTenantId; - /** * 用户id(wx_c_user_basic_info.id) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserMouldVideo.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserMouldVideo.java index 5dc9320..51fedb4 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserMouldVideo.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserMouldVideo.java @@ -197,8 +197,20 @@ public class UserMouldVideo extends TenantEntity { private Date createDate; @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") private Date updateDate; - + + @io.swagger.annotations.ApiModelProperty(value="消耗金币",name="costPoints") + private Integer costPoints; + @io.swagger.annotations.ApiModelProperty(value="消耗金币明细",name="costPointsDetail") + private String costPointsDetail; + @io.swagger.annotations.ApiModelProperty(value="isDel",name="isDel") + private Integer isDel; + @TableField(exist = false) private List videoStatuss; + + @TableField(exist = false) + private String phone; + @TableField(exist = false) + private List cUserIds; } diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserPackageDetail.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserPackageDetail.java index 6d654c5..0be483b 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserPackageDetail.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserPackageDetail.java @@ -3,6 +3,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import java.util.Date; import java.io.Serializable; import lombok.Data; @@ -15,7 +17,7 @@ import lombok.Data; */ @Data @TableName("user_package_detail" ) -public class UserPackageDetail implements Serializable { +public class UserPackageDetail extends TenantEntity { private static final long serialVersionUID = 8868339443558940187L; @@ -25,16 +27,6 @@ public class UserPackageDetail implements Serializable { @TableId private Integer id; - /** - * 租户ID - */ - private String tenantId; - - /** - * 父租户ID - */ - private String parentTenantId; - /** * 套餐类型(1、图片说话,2、口播) */ diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserPersonMould.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserPersonMould.java new file mode 100644 index 0000000..acc8fd1 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserPersonMould.java @@ -0,0 +1,34 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; +import java.util.Date; +import java.util.List; + +@TableName(value = "user_person_mould") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class UserPersonMould extends BaseEntity { + + private static final long serialVersionUID = 5153174991543978589L; + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="PersonMould编号",name="personMouldId") + private Long personMouldId; + @io.swagger.annotations.ApiModelProperty(value="WxCuserBasicInfo编码",name="userId") + private Long userId; + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + @TableField(exist = false) + private List cuserIds; + @TableField(exist = false) + private List mouldIds; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserTimeConfig.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserTimeConfig.java index 68f8465..aecf1a7 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/UserTimeConfig.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserTimeConfig.java @@ -2,6 +2,8 @@ package com.iformall.domain.po.sm; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.TenantEntity; + import java.util.Date; import java.io.Serializable; @@ -16,7 +18,7 @@ import lombok.Data; */ @Data @TableName("user_time_config" ) -public class UserTimeConfig implements Serializable { +public class UserTimeConfig extends TenantEntity { private static final long serialVersionUID = 2953038588956565523L; @@ -33,10 +35,6 @@ public class UserTimeConfig implements Serializable { */ private Long time; - private String tenantId; - - private String parentTenantId; - private Date createDate; private Date updateDate; diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/UserVoiceLanguage.java b/suimangService/src/main/java/com/iformall/domain/po/sm/UserVoiceLanguage.java new file mode 100644 index 0000000..5c39251 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/UserVoiceLanguage.java @@ -0,0 +1,34 @@ +package com.iformall.domain.po.sm; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.ToString; +import java.util.Date; +import java.util.List; + +@TableName(value = "user_voice_language") +@Data +@ToString(callSuper = true) +@EqualsAndHashCode(callSuper = true) +public class UserVoiceLanguage extends BaseEntity { + + private static final long serialVersionUID = 5153174991543978589L; + + protected Long id; + + @io.swagger.annotations.ApiModelProperty(value="VocieLanguage编码",name="voiceLanguageId") + private Long voiceLanguageId; + @io.swagger.annotations.ApiModelProperty(value="WxCuserBasicInfo编码",name="cUserId") + private Long userId; + @io.swagger.annotations.ApiModelProperty(value="创建时间",name="createDate") + private Date createDate; + @io.swagger.annotations.ApiModelProperty(value="更新时间",name="updateDate") + private Date updateDate; + @TableField(exist = false) + private List cuserIds; + @TableField(exist = false) + private List voiceLanguageIdList; +} diff --git a/suimangService/src/main/java/com/iformall/domain/po/sm/VoiceLanguage.java b/suimangService/src/main/java/com/iformall/domain/po/sm/VoiceLanguage.java index d2799f7..b6b2e2d 100644 --- a/suimangService/src/main/java/com/iformall/domain/po/sm/VoiceLanguage.java +++ b/suimangService/src/main/java/com/iformall/domain/po/sm/VoiceLanguage.java @@ -1,13 +1,16 @@ package com.iformall.domain.po.sm; +import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; +import com.iformall.domain.po.WxCUserBasicInfo; import com.iformall.domain.po.base.TenantEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import java.util.Date; +import java.util.List; import java.util.Objects; /** @@ -59,5 +62,24 @@ public class VoiceLanguage extends TenantEntity { * 是否删除1是0否 */ private Integer isDel; + + @TableField(exist = false) + private Integer customizedQuery; + @io.swagger.annotations.ApiModelProperty(value="是否私人定制EnumYesOrNo",name="customized") + private Integer customized; + @TableField(exist = false) + private List customizedVocideIds; + + @TableField(exist = false) + private Integer onlyCustomizedQuery = 0; + + @TableField(exist = false) + private Long cUserId; + + @TableField(exist = false) + private String phone; + + @TableField(exist = false) + private List wxCUserBasicInfoList; } diff --git a/suimangService/src/main/java/com/iformall/domain/vo/neuver/PageServiceInfoVO.java b/suimangService/src/main/java/com/iformall/domain/vo/neuver/PageServiceInfoVO.java new file mode 100644 index 0000000..674d79a --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/vo/neuver/PageServiceInfoVO.java @@ -0,0 +1,7 @@ +package com.iformall.domain.vo.neuver; + +import lombok.Data; + +@Data +public class PageServiceInfoVO { +} diff --git a/suimangService/src/main/java/com/iformall/domain/vo/sm/ListApiSubmenuVO.java b/suimangService/src/main/java/com/iformall/domain/vo/sm/ListApiSubmenuVO.java new file mode 100644 index 0000000..6d1cf16 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/vo/sm/ListApiSubmenuVO.java @@ -0,0 +1,27 @@ +package com.iformall.domain.vo.sm; + +import com.iformall.domain.po.sm.ApiDetail; +import com.iformall.domain.po.sm.ApiMenu; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import java.util.Date; +import java.util.List; + +@ApiModel(value = "查询某个api菜单所有子菜单相应数据") +@Data +public class ListApiSubmenuVO { + @ApiModelProperty("菜单id") + private Long id; + @ApiModelProperty("修改时间") + private Date updateTime; + @ApiModelProperty("菜单名称") + private String name; + @ApiModelProperty("状态(0:正常,1:锁定)") + private Integer status; + @ApiModelProperty("详情id") + private Long detailId; + @ApiModelProperty("接口描述") + private String description; +} diff --git a/suimangService/src/main/java/com/iformall/domain/vo/sm/PreviewVoiceVO.java b/suimangService/src/main/java/com/iformall/domain/vo/sm/PreviewVoiceVO.java new file mode 100644 index 0000000..c8cf05f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/domain/vo/sm/PreviewVoiceVO.java @@ -0,0 +1,11 @@ +package com.iformall.domain.vo.sm; + +import io.swagger.annotations.ApiModel; +import lombok.Data; + +@ApiModel(value = "音色预览请求参数") +@Data +public class PreviewVoiceVO { + private Double time; + private String url; +} diff --git a/suimangService/src/main/java/com/iformall/douyin/pay/DouYinPayHelper.java b/suimangService/src/main/java/com/iformall/douyin/pay/DouYinPayHelper.java index 9942734..056631a 100644 --- a/suimangService/src/main/java/com/iformall/douyin/pay/DouYinPayHelper.java +++ b/suimangService/src/main/java/com/iformall/douyin/pay/DouYinPayHelper.java @@ -10,6 +10,7 @@ import com.iformall.douyin.pay.orderQuery.QueryMerchantResult; import com.iformall.douyin.pay.orderQuery.QueryRefundResult; import com.iformall.douyin.pay.orderQuery.QuerySettleResult; import com.iformall.douyin.pay.preOrder.*; +import com.iformall.enums.EnumPayOrderStatus; import com.iformall.enums.EnumPayStatus; import com.iformall.enums.EnumProductOrderStatus; import com.iformall.exception.MallinkException; @@ -195,15 +196,15 @@ public class DouYinPayHelper { } String orderStatus = result.getOrderStatus(); if(StringUtils.isBlank(orderStatus)){ - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode(); + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode(); }else if("PROCESSING".equals(orderStatus)){//以观后效 - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENTING.getCode(); + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENTING.getCode(); }else if("SUCCESS".equals(orderStatus)){ - return EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode(); + return EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode(); }else if("FAIL".equals(orderStatus)){ - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode(); + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode(); }else if("TIMEOUT".equals(orderStatus)){ - return EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode(); + return EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode(); } throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "订单查询抖音支付状态失败"+payOrderNo); } diff --git a/suimangService/src/main/java/com/iformall/enums/EnumPayOrderStatus.java b/suimangService/src/main/java/com/iformall/enums/EnumPayOrderStatus.java new file mode 100644 index 0000000..e025e80 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/EnumPayOrderStatus.java @@ -0,0 +1,44 @@ +package com.iformall.enums; + +/** + * Created by Stormeye on 2018/08/09. + */ +public enum EnumPayOrderStatus { + + // +// ORDER_STATUS_PENDING_CREATE(0, "创建"), + ORDER_STATUS_PENDING_PAYMENT(1, "待支付"), + ORDER_STATUS_PENDING_PAYMENTING(2, "支付中"), + ORDER_STATUS_PAYMENT_SUCCESS(3, "已支付"), + ORDER_STATUS_OVERTIME_CANCEL(4, "已取消"), + ORDER_STATUS_PENDING_REFUND(5,"待退款"), + ORDER_STATUS_REFUND_SUCCESS(6, "已退款"), + ORDER_STATUS_REFUND_FAILD(7, "退款失败"), + ORDER_STATUS_REFUND_WAIT(10, "重复支付需要退款"), + ; + public static EnumPayOrderStatus getEnum(Integer code) { + for (EnumPayOrderStatus value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumPayOrderStatus(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } + +} diff --git a/suimangService/src/main/java/com/iformall/enums/EnumProductOrderPayVendor.java b/suimangService/src/main/java/com/iformall/enums/EnumProductOrderPayVendor.java index 222afc0..9f6f2cf 100644 --- a/suimangService/src/main/java/com/iformall/enums/EnumProductOrderPayVendor.java +++ b/suimangService/src/main/java/com/iformall/enums/EnumProductOrderPayVendor.java @@ -6,9 +6,9 @@ package com.iformall.enums; public enum EnumProductOrderPayVendor { PAY_WAY_WECHAT(1, "微信小程序",EnumAppPlat.WX.getCode(),EnumProfitSharing.PROFIT_SHARING_NO.getCode()), - PAY_WAY_WECHAT_NATIVE(2, "微信Native",null,null), + PAY_WAY_WECHAT_NATIVE(2, "微信Native",EnumAppPlat.WX.getCode(),EnumProfitSharing.PROFIT_SHARING_NO.getCode()), PAY_WAY_ALIPAY(3, "支付宝小程序",null,null), - PAY_WAY_ALIPAY_WAP(4, "支付宝H5",null,null), + PAY_WAY_ALIPAY_WAP(4, "支付宝H5",EnumAppPlat.ALI.getCode(),EnumProfitSharing.PROFIT_SHARING_NO.getCode()), PAY_WAY_TT(5, "抖音小程序",EnumAppPlat.TOUTIAO.getCode(),EnumProfitSharing.PROFIT_SHARING_NO.getCode()), ; public static EnumProductOrderPayVendor getEnum(Integer code) { diff --git a/suimangService/src/main/java/com/iformall/enums/EnumProductType.java b/suimangService/src/main/java/com/iformall/enums/EnumProductType.java index 2fc7579..f231c07 100644 --- a/suimangService/src/main/java/com/iformall/enums/EnumProductType.java +++ b/suimangService/src/main/java/com/iformall/enums/EnumProductType.java @@ -13,6 +13,7 @@ public enum EnumProductType { product_1(1, "充值金币"), + product_2(2, "充值套餐"), ; public static EnumProductType getEnum(Integer code) { diff --git a/suimangService/src/main/java/com/iformall/enums/EnumProject.java b/suimangService/src/main/java/com/iformall/enums/EnumProject.java index acc6dc0..ff33f2a 100644 --- a/suimangService/src/main/java/com/iformall/enums/EnumProject.java +++ b/suimangService/src/main/java/com/iformall/enums/EnumProject.java @@ -7,6 +7,8 @@ package com.iformall.enums; public enum EnumProject { + PROJECT_0(0,"通用"),//直播 + PROJECT_1(1,"邃芒慧播"),//直播 PROJECT_2(2,"邃芒慧影"),//数字人视频 PROJECT_3(3,"邃芒慧语"),//照片说话 diff --git a/suimangService/src/main/java/com/iformall/enums/EnumRefundOrderStatus.java b/suimangService/src/main/java/com/iformall/enums/EnumRefundOrderStatus.java new file mode 100644 index 0000000..97c09f3 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/EnumRefundOrderStatus.java @@ -0,0 +1,39 @@ +package com.iformall.enums; + +/** + * + */ +public enum EnumRefundOrderStatus { + REFUND_WAIT(0, "退款中"), + REFUND_REQ_SUCCESS(1, "退款申请成功"), + REFUND_REQ_FAIL(2, "退款申请失败"), + REFUND_REQ_AGREE(3, "同意退款"), + REFUND_SUCCESS(4, "退款成功"), + REFUND_FAIL(5, "退款失败"), + ; + + public static EnumRefundOrderStatus getEnum(Integer code) { + for (EnumRefundOrderStatus value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumRefundOrderStatus(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/suimangService/src/main/java/com/iformall/enums/sm/EnumAiTemplateType.java b/suimangService/src/main/java/com/iformall/enums/sm/EnumAiTemplateType.java new file mode 100644 index 0000000..23bd56b --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/sm/EnumAiTemplateType.java @@ -0,0 +1,34 @@ +package com.iformall.enums.sm; + +/** + * 数字人模板 + */ +public enum EnumAiTemplateType { + FREE(1, "免费"), + VIP(2, "VIP"); + + public static EnumAiTemplateType getEnum(Integer code) { + for (EnumAiTemplateType value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumAiTemplateType(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/suimangService/src/main/java/com/iformall/enums/sm/EnumTemplateType.java b/suimangService/src/main/java/com/iformall/enums/sm/EnumTemplateType.java new file mode 100644 index 0000000..cd99efe --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/sm/EnumTemplateType.java @@ -0,0 +1,34 @@ +package com.iformall.enums.sm; + +/** + * 数字人模板 + */ +public enum EnumTemplateType { + FREE(1, "免费"), + VIP(2, "VIP"); + + public static EnumTemplateType getEnum(Integer code) { + for (EnumTemplateType value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumTemplateType(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/suimangService/src/main/java/com/iformall/enums/sm/EnumThirdPartyType.java b/suimangService/src/main/java/com/iformall/enums/sm/EnumThirdPartyType.java new file mode 100644 index 0000000..b5ccf3d --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/sm/EnumThirdPartyType.java @@ -0,0 +1,31 @@ +package com.iformall.enums.sm; + +public enum EnumThirdPartyType { + API_JOIN(1, "API接入"), + PRIVATE_JOIN(2, "私有化接入"); + + public static EnumThirdPartyType getEnum(Integer code) { + for (EnumThirdPartyType value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumThirdPartyType(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/suimangService/src/main/java/com/iformall/enums/sm/EnumVideoFormatType.java b/suimangService/src/main/java/com/iformall/enums/sm/EnumVideoFormatType.java new file mode 100644 index 0000000..e6cedaa --- /dev/null +++ b/suimangService/src/main/java/com/iformall/enums/sm/EnumVideoFormatType.java @@ -0,0 +1,34 @@ +package com.iformall.enums.sm; + +/** + * 分辨率 + */ +public enum EnumVideoFormatType { + VIDEOFORMAT_720P(1, "720p"), + VIDEOFORMAT_1080P(2, "1080p"); + + public static EnumVideoFormatType getEnum(Integer code) { + for (EnumVideoFormatType value : values()) { + if (value.getCode().equals(code)) { + return value; + } + } + return null; + } + + private Integer code; + private String message; + + EnumVideoFormatType(Integer code, String message) { + this.code = code; + this.message = message; + } + + public Integer getCode() { + return code; + } + + public String getMessage() { + return message; + } +} diff --git a/suimangService/src/main/java/com/iformall/exception/BizException.java b/suimangService/src/main/java/com/iformall/exception/BizException.java new file mode 100644 index 0000000..522dbbb --- /dev/null +++ b/suimangService/src/main/java/com/iformall/exception/BizException.java @@ -0,0 +1,39 @@ +package com.iformall.exception; + +import com.iformall.common.ErrorCode; + +/** + * 业务异常,该异常不发送邮件 + * @author xmzhao71 + * @date 2023-09-12 + */ +public class BizException extends RuntimeException { + + private int code; + private String msg; + + public BizException(String msg) { + super(msg); + this.msg = msg; + } + + public BizException(int code, String msg) { + super(msg); + this.code = code; + this.msg = msg; + } + + public BizException(ErrorCode errCode) { + super(errCode.getMessage()); + this.code = errCode.getCode(); + this.msg = errCode.getMessage(); + } + + public int getCode() { + return code; + } + + public String getMsg() { + return msg; + } +} diff --git a/suimangService/src/main/java/com/iformall/exception/BizMessageException.java b/suimangService/src/main/java/com/iformall/exception/BizMessageException.java deleted file mode 100644 index 049f048..0000000 --- a/suimangService/src/main/java/com/iformall/exception/BizMessageException.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.iformall.exception; - -/** - * Created by Stormeye on 2018/8/10. - */ -public class BizMessageException extends RuntimeException { - public BizMessageException() { - super(); - } - - public BizMessageException(String bizMessage) { - super(bizMessage); - } -} diff --git a/suimangService/src/main/java/com/iformall/mapper/ApiDetailMapper.java b/suimangService/src/main/java/com/iformall/mapper/ApiDetailMapper.java new file mode 100644 index 0000000..e7574e4 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ApiDetailMapper.java @@ -0,0 +1,15 @@ +package com.iformall.mapper; + +import com.iformall.domain.po.sm.ApiDetail; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + * @Entity com.iformall.domain.po.sm.ApiDetail + */ +public interface ApiDetailMapper extends BaseMapper { + +} + + + + diff --git a/suimangService/src/main/java/com/iformall/mapper/ApiGuideMapper.java b/suimangService/src/main/java/com/iformall/mapper/ApiGuideMapper.java new file mode 100644 index 0000000..42a1d0d --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ApiGuideMapper.java @@ -0,0 +1,18 @@ +package com.iformall.mapper; + +import com.iformall.domain.po.sm.ApiGuide; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +import java.util.List; + +/** + * @Entity com.iformall.domain.po.sm.ApiGuide + */ +public interface ApiGuideMapper extends BaseMapper { + + List listApiGuide(ApiGuide apiGuide); +} + + + + diff --git a/suimangService/src/main/java/com/iformall/mapper/ApiMenuMapper.java b/suimangService/src/main/java/com/iformall/mapper/ApiMenuMapper.java new file mode 100644 index 0000000..636e5fe --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ApiMenuMapper.java @@ -0,0 +1,22 @@ +package com.iformall.mapper; + +import com.iformall.domain.po.sm.ApiMenu; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.iformall.domain.vo.sm.ListApiSubmenuVO; + +import java.util.List; + +/** + * @Entity com.iformall.domain.po.sm.ApiMenu + */ +public interface ApiMenuMapper extends BaseMapper { + + List listApiMenu(ApiMenu apiMenu); + + List listParentMenu(); + +} + + + + diff --git a/suimangService/src/main/java/com/iformall/mapper/MallUserInfoMapper.java b/suimangService/src/main/java/com/iformall/mapper/MallUserInfoMapper.java index e616bcd..57c8e8b 100644 --- a/suimangService/src/main/java/com/iformall/mapper/MallUserInfoMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/MallUserInfoMapper.java @@ -15,7 +15,7 @@ public interface MallUserInfoMapper extends CommonMapper { List findList(MallUserInfo mallUserInfo); - MallUserInfo selectByUserName(@Param("username") String username); + MallUserInfo selectByUserName(@Param("username") String username,@Param("projectType") Integer projectType); MallUserInfo selectByUserNameWebOpen(@Param("username") String username, @Param("webOpenId") String webOpenId); @@ -34,7 +34,7 @@ public interface MallUserInfoMapper extends CommonMapper { int cntByUserName(Map params); - List selectUsersByPhone(@Param("phone") String phone); + List selectUsersByPhone(@Param("phone") String phone,@Param("projectType") Integer projectType); List selectUsersByWebOpenId(@Param("webOpenId") String webOpenId); diff --git a/suimangService/src/main/java/com/iformall/mapper/ProductOrderMapper.java b/suimangService/src/main/java/com/iformall/mapper/ProductOrderMapper.java index a0cf472..52607b9 100644 --- a/suimangService/src/main/java/com/iformall/mapper/ProductOrderMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/ProductOrderMapper.java @@ -10,4 +10,6 @@ public interface ProductOrderMapper extends CommonMapper { List findList(ProductOrder record); int orderPayUpdStatus(ProductOrder productOrder); + + int findCount(ProductOrder record); } diff --git a/suimangService/src/main/java/com/iformall/mapper/ProductOrderPayMapper.java b/suimangService/src/main/java/com/iformall/mapper/ProductOrderPayMapper.java new file mode 100644 index 0000000..7c868ba --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ProductOrderPayMapper.java @@ -0,0 +1,19 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.ProductOrder; +import com.iformall.domain.po.ProductOrderPay; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface ProductOrderPayMapper extends CommonMapper { + + List findList(ProductOrderPay record); + + int orderPayUpdStatus(ProductOrderPay productOrderPay); + + ProductOrderPay selectByOrder(@Param("orderId")Long orderId, @Param("payVendor")Integer payVendor); + + void updStatusByOrder(@Param("orderId")Long orderId, @Param("payOrderStatus")Integer payOrderStatus); +} diff --git a/suimangService/src/main/java/com/iformall/mapper/ProductOrderRefundMapper.java b/suimangService/src/main/java/com/iformall/mapper/ProductOrderRefundMapper.java new file mode 100644 index 0000000..828bf15 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ProductOrderRefundMapper.java @@ -0,0 +1,15 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.ProductOrderPay; +import com.iformall.domain.po.ProductOrderRefund; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface ProductOrderRefundMapper extends CommonMapper { + + List findList(ProductOrderRefund record); + + int orderRefundUpdStatus(ProductOrderRefund record); +} diff --git a/suimangService/src/main/java/com/iformall/mapper/ProjectPackageDetailMapper.java b/suimangService/src/main/java/com/iformall/mapper/ProjectPackageDetailMapper.java new file mode 100644 index 0000000..289625d --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ProjectPackageDetailMapper.java @@ -0,0 +1,15 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.ProjectPackageDetail; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +public interface ProjectPackageDetailMapper extends CommonMapper{ + + List findList(ProjectPackageDetail record); + + ProjectPackageDetail selectByProject(@Param("packageId")Long packageId, @Param("projectType")Integer projectType); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/ServiceInfoMapper.java b/suimangService/src/main/java/com/iformall/mapper/ServiceInfoMapper.java new file mode 100644 index 0000000..702e498 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ServiceInfoMapper.java @@ -0,0 +1,27 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.sm.ServiceInfo; + +import java.util.List; + +import org.apache.ibatis.annotations.Param; + +/** + * 合作商service + * + * @author xmzhao71 + * @date 2023-10-24 + */ +public interface ServiceInfoMapper extends CommonMapper { + + /** + * 全查询合作商 + * + * @param serviceInfo + * @return {@link List}<{@link ServiceInfo}> + */ + List listServiceInfo(ServiceInfo serviceInfo); + + void reduceTimes(@Param("id") Long id,@Param("seconds") Long seconds); +} diff --git a/suimangService/src/main/java/com/iformall/mapper/ServicePersonMouldMapper.java b/suimangService/src/main/java/com/iformall/mapper/ServicePersonMouldMapper.java new file mode 100644 index 0000000..3fbfa4e --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ServicePersonMouldMapper.java @@ -0,0 +1,16 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.sm.ServicePersonMould; +import org.apache.ibatis.annotations.Param; +import java.util.List; + +public interface ServicePersonMouldMapper extends CommonMapper { + + List findMouldIdList(ServicePersonMould record); + + void deleteByServiceId(@Param("serviceId") Long serviceId); + + void saveBatch(@Param("list") List list); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/ServiceVideoRecordMapper.java b/suimangService/src/main/java/com/iformall/mapper/ServiceVideoRecordMapper.java new file mode 100644 index 0000000..36ce326 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/ServiceVideoRecordMapper.java @@ -0,0 +1,11 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServiceVideoRecord; + +public interface ServiceVideoRecordMapper extends CommonMapper { + + Float totalTimes(ServiceVideoRecord record); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/UserLevelCreditLogMapper.java b/suimangService/src/main/java/com/iformall/mapper/UserLevelCreditLogMapper.java new file mode 100644 index 0000000..585cd54 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/UserLevelCreditLogMapper.java @@ -0,0 +1,12 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.UserLevelCreditLog; + +import java.util.List; + +public interface UserLevelCreditLogMapper extends CommonMapper{ + + List findList(UserLevelCreditLog record); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/UserLevelPackageMapper.java b/suimangService/src/main/java/com/iformall/mapper/UserLevelPackageMapper.java new file mode 100644 index 0000000..b195b56 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/UserLevelPackageMapper.java @@ -0,0 +1,12 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.UserLevelPackage; + +import java.util.List; + +public interface UserLevelPackageMapper extends CommonMapper{ + + List findList(UserLevelPackage record); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/UserMouldVideoMapper.java b/suimangService/src/main/java/com/iformall/mapper/UserMouldVideoMapper.java index 9bd26e0..a1e1af4 100644 --- a/suimangService/src/main/java/com/iformall/mapper/UserMouldVideoMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/UserMouldVideoMapper.java @@ -24,4 +24,7 @@ public interface UserMouldVideoMapper extends CommonMapper List getSortList(UserMouldVideo record); List getNotHaveUrl(UserMouldVideo record); + + Integer checkVideoStatus(@Param("userId") Long userId, @Param("list") List list); + } diff --git a/suimangService/src/main/java/com/iformall/mapper/UserPersonMouldMapper.java b/suimangService/src/main/java/com/iformall/mapper/UserPersonMouldMapper.java new file mode 100644 index 0000000..018cec8 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/UserPersonMouldMapper.java @@ -0,0 +1,19 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.sm.UserPersonMould; + +import org.apache.ibatis.annotations.Param; +import java.util.List; + +public interface UserPersonMouldMapper extends CommonMapper { + + List findMouldIdList(UserPersonMould record); + + List findCUserIdList(UserPersonMould record); + + void deleteByCuserId(@Param("cUserId") Long cUserId); + + void saveBatch(@Param("list") List list); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/UserVoiceLanguageMapper.java b/suimangService/src/main/java/com/iformall/mapper/UserVoiceLanguageMapper.java new file mode 100644 index 0000000..2667e48 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/mapper/UserVoiceLanguageMapper.java @@ -0,0 +1,19 @@ +package com.iformall.mapper; + +import com.iformall.common.CommonMapper; +import com.iformall.domain.po.sm.UserVoiceLanguage; + +import org.apache.ibatis.annotations.Param; +import java.util.List; + +public interface UserVoiceLanguageMapper extends CommonMapper { + + List findVoiceIdList(UserVoiceLanguage record); + + List findCUserIdList(UserVoiceLanguage record); + + void deleteByCuserId(@Param("cUserId") Long cUserId); + + void saveBatch(@Param("list") List list); + +} diff --git a/suimangService/src/main/java/com/iformall/mapper/VoiceLanguageMapper.java b/suimangService/src/main/java/com/iformall/mapper/VoiceLanguageMapper.java index 1d5e054..af567e3 100644 --- a/suimangService/src/main/java/com/iformall/mapper/VoiceLanguageMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/VoiceLanguageMapper.java @@ -6,8 +6,34 @@ import com.iformall.domain.po.sm.VoiceLanguage; import org.apache.ibatis.annotations.Param; import java.util.HashSet; +import java.util.List; +/** + * 语种服务 + * + * @author xmzhao71 + * @date 2023-10-13 + */ public interface VoiceLanguageMapper extends CommonMapper { + + List findList(VoiceLanguage record); + void saveBatch(@Param("set") HashSet set); + + /** + * 根据地区语言查询语种信息 + * + * @param local + * @return {@link List}<{@link VoiceLanguage}> + */ + List listByLocal(@Param("local") String local); + + /** + * 根据语言查询语种信息 + * + * @param language + * @return {@link List}<{@link VoiceLanguage}> + */ + List listByLanguage(@Param("language") String language); } diff --git a/suimangService/src/main/java/com/iformall/mapper/WxCUserBasicInfoMapper.java b/suimangService/src/main/java/com/iformall/mapper/WxCUserBasicInfoMapper.java index 7c6b85f..9adcb23 100644 --- a/suimangService/src/main/java/com/iformall/mapper/WxCUserBasicInfoMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/WxCUserBasicInfoMapper.java @@ -69,5 +69,8 @@ public interface WxCUserBasicInfoMapper extends CommonMapper { List getById(Long id); - WxCVideoTable selectOne(Long id, long resource_id); + } diff --git a/suimangService/src/main/java/com/iformall/mapper/WxThirdPartyApiMapper.java b/suimangService/src/main/java/com/iformall/mapper/WxThirdPartyApiMapper.java index 1374b8c..1347eb4 100644 --- a/suimangService/src/main/java/com/iformall/mapper/WxThirdPartyApiMapper.java +++ b/suimangService/src/main/java/com/iformall/mapper/WxThirdPartyApiMapper.java @@ -9,4 +9,11 @@ public interface WxThirdPartyApiMapper extends CommonMapper findList(WxThirdPartyApi apiConfig); + /** + * 全查询秘钥 + * + * @param thirdPartyApi + * @return {@link List}<{@link WxThirdPartyApi}> + */ + List listThirdPartyApi(WxThirdPartyApi thirdPartyApi); } diff --git a/suimangService/src/main/java/com/iformall/service/MallUserInfoService.java b/suimangService/src/main/java/com/iformall/service/MallUserInfoService.java index ede0135..72273d6 100644 --- a/suimangService/src/main/java/com/iformall/service/MallUserInfoService.java +++ b/suimangService/src/main/java/com/iformall/service/MallUserInfoService.java @@ -31,7 +31,7 @@ public interface MallUserInfoService { * @param username * @return */ - MallUserInfo getByUsername(String username); + MallUserInfo getByUsername(String username,int projectType); /** @@ -121,14 +121,14 @@ public interface MallUserInfoService { * * @param username */ - int cntByUserName(String username); + int cntByUserName(String username,int projectType); /** * 查询手机号,用于校验手机号是否重复 * * @param phone */ - int cntByUserPhone(String phone); + int cntByUserPhone(String phone,int projectType); @@ -164,7 +164,7 @@ public interface MallUserInfoService { * @param phone * @return */ - List getUserByPhone(String phone); + List getUserByPhone(String phone,int projectType); void updateBOpenId(MallUserInfo user); diff --git a/suimangService/src/main/java/com/iformall/service/ProductOrderPayService.java b/suimangService/src/main/java/com/iformall/service/ProductOrderPayService.java new file mode 100644 index 0000000..bed0ba2 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/ProductOrderPayService.java @@ -0,0 +1,39 @@ +package com.iformall.service; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.ResultData; +import com.iformall.domain.po.ProductOrder; +import com.iformall.domain.po.ProductOrderPay; +import com.iformall.domain.po.WxAppinfo; +import com.iformall.domain.po.WxPayAccount; +import com.iformall.enums.EnumProductOrderPayVendor; +import com.iformall.service.pay.service.pay.PayAdapterService; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; + +import java.util.List; + +public interface ProductOrderPayService { + + /** + * 根据实体查询分页列表 + * + * @param record + * @param pageIndex + * @param pageSize + * @return + */ + PageInfo listAsPage(ProductOrderPay record, Integer pageIndex, Integer pageSize); + + void saveOrUpdate(ProductOrderPay record); + + ProductOrderPay getById(Long id); + + ProductOrderPay getByOrder(Long orderId,EnumProductOrderPayVendor payVendorEnum); + + ResultData createPay(Long orderId, EnumProductOrderPayVendor payVendorEnum, String openId); + + ResultData handleProductOrderByQuery(WxAppinfo appinfo,WxPayAccount payAccount,ProductOrderPay productOrderPay,PayAdapterService payAdapterService); + + void handleProductOrderSuccess(ProductOrderPay productOrderPay, PayQueryAdapterResult result); + +} diff --git a/suimangService/src/main/java/com/iformall/service/ProductOrderRefundService.java b/suimangService/src/main/java/com/iformall/service/ProductOrderRefundService.java new file mode 100644 index 0000000..9ad9fac --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/ProductOrderRefundService.java @@ -0,0 +1,31 @@ +package com.iformall.service; + +import com.github.pagehelper.PageInfo; +import com.iformall.common.ResultData; +import com.iformall.domain.po.ProductOrderPay; +import com.iformall.domain.po.ProductOrderRefund; +import com.iformall.domain.po.WxAppinfo; +import com.iformall.domain.po.WxPayAccount; +import com.iformall.enums.EnumProductOrderPayVendor; +import com.iformall.service.pay.service.pay.PayAdapterService; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; + +public interface ProductOrderRefundService { + + /** + * 根据实体查询分页列表 + * + * @param record + * @param pageIndex + * @param pageSize + * @return + */ + PageInfo listAsPage(ProductOrderRefund record, Integer pageIndex, Integer pageSize); + + void saveOrUpdate(ProductOrderRefund record); + + ProductOrderRefund getById(Long id); + + void handleRefund(ProductOrderPay orderPay); + +} diff --git a/suimangService/src/main/java/com/iformall/service/ProductOrderService.java b/suimangService/src/main/java/com/iformall/service/ProductOrderService.java index 0b67e0c..3a63da6 100644 --- a/suimangService/src/main/java/com/iformall/service/ProductOrderService.java +++ b/suimangService/src/main/java/com/iformall/service/ProductOrderService.java @@ -24,15 +24,12 @@ public interface ProductOrderService { ProductOrder getById(Long id); - ResultData createPay(ProductOrder productOrder); - - ResultData handleProductOrderByQuery(WxAppinfo appinfo,WxPayAccount payAccount,ProductOrder productOrder,PayAdapterService payAdapterService); - - void handleProductOrderSuccess(ProductOrder productOrder, PayQueryAdapterResult result); - List findList(ProductOrder record); void handldSharing(ProductOrder order); void handldTimeOut(Long id); + + Integer findPaidCount(ProductOrder record); + } diff --git a/suimangService/src/main/java/com/iformall/service/ProductService.java b/suimangService/src/main/java/com/iformall/service/ProductService.java index 7aa7d63..25812f2 100644 --- a/suimangService/src/main/java/com/iformall/service/ProductService.java +++ b/suimangService/src/main/java/com/iformall/service/ProductService.java @@ -3,6 +3,8 @@ package com.iformall.service; import com.github.pagehelper.PageInfo; import com.iformall.domain.po.Product; +import java.util.List; + public interface ProductService { /** @@ -17,4 +19,6 @@ public interface ProductService { Product getById(Long id); + List findListDetail(Product record, Integer projectType); + } diff --git a/suimangService/src/main/java/com/iformall/service/WxAppinfoService.java b/suimangService/src/main/java/com/iformall/service/WxAppinfoService.java index 7ea31cc..b9a83fe 100644 --- a/suimangService/src/main/java/com/iformall/service/WxAppinfoService.java +++ b/suimangService/src/main/java/com/iformall/service/WxAppinfoService.java @@ -52,15 +52,6 @@ public interface WxAppinfoService { */ WxAppinfo getById(Long id); - /** - * 多个存在获取集团的。 - * - * @param appId - * @return - */ - WxAppinfo getOnlyByAppId(String appId); - WxAppinfo getByAppId(String appId,String tenantId); - /** * 获取c端小程序信息 * @return @@ -85,14 +76,15 @@ public interface WxAppinfoService { */ void deleteById(Long id); - WxAppinfo getOnlyByAppIdFromRedis(String appId); - WxAppinfo getByAppIdFromRedis(String appId,String tenantId); - WxAppinfo getByIdFromRedis(Long id); - WxAppinfo getCAppInfoFromRedis(String tenantId, EnumAppPlat appPlat); + WxAppinfo getProjectCAppInfo(Integer projectType, Integer plat); WxAppinfo getProjectCAppInfoFromRedis(Integer projectType, Integer plat); + WxAppinfo getProjectCAppInfo(String appId, Integer projectType); + + WxAppinfo getProjectCAppInfoFromRedis(String appId, Integer projectType); + } diff --git a/suimangService/src/main/java/com/iformall/service/WxCUserAuthorityService.java b/suimangService/src/main/java/com/iformall/service/WxCUserAuthorityService.java index 201a62e..1c2d76a 100644 --- a/suimangService/src/main/java/com/iformall/service/WxCUserAuthorityService.java +++ b/suimangService/src/main/java/com/iformall/service/WxCUserAuthorityService.java @@ -5,5 +5,7 @@ import com.iformall.common.ResultData; import java.util.Map; public interface WxCUserAuthorityService { + Map getAuthor(Long id, String code, Integer type, Long resourceId); + } diff --git a/suimangService/src/main/java/com/iformall/service/WxCUserBasicInfoService.java b/suimangService/src/main/java/com/iformall/service/WxCUserBasicInfoService.java index 29ed2ee..17701ab 100644 --- a/suimangService/src/main/java/com/iformall/service/WxCUserBasicInfoService.java +++ b/suimangService/src/main/java/com/iformall/service/WxCUserBasicInfoService.java @@ -205,5 +205,12 @@ public interface WxCUserBasicInfoService { // void updateCode(Long id, String mcode); + + void reducePoints(Long id,String finalTenantId,Integer reducePoints); + void addPoints(Long id,String finalTenantId,Integer addPoints); + + List findIdsListByPhone(String finalTenantId,String phone); + + List findList(WxCUserBasicInfo basicInfo); } diff --git a/suimangService/src/main/java/com/iformall/service/WxCVideoService.java b/suimangService/src/main/java/com/iformall/service/WxCVideoService.java index 0d96c1c..84674f8 100644 --- a/suimangService/src/main/java/com/iformall/service/WxCVideoService.java +++ b/suimangService/src/main/java/com/iformall/service/WxCVideoService.java @@ -8,7 +8,7 @@ import java.util.Map; public interface WxCVideoService { - Map getById(Long id) throws Exception; + Map getById(Long userId) throws Exception; WxCVideoTable selectOne(Long id, long resource_id); } diff --git a/suimangService/src/main/java/com/iformall/service/WxCVoiceService.java b/suimangService/src/main/java/com/iformall/service/WxCVoiceService.java index f1b86ed..4c11bc3 100644 --- a/suimangService/src/main/java/com/iformall/service/WxCVoiceService.java +++ b/suimangService/src/main/java/com/iformall/service/WxCVoiceService.java @@ -8,9 +8,11 @@ import java.util.List; import java.util.Map; public interface WxCVoiceService { - Map getById(Long id,String phone); + + Map getById(Long userId); List chooseType(Long id); - Map voicePreview(AiPreviewParam aiPreviewParam); + Map voicePreview(Long voiceId, String voiceStyle, String text, Integer speed); + } diff --git a/suimangService/src/main/java/com/iformall/service/WxMsgValidationcodeService.java b/suimangService/src/main/java/com/iformall/service/WxMsgValidationcodeService.java index a59788f..9188cec 100644 --- a/suimangService/src/main/java/com/iformall/service/WxMsgValidationcodeService.java +++ b/suimangService/src/main/java/com/iformall/service/WxMsgValidationcodeService.java @@ -37,9 +37,9 @@ public interface WxMsgValidationcodeService { void deleteById(Long id); - ResultData sendvalidationcode(WxMsgValidationcode record); + ResultData sendvalidationcode(WxMsgValidationcode record,int projectType); - boolean checkCodeValid(String phone, String code); + boolean checkCodeValid(String phone, String code,int projectType); ResultData hasvalidationcode(WxMsgValidationcode record); diff --git a/suimangService/src/main/java/com/iformall/service/WxPayBillService.java b/suimangService/src/main/java/com/iformall/service/WxPayBillService.java deleted file mode 100644 index 97a48a3..0000000 --- a/suimangService/src/main/java/com/iformall/service/WxPayBillService.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.iformall.service; - -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxAppinfo; -import com.iformall.domain.po.WxMerchant; -import com.iformall.domain.po.WxPayBill; -import com.iformall.enums.EnumPayWay; - -import java.util.Map; - -/** - * @author gongbiao - */ -public interface WxPayBillService { - - /** - * 创建支付订单 - * - * @param record 支付订单请求 - * @param payWay - * @return - */ - ResultData createPayBill(WxMerchant merchant,Integer billTypeValue,WxAppinfo appInfo, WxPayBill record, EnumPayWay payWay); - - /** - * 微信支付订单查询 - * @param appInfo 支付订单Appinfo - * @param record 支付订单 - */ - ResultData payBillQuery(WxAppinfo appInfo, WxPayBill record); - - /** - * 微信支付关闭订单 - * @param appInfo 支付订单Appinfo - * @param record 支付订单 - */ - ResultData payBillClose(WxAppinfo appInfo, WxPayBill record); - - /** - * 异步通知 - * - * @param paramMap 异步通知参数 - * @param payWay 支付方式 - * @return - */ - String notify(String tenantId,Map paramMap, EnumPayWay payWay); - - /** - * 支付成功处理 - * - * @param record - * @param transactionId - */ - void handleBillPaySuccess(WxPayBill record, String transactionId); - - /** - * 支付状态处理 - * - * @param record - */ - void handlePayBillStatusUpdate(WxPayBill record); - - - WxPayBill getById(Long payBillId); - - void updatePayBillStatus(WxPayBill payBill); - - WxPayBill queryPayBill(WxPayBill payBill); - -} diff --git a/suimangService/src/main/java/com/iformall/service/WxRefundOrderService.java b/suimangService/src/main/java/com/iformall/service/WxRefundOrderService.java index 4a50d3e..f10f523 100644 --- a/suimangService/src/main/java/com/iformall/service/WxRefundOrderService.java +++ b/suimangService/src/main/java/com/iformall/service/WxRefundOrderService.java @@ -41,13 +41,6 @@ public interface WxRefundOrderService { * @return */ ResultData queryRefundOrder(WxAppinfo appInfo, WxRefundOrder record); - /** - * 异步通知 - * @param paramMap 异步通知参数 - * @param payWay 支付方式 - * @return - */ - String notify(Map paramMap, EnumPayWay payWay,EnumPayVersion payVersion); /** * 处理退款成功 diff --git a/suimangService/src/main/java/com/iformall/service/WxThirdPartyApiService.java b/suimangService/src/main/java/com/iformall/service/WxThirdPartyApiService.java index 4f37ecd..fa372ae 100644 --- a/suimangService/src/main/java/com/iformall/service/WxThirdPartyApiService.java +++ b/suimangService/src/main/java/com/iformall/service/WxThirdPartyApiService.java @@ -1,5 +1,8 @@ package com.iformall.service; +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveThirdPartyApiDTO; +import com.iformall.domain.dto.sm.UpdateThirdPartyApiStatusDTO; import com.iformall.domain.po.WxThirdPartyApi; import java.util.List; @@ -18,4 +21,31 @@ public interface WxThirdPartyApiService { WxThirdPartyApi findByApp(String appId, String appKey); + /** + * 分页查询秘钥 + * + * @param thirdPartyApi + * @param pageNum + * @param pageSize + * @return {@link PageInfo}<{@link WxThirdPartyApi}> + */ + PageInfo pageThirdPartyApi(WxThirdPartyApi thirdPartyApi, Integer pageNum, Integer pageSize); + + /** + * 新增秘钥 + * + * @param dto + */ + void saveThirdPartyApi(SaveThirdPartyApiDTO dto); + + /** + * 修改秘钥状态 + * + * @param dto + */ + void updateThirdPartyApiStatus(UpdateThirdPartyApiStatusDTO dto); + + WxThirdPartyApi getThirdPartyApi(Long id); + WxThirdPartyApi getThirdPartyApiByServiceId(Long id); + } diff --git a/suimangService/src/main/java/com/iformall/service/helper/WxPayOrderServiceHelper.java b/suimangService/src/main/java/com/iformall/service/helper/WxPayOrderServiceHelper.java index 2f94991..0d7209e 100644 --- a/suimangService/src/main/java/com/iformall/service/helper/WxPayOrderServiceHelper.java +++ b/suimangService/src/main/java/com/iformall/service/helper/WxPayOrderServiceHelper.java @@ -73,21 +73,21 @@ public class WxPayOrderServiceHelper { return null; } - public static EnumProductOrderStatus getProductOrderStatus(String trade_state) { + public static EnumPayOrderStatus getProductOrderStatus(String trade_state) { if ("SUCCESS".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS; + return EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS; }else if ("REFUND".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_REFUND_SUCCESS; + return EnumPayOrderStatus.ORDER_STATUS_REFUND_SUCCESS; }else if ("NOTPAY".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT; + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT; }else if ("CLOSED".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL; + return EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL; }else if ("REVOKED".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT; + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT; }else if ("USERPAYING".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENTING; + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENTING; }else if ("PAYERROR".equals(trade_state)) { - return EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT; + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT; } return null; } diff --git a/suimangService/src/main/java/com/iformall/service/impl/MallUserInfoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/MallUserInfoServiceImpl.java index 9d4aad3..f138c8c 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/MallUserInfoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/MallUserInfoServiceImpl.java @@ -106,8 +106,8 @@ public class MallUserInfoServiceImpl implements MallUserInfoService { } @Override - public List getUserByPhone(String phone) { - return mallUserInfoMapper.selectUsersByPhone(phone); + public List getUserByPhone(String phone,int projectType) { + return mallUserInfoMapper.selectUsersByPhone(phone,projectType); } @Override @@ -209,21 +209,23 @@ public class MallUserInfoServiceImpl implements MallUserInfoService { } @Override - public MallUserInfo getByUsername(String username) { - return mallUserInfoMapper.selectByUserName(username); + public MallUserInfo getByUsername(String username,int projectType) { + return mallUserInfoMapper.selectByUserName(username,projectType); } @Override - public int cntByUserName(String username) { + public int cntByUserName(String username,int projectType) { Map params = new HashMap<>(); params.put("username", username); + params.put("projectType", projectType); return mallUserInfoMapper.cntByUserName(params); } @Override - public int cntByUserPhone(String phone) { + public int cntByUserPhone(String phone,int projectType) { Map params = new HashMap<>(); params.put("phone", phone); + params.put("projectType", projectType); return mallUserInfoMapper.cntByUserName(params); } @@ -259,7 +261,7 @@ public class MallUserInfoServiceImpl implements MallUserInfoService { @Override public ResultData updatepwd(MallUserInfo user, String code) { - if(checkCodeValid(user, code)) { + //if(checkCodeValid(user, code)) { try { MallUserInfo updateUser = new MallUserInfo(); updateUser.setId(user.getId()); @@ -270,9 +272,9 @@ public class MallUserInfoServiceImpl implements MallUserInfoService { logger.error("db failed: 用户-" + user.getUsername() + ", e:" + e.getMessage()); throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "DB FAILD " + e.getMessage()); } - } else { - return new ResultData(ErrorCode.MSG_VERIFY_CODE_NOT_FOUND, false); - } +// } else { +// return new ResultData(ErrorCode.MSG_VERIFY_CODE_NOT_FOUND, false); +// } return new ResultData(); } diff --git a/suimangService/src/main/java/com/iformall/service/impl/ProductOrderPayServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderPayServiceImpl.java new file mode 100644 index 0000000..222b726 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderPayServiceImpl.java @@ -0,0 +1,293 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.IdWorker; +import com.iformall.common.ResultData; +import com.iformall.domain.po.*; +import com.iformall.enums.*; +import com.iformall.exception.MallinkException; +import com.iformall.mapper.ProductMapper; +import com.iformall.mapper.ProductOrderMapper; +import com.iformall.mapper.ProductOrderPayMapper; +import com.iformall.mapper.ProductOrderSharingMapper; +import com.iformall.service.*; +import com.iformall.service.pay.PayServiceFactory; +import com.iformall.service.pay.service.pay.PayAdapterService; +import com.iformall.service.pay.service.pay.entity.PayAdapterResult; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; +import com.iformall.service.pay.service.refund.RefundPayAdapterService; +import com.iformall.service.project.ProjectFactory; +import com.iformall.utils.DateUtils; +import com.iformall.utils.RedisLock; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.aop.framework.AopContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; +import java.util.List; + +@Service +@Slf4j +public class ProductOrderPayServiceImpl implements ProductOrderPayService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + ProductOrderMapper productOrderMapper; + + @Autowired + ProductOrderPayMapper productOrderPayMapper; + + @Autowired + ProductOrderSharingMapper productOrderSharingMapper; + + @Autowired + ProductMapper productMapper; + + @Autowired + UserBasicPropertyService userBasicPropertyService; + + @Autowired + WxAppinfoService wxAppinfoService; + + @Autowired + WxPayAccountService wxPayAccountService; + + @Autowired + ProductOrderRefundService productOrderRefundService; + + @Autowired + PayServiceFactory payServiceFactory; + + @Autowired + ProjectFactory projectFactory; + + @Autowired + RedisLock redisLock; + + @Override + public PageInfo listAsPage(ProductOrderPay record, Integer pageIndex, Integer pageSize) { + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> productOrderPayMapper.findList(record)); + } + + @Override + public void saveOrUpdate(ProductOrderPay record) { + Date now = new Date(); + if (record.getId() == null) { + final IdWorker idWorker = IdWorker.get(); + record.setId(idWorker.nextId()); + record.setCreateDate(now); + record.setUpdateDate(now); + productOrderPayMapper.insert(record); + } else { + record.setUpdateDate(now); + productOrderPayMapper.updateById(record); + } + } + + @Override + public ProductOrderPay getById(Long id) { + return productOrderPayMapper.selectById(id); + } + + @Override + public ProductOrderPay getByOrder(Long orderId, EnumProductOrderPayVendor payVendorEnum) { + return productOrderPayMapper.selectByOrder(orderId,payVendorEnum.getCode()); + } + + @Override + public ResultData createPay(Long orderId, EnumProductOrderPayVendor payVendorEnum, String openId) { + + ProductOrder productOrder = productOrderMapper.selectById(orderId); + if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ + return new ResultData(ErrorCode.ORDER_IS_FAIL.getCode(),"订单已取消或已支付"); + } + + WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(productOrder.getProjectType(), payVendorEnum.getPlat()); + if(appinfo == null){ + return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付应用"); + } + WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); + if(payAccount == null){ + return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付配置"); + } + + PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(payVendorEnum.getCode()); + if(payAdapterService == null){ + return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"不支持当前支付"); + } + + ProductOrderPay productOrderPay = productOrderPayMapper.selectByOrder(orderId,payVendorEnum.getCode()); + Date now = new Date(); + if(productOrderPay != null){ + ResultData resultData = handleProductOrderByQuery(appinfo,payAccount,productOrderPay,payAdapterService); + if(ResultData.SUCCESS != resultData.code){ + return resultData; + } + if(EnumPayOrderStatus.ORDER_STATUS_PENDING_REFUND.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_SUCCESS.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_FAILD.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_WAIT.getCode().equals(productOrderPay.getPayOrderStatus())){ + return new ResultData(ErrorCode.ORDER_IS_FAIL.getCode(),"当前订单存在异常,请查看支付记录"); + } + if(!EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrderPay.getPayOrderStatus())){ + return new ResultData(ErrorCode.ORDER_IS_FAIL.getCode(),"订单已取消或已支付"); + } + }else{ + productOrderPay = new ProductOrderPay(); + final IdWorker idWorker = IdWorker.get(); + productOrderPay.setId(idWorker.nextId()); + productOrderPay.setOrderId(productOrder.getId()); + productOrderPay.setOrderNumber(productOrder.getId().toString()); + productOrderPay.setPayAmount(productOrder.getOrderPrice()); + productOrderPay.setUserId(productOrder.getUserId()); + productOrderPay.setOrderDetail(productOrder.getProductTitle()); + productOrderPay.setOpenId(openId); + productOrderPay.setProjectType(productOrder.getProjectType()); + productOrderPay.setPayVendor(payVendorEnum.getCode()); + productOrderPay.setPayOrderStatus(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + productOrderPay.setProfitSharing(payVendorEnum.getProfitSharing()); + productOrderPay.setCreateDate(now); + productOrderPay.setUpdateDate(now); + productOrderPayMapper.insert(productOrderPay); + } + + try { + PayAdapterResult payResult = payAdapterService.createPay(productOrderPay, appinfo, payAccount); + if(payResult.isSuccess()){ + ProductOrderPay updPay = new ProductOrderPay(); + updPay.setId(productOrderPay.getId()); + updPay.setTransactionId(payResult.getTransactionId()); + updPay.setUpdateDate(new Date()); + productOrderPayMapper.updateById(updPay); + return new ResultData(payResult.getData()); + }else{ + return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(), payResult.getMsg(), payResult.getData()); + } + } catch (Exception e) { + logger.error("创建支付单异常 ",e); + return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"支付订单异常"); + } + } + + @Override + public ResultData handleProductOrderByQuery(WxAppinfo appinfo,WxPayAccount payAccount,ProductOrderPay productOrderPay,PayAdapterService payAdapterService) { + + try { + PayQueryAdapterResult result = payAdapterService.queryPayStatus(productOrderPay, appinfo, payAccount); + Integer productOrderStatus = result.getCode(); + if(productOrderStatus == null){ + return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"查询支付单异常"); + } + + if(EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode().equals(productOrderStatus)){ + ProductOrderPayServiceImpl proxy = (ProductOrderPayServiceImpl) AopContext.currentProxy(); + proxy.handleProductOrderSuccess(productOrderPay,result); + }else if(EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode().equals(productOrderStatus) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_SUCCESS.getCode().equals(productOrderStatus)){ + + productOrderPay.setOpenId(result.getOpenId()); + productOrderPay.setTransactionId(result.getTransactionId()); + productOrderPay.setPayTime(result.getPayTime()); + productOrderPay.setPayWay(result.getWay()); + productOrderPay.setPayOrderStatus(productOrderStatus); +// productOrder.setIsOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + productOrderPay.setUpdateDate(new Date()); + int num = productOrderPayMapper.orderPayUpdStatus(productOrderPay); + + }else if(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrderStatus)){ + + }else{ + return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"支付单状态异常"); + } + } catch (Exception e) { + logger.error("查询支付单异常 ",e); + return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),e.getMessage()); + } + return new ResultData(); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) + public void handleProductOrderSuccess(ProductOrderPay productOrderPay, PayQueryAdapterResult result) { + String lockKey = "productOrderPay:success:"+productOrderPay.getOrderId(); + long time = System.currentTimeMillis() + 5000; + String timeStr = String.valueOf(time); + try{ +// while (!redisLock.lock2(lockKey, timeStr)){ +// Thread.sleep(1000); +// } + if(!redisLock.lock2(lockKey, timeStr)){ + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"当前订单处理中,请稍后重试"); + } + ProductOrderPay orderPay = productOrderPayMapper.selectById(productOrderPay.getId()); + if(EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode().equals(orderPay.getPayOrderStatus())){ + return; + } + if(EnumPayOrderStatus.ORDER_STATUS_PENDING_REFUND.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_SUCCESS.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_FAILD.getCode().equals(productOrderPay.getPayOrderStatus()) + || EnumPayOrderStatus.ORDER_STATUS_REFUND_WAIT.getCode().equals(productOrderPay.getPayOrderStatus())){ + logger.info("当前支付订单已处理:"+productOrderPay.getId()); + return ; + } + + Date now = new Date(); + productOrderPay.setOpenId(result.getOpenId()); + productOrderPay.setTransactionId(result.getTransactionId()); + productOrderPay.setPayTime(result.getPayTime()); + productOrderPay.setPayOrderStatus(EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode()); + + ProductOrder order = productOrderMapper.selectById(productOrderPay.getOrderId()); + if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(order.getOrderStatus())){ + productOrderPay.setPayOrderStatus(EnumPayOrderStatus.ORDER_STATUS_REFUND_WAIT.getCode()); + } + productOrderPay.setUpdateDate(now); + productOrderPayMapper.orderPayUpdStatus(productOrderPay); + + if(EnumPayOrderStatus.ORDER_STATUS_REFUND_WAIT.getCode().equals(productOrderPay.getPayOrderStatus())){ + logger.info("当前订单异常支付,退款处理"); + productOrderRefundService.handleRefund(productOrderPay); + return; + } + + order.setOpenId(productOrderPay.getOpenId()); + order.setPayVendor(productOrderPay.getPayVendor()); + order.setTransactionId(productOrderPay.getTransactionId()); + order.setPayment(productOrderPay.getPayAmount()); + order.setPaymentTime(productOrderPay.getPayTime()); + order.setPayWay(productOrderPay.getPayWay()); + order.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode()); + order.setUpdateDate(now); + productOrderMapper.orderPayUpdStatus(order); + + Product product = productMapper.selectById(order.getProductId()); + //智象 + if (product.getProjectType().intValue() == EnumProject.PROJECT_5.getCode().intValue()) { + if(EnumProductType.product_1.getCode().equals(product.getType())){ + userBasicPropertyService.updUserGlod(order.getUserId(),product.getProjectType(),EnumPropertyLogType.RECHARGE.getCode(), + order.getId(),product.getGlod(),now); + }else if(EnumProductType.product_2.getCode().equals(product.getType())){ + } + }else { + projectFactory.getProjectService(product.getProjectType()).handlePaidOrder(order.getUserId(),order.getFinalTenantId(),product); + } + }catch(MallinkException e){ + throw e; + }catch(Exception e){ + throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR); + }finally { + redisLock.unlock(lockKey, timeStr); + } + + } + + +} diff --git a/suimangService/src/main/java/com/iformall/service/impl/ProductOrderRefundServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderRefundServiceImpl.java new file mode 100644 index 0000000..03ae4ea --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderRefundServiceImpl.java @@ -0,0 +1,122 @@ +package com.iformall.service.impl; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.ErrorCode; +import com.iformall.common.IdWorker; +import com.iformall.common.ResultData; +import com.iformall.domain.po.*; +import com.iformall.enums.*; +import com.iformall.exception.MallinkException; +import com.iformall.mapper.*; +import com.iformall.service.*; +import com.iformall.service.pay.PayServiceFactory; +import com.iformall.service.pay.service.pay.PayAdapterService; +import com.iformall.service.pay.service.pay.entity.PayAdapterResult; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; +import com.iformall.service.pay.service.refund.RefundPayAdapterService; +import com.iformall.service.pay.service.refund.entity.RefundAdapterResult; +import com.iformall.utils.RedisLock; +import lombok.extern.slf4j.Slf4j; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.aop.framework.AopContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Date; + +@Service +@Slf4j +public class ProductOrderRefundServiceImpl implements ProductOrderRefundService { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Autowired + ProductOrderRefundMapper productOrderRefundMapper; + + @Autowired + ProductOrderPayMapper productOrderPayMapper; + + @Autowired + PayServiceFactory payServiceFactory; + + @Autowired + WxAppinfoService wxAppinfoService; + + @Autowired + WxPayAccountService wxPayAccountService; + + @Override + public PageInfo listAsPage(ProductOrderRefund record, Integer pageIndex, Integer pageSize) { + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> productOrderRefundMapper.findList(record)); + } + + @Override + public void saveOrUpdate(ProductOrderRefund record) { + Date now = new Date(); + if (record.getId() == null) { + final IdWorker idWorker = IdWorker.get(); + record.setId(idWorker.nextId()); + record.setCreateDate(now); + record.setUpdateDate(now); + productOrderRefundMapper.insert(record); + } else { + record.setUpdateDate(now); + productOrderRefundMapper.updateById(record); + } + } + + @Override + public ProductOrderRefund getById(Long id) { + return productOrderRefundMapper.selectById(id); + } + + @Override + public void handleRefund(ProductOrderPay orderPay) { + String refundReason = "重复支付退款"; + + Date now = new Date(); + ProductOrderRefund record = new ProductOrderRefund(); + final IdWorker idWorker = IdWorker.get(); + record.setId(idWorker.nextId()); + record.setOrderId(orderPay.getOrderId()); + record.setOrderNumber(orderPay.getOrderNumber()); + record.setProjectType(orderPay.getProjectType()); + record.setPayVendor(orderPay.getPayVendor()); + record.setUserId(orderPay.getUserId()); + record.setPayId(orderPay.getId()); + record.setTransactionId(orderPay.getTransactionId()); + record.setPayAmount(orderPay.getPayAmount()); + record.setRefundAmount(orderPay.getPayAmount()); + record.setRefundOrderStatus(EnumRefundOrderStatus.REFUND_WAIT.getCode()); + record.setRefundReason(refundReason); + record.setCreateDate(now); + record.setUpdateDate(now); + productOrderRefundMapper.insert(record); + + RefundPayAdapterService refundPayAdapterService = payServiceFactory.getRefundPayAdapterService(record.getPayVendor()); + + EnumProductOrderPayVendor payVendorEnum = EnumProductOrderPayVendor.getEnum(record.getPayVendor()); + WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(record.getProjectType(), payVendorEnum.getPlat()); + WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); + + RefundAdapterResult refund = refundPayAdapterService.refund(appinfo, payAccount, record); + if(refund.isSuccess()){ + ProductOrderRefund orderRefundUpd = new ProductOrderRefund(); + orderRefundUpd.setId(record.getId()); + orderRefundUpd.setRefundId(refund.getRefundId()); + orderRefundUpd.setRefundOrderStatus(EnumRefundOrderStatus.REFUND_REQ_SUCCESS.getCode()); + productOrderRefundMapper.updateById(orderRefundUpd); + + ProductOrderPay orderPayUpd = new ProductOrderPay(); + orderPayUpd.setId(orderPay.getId()); + orderPayUpd.setPayOrderStatus(EnumPayOrderStatus.ORDER_STATUS_PENDING_REFUND.getCode()); + productOrderPayMapper.orderPayUpdStatus(orderPayUpd); + } + + } + +} diff --git a/suimangService/src/main/java/com/iformall/service/impl/ProductOrderServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderServiceImpl.java index f21acf5..416ee7a 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/ProductOrderServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/ProductOrderServiceImpl.java @@ -10,11 +10,9 @@ import com.iformall.enums.*; import com.iformall.exception.MallinkException; import com.iformall.mapper.ProductMapper; import com.iformall.mapper.ProductOrderMapper; +import com.iformall.mapper.ProductOrderPayMapper; import com.iformall.mapper.ProductOrderSharingMapper; -import com.iformall.service.ProductOrderService; -import com.iformall.service.UserBasicPropertyService; -import com.iformall.service.WxAppinfoService; -import com.iformall.service.WxPayAccountService; +import com.iformall.service.*; import com.iformall.service.pay.PayServiceFactory; import com.iformall.service.pay.service.pay.PayAdapterService; import com.iformall.service.pay.service.pay.entity.PayAdapterResult; @@ -43,6 +41,9 @@ public class ProductOrderServiceImpl implements ProductOrderService { @Autowired ProductOrderMapper productOrderMapper; + @Autowired + ProductOrderPayMapper productOrderPayMapper; + @Autowired ProductOrderSharingMapper productOrderSharingMapper; @@ -61,6 +62,9 @@ public class ProductOrderServiceImpl implements ProductOrderService { @Autowired PayServiceFactory payServiceFactory; + @Autowired + ProductOrderPayService productOrderPayService; + @Autowired RedisLock redisLock; @@ -90,137 +94,6 @@ public class ProductOrderServiceImpl implements ProductOrderService { return productOrderMapper.selectById(id); } - @Override - public ResultData createPay(ProductOrder productOrder) { - - if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ - return new ResultData(ErrorCode.ORDER_IS_FAIL.getCode(),"订单已取消或已支付"); - } - - PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(productOrder.getPayVendor()); - if(payAdapterService == null){ - return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"该订单不支持当前支付"); - } - EnumProductOrderPayVendor payVendoEnum = EnumProductOrderPayVendor.getEnum(productOrder.getPayVendor()); - - WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(productOrder.getProjectType(), payVendoEnum.getPlat()); - if(appinfo == null){ - return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付应用"); - } - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - if(payAccount == null){ - return new ResultData(ErrorCode.ORDER_IS_NOT_PAY.getCode(),"未找到支付密钥"); - } - - ResultData resultData = handleProductOrderByQuery(appinfo,payAccount,productOrder,payAdapterService); - if(ResultData.SUCCESS != resultData.code){ - return resultData; - } - if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ - return new ResultData(ErrorCode.ORDER_IS_FAIL.getCode(),"订单已取消或已支付"); - } - try { - PayAdapterResult payResult = payAdapterService.createPay(productOrder, appinfo, payAccount); - if(payResult.isSuccess()){ - ProductOrder updOrder = new ProductOrder(); - updOrder.setId(productOrder.getId()); - updOrder.setPayVendor(productOrder.getPayVendor()); - updOrder.setOrderId(payResult.getTransactionId()); - updOrder.setUpdateDate(new Date()); - productOrderMapper.updateById(updOrder); - return new ResultData(payResult.getData()); - }else{ - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(), payResult.getMsg(), payResult.getData()); - } - } catch (Exception e) { - e.printStackTrace(); - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"支付订单异常"); - } - } - - @Override - public ResultData handleProductOrderByQuery(WxAppinfo appinfo,WxPayAccount payAccount,ProductOrder productOrder,PayAdapterService payAdapterService) { - - try { - PayQueryAdapterResult result = payAdapterService.queryPayStatus(productOrder, appinfo, payAccount); - Integer productOrderStatus = result.getCode(); - if(productOrderStatus == null){ - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"查询支付单异常"); - } - - if(EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode().equals(productOrderStatus)){ - ProductOrderServiceImpl proxy = (ProductOrderServiceImpl) AopContext.currentProxy(); - proxy.handleProductOrderSuccess(productOrder,result); - }else if(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode().equals(productOrderStatus) - || EnumProductOrderStatus.ORDER_STATUS_REFUND_SUCCESS.getCode().equals(productOrderStatus)){ - - productOrder.setOpenId(result.getOpenId()); - productOrder.setTransactionId(result.getTransactionId()); - productOrder.setPaymentTime(result.getPayTime()); - productOrder.setPayWay(result.getWay()); - productOrder.setOrderStatus(productOrderStatus); -// productOrder.setIsOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - productOrder.setUpdateDate(new Date()); - int num = productOrderMapper.orderPayUpdStatus(productOrder); - - }else if(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrderStatus)){ - - }else{ - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(),"支付单状态异常"); - } - } catch (Exception e) { - e.printStackTrace(); - return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(),e.getMessage()); - } - return new ResultData(); - } - - @Override - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public void handleProductOrderSuccess(ProductOrder productOrder, PayQueryAdapterResult result) { - String lockKey = "productOrder:success:"+productOrder.getId(); - long time = System.currentTimeMillis() + 5000; - String timeStr = String.valueOf(time); - try{ -// while (!redisLock.lock2(lockKey, timeStr)){ -// Thread.sleep(1000); -// } - if(!redisLock.lock2(lockKey, timeStr)){ - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"请稍后重试"); - } - ProductOrder order = this.getById(productOrder.getId()); - - if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(order.getOrderStatus())){ - return; - } - Date now = new Date(); - productOrder.setOpenId(result.getOpenId()); - productOrder.setTransactionId(result.getTransactionId()); - productOrder.setPaymentTime(result.getPayTime()); - productOrder.setPayWay(result.getWay()); - productOrder.setOrderStatus(result.getCode()); - productOrder.setUpdateDate(now); - productOrder.setIsOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - int num = productOrderMapper.orderPayUpdStatus(productOrder); - - if(num == 0){ - return; - }else if(num > 1){ - throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR); - } - Product product = productMapper.selectById(order.getProductId()); - if(EnumProductType.product_1.getCode().equals(product.getType())){ - userBasicPropertyService.updUserGlod(order.getUserId(),product.getProjectType(),EnumPropertyLogType.RECHARGE.getCode(), - order.getId(),product.getGlod(),now); - } - }catch(Exception e){ - throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR); - }finally { - redisLock.unlock(lockKey, timeStr); - } - - } - @Override public List findList(ProductOrder record) { return productOrderMapper.findList(record); @@ -262,6 +135,7 @@ public class ProductOrderServiceImpl implements ProductOrderService { } @Override + @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) public void handldTimeOut(Long id) { ProductOrder productOrder = productOrderMapper.selectById(id); if(productOrder == null){ @@ -270,28 +144,46 @@ public class ProductOrderServiceImpl implements ProductOrderService { if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ return; } - - if(productOrder.getPayVendor() != null){ - PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(productOrder.getPayVendor()); - EnumProductOrderPayVendor payVendoEnum = EnumProductOrderPayVendor.getEnum(productOrder.getPayVendor()); - - WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(productOrder.getProjectType(), payVendoEnum.getPlat()); - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - ResultData resultData = handleProductOrderByQuery(appinfo,payAccount,productOrder,payAdapterService); - if(ResultData.SUCCESS != resultData.code){ - return; + ProductOrderPay orderPayQ = new ProductOrderPay(); + orderPayQ.setOrderId(productOrder.getId()); + List payList = productOrderPayMapper.findList(orderPayQ); + + if(payList != null && !payList.isEmpty()){ + for (ProductOrderPay orderPay:payList) { + PayAdapterService payAdapterService = payServiceFactory.getPayAdapterService(orderPay.getPayVendor()); + EnumProductOrderPayVendor payVendoEnum = EnumProductOrderPayVendor.getEnum(orderPay.getPayVendor()); + WxAppinfo appinfo = wxAppinfoService.getProjectCAppInfoFromRedis(orderPay.getProjectType(), payVendoEnum.getPlat()); + WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); + ResultData resultData = productOrderPayService.handleProductOrderByQuery(appinfo,payAccount,orderPay,payAdapterService); + if(ResultData.SUCCESS != resultData.code){ + return; + } } } + productOrder = productOrderMapper.selectById(id); + if(!EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode().equals(productOrder.getOrderStatus())){ return; } Date hourDateBefore = DateUtils.getHourDateBefore(1, new Date()); if(productOrder.getCreateDate().before(hourDateBefore)){ - productOrder.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); - productOrder.setIsOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - productOrder.setUpdateDate(new Date()); - int num = productOrderMapper.orderPayUpdStatus(productOrder); + ProductOrder orderUpd = new ProductOrder(); + orderUpd.setId(id); + orderUpd.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); + orderUpd.setIsOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + orderUpd.setUpdateDate(new Date()); + int num = productOrderMapper.orderPayUpdStatus(orderUpd); + + if(num == 1){ + productOrderPayMapper.updStatusByOrder(id,EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); + } } } + @Override + public Integer findPaidCount(ProductOrder record) { + record.setOrderStatus(EnumProductOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode()); + return productOrderMapper.findCount(record); + } + } diff --git a/suimangService/src/main/java/com/iformall/service/impl/ProductServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/ProductServiceImpl.java index 129fc0e..c913f4b 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/ProductServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/ProductServiceImpl.java @@ -3,15 +3,17 @@ package com.iformall.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.iformall.domain.po.Product; +import com.iformall.enums.EnumProductType; import com.iformall.mapper.ProductMapper; import com.iformall.service.ProductService; +import com.iformall.service.project.ProjectFactory; + import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; - -import java.util.Date; +import java.util.List; @Service @Slf4j @@ -20,16 +22,28 @@ public class ProductServiceImpl implements ProductService { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired - ProductMapper productFromMapper; + ProductMapper productMapper; + + @Autowired + ProjectFactory payProductFactory; @Override public PageInfo listAsPage(Product record, Integer pageIndex, Integer pageSize) { - return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> productFromMapper.findList(record)); + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> productMapper.findList(record)); } @Override public Product getById(Long id) { - return productFromMapper.selectById(id); + return productMapper.selectById(id); + } + + @Override + public List findListDetail(Product record, Integer projectType) { + List list = productMapper.findList(record); + for (Product prod: list) { + prod.setExtraInfo(payProductFactory.getProjectService(prod.getProjectType()).getPayProductExtroInfo(prod)); + } + return list; } } diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxAppinfoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxAppinfoServiceImpl.java index bfd6a0e..9c93d9a 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxAppinfoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxAppinfoServiceImpl.java @@ -15,6 +15,7 @@ import com.iformall.service.WxMallService; import com.iformall.utils.Constant; import com.iformall.utils.RedisCacheUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -93,30 +94,6 @@ public class WxAppinfoServiceImpl implements WxAppinfoService { } return null; } - - @Override - public WxAppinfo getOnlyByAppId(String appId) { - WxAppinfo appinfoQ = new WxAppinfo(); - appinfoQ.setAppId(appId); - List list = wxAppinfoMapper.findList(appinfoQ); - if(list.size() == 1){ - return list.get(0); - }else if(list.size() > 0){ - for (WxAppinfo appinfo:list) { - TenantEntity tenantEntity = new TenantEntity(); - tenantEntity.setTenantId(appinfo.getTenantId()); - if(wxMallService.isgroupSupport(tenantEntity)){ - return appinfo; - } - } - } - return null; - } - - @Override - public WxAppinfo getByAppId(String appId, String tenantId) { - return wxAppinfoMapper.findByAppId(appId,tenantId); - } @Override public void wxAppinfoInit(String tenantId, Long payId, Long payBillId, WxProjectConfig wxProjectConfig) { @@ -174,48 +151,6 @@ public class WxAppinfoServiceImpl implements WxAppinfoService { wxAppinfoMapper.deleteById(id); } - @Override - public WxAppinfo getOnlyByAppIdFromRedis(String appId) { - WxAppinfo record = null; - String key = Constant.appinfoPrev + "only" + ":" + appId; - record = RedisCacheUtils.getCacheObject(wxAppinfoRedisTemplate, key, WxAppinfo.class); - if (null == record) { - record = this.getOnlyByAppId(appId); - if(record != null){ - RedisCacheUtils.cache(wxAppinfoRedisTemplate, key, record, 3600*24*7); - } - } - return record; - } - - @Override - public WxAppinfo getByAppIdFromRedis(String appId,String tenantId) { - WxAppinfo record = null; - String key = Constant.appinfoPrev + tenantId + ":" + appId; - record = RedisCacheUtils.getCacheObject(wxAppinfoRedisTemplate, key, WxAppinfo.class); - if (null == record) { - record = this.getByAppId(appId,tenantId); - if(record != null){ - RedisCacheUtils.cache(wxAppinfoRedisTemplate, key, record, 3600*24*7); - } - } - return record; - } - - @Override - public WxAppinfo getByIdFromRedis(Long id) { - WxAppinfo record = null; - String key = Constant.appinfoPrev + id; - record = RedisCacheUtils.getCacheObject(wxAppinfoRedisTemplate, key, WxAppinfo.class); - if (null == record) { - record = this.getById(id); - if(record != null){ - RedisCacheUtils.cache(wxAppinfoRedisTemplate, key, record, 3600*24*7); - } - } - return record; - } - @Override public WxAppinfo getCAppInfoFromRedis(String tenantId, EnumAppPlat plat) { WxAppinfo record = null; @@ -267,19 +202,48 @@ public class WxAppinfoServiceImpl implements WxAppinfoService { return record; } + @Override + public WxAppinfo getProjectCAppInfo(String appId, Integer projectType) { + if(StringUtils.isBlank(appId) || projectType == null){ + return null; + } + WxAppinfo appinfoQ = new WxAppinfo(); + appinfoQ.setProjectType(projectType); + appinfoQ.setAppId(appId); + appinfoQ.setType(EnumAppType.C.getCode()); + WxAppinfo appInfo = wxAppinfoMapper.selectOne(new QueryWrapper<>(appinfoQ)); + return appInfo; + } + + @Override + public WxAppinfo getProjectCAppInfoFromRedis(String appId, Integer projectType) { + if(StringUtils.isBlank(appId) || projectType == null){ + return null; + } + WxAppinfo record = null; + String key = Constant.appinfoPrev + appId + "-" + projectType + + "-" + EnumAppType.C.getCode(); + record = RedisCacheUtils.getCacheObject(wxAppinfoRedisTemplate, key, WxAppinfo.class); + if (null == record) { + record = this.getProjectCAppInfo(appId, projectType); + if(record != null){ + RedisCacheUtils.cache(wxAppinfoRedisTemplate, key, record, 3600*24*7); + } + } + return record; + } + private void deleteRedis(Long id){ WxAppinfo record = this.getById(id); if(record != null){ - String key1 = Constant.appinfoPrev + record.getAppId(); + String key1 = Constant.appinfoPrev + record.getId(); RedisCacheUtils.removeCache(wxAppinfoRedisTemplate, key1); - String key2 = Constant.appinfoPrev + record.getId(); + String key2 = Constant.appinfoPrev + record.getProjectType() + "-" + record.getPlat() + + "-" + EnumAppType.C.getCode(); RedisCacheUtils.removeCache(wxAppinfoRedisTemplate, key2); - String key3 = Constant.appinfoPrev + record.getTenantId() - + "-" + EnumAppPlat.getByCode(record.getPlat()) + "-" + record.getType(); + String key3 = Constant.appinfoPrev + record.getAppId() + "-" + record.getProjectType() + + "-" + EnumAppType.C.getCode(); RedisCacheUtils.removeCache(wxAppinfoRedisTemplate, key3); - String key4 = Constant.appinfoPrev + record.getTenantId() - + "-" + null + "-" + record.getType(); - RedisCacheUtils.removeCache(wxAppinfoRedisTemplate, key4); } } diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxCUserAuthorityServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxCUserAuthorityServiceImpl.java index 868a141..2094de3 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxCUserAuthorityServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxCUserAuthorityServiceImpl.java @@ -19,8 +19,8 @@ public class WxCUserAuthorityServiceImpl implements WxCUserAuthorityService { @Override public Map getAuthor(Long id, String code, Integer type, Long resourceId) { + List resultList = new ArrayList(); - HashMap authorVos = new HashMap<>(); if (type == 0) { //查询数字人相关权限 @@ -31,41 +31,9 @@ public class WxCUserAuthorityServiceImpl implements WxCUserAuthorityService { resultList = wxCUserAuthorityMapper.getAuthorVoice(id, 1, resourceId); } - if (resourceId == null || resourceId == -1) { - //若资源id没有传入那就展示所有当前类型资源权限 - HashMap info = new HashMap<>(); - HashMap status = new HashMap<>(); - List authorList = new ArrayList(); - for (WxCUserAuthority wxCUserAuthority : resultList) { - HashMap data = new HashMap<>(); - data.put("username", wxCUserAuthority.getUserName()); - data.put("type", wxCUserAuthority.getType()); - data.put("resource_id", wxCUserAuthority.getResourceId()); - data.put("class", wxCUserAuthority.getClassType()); - data.put("current_time", new Date(System.currentTimeMillis() / 1000)); - data.put("expire_time", wxCUserAuthority.getExpireTime().getTime() / 1000); - authorList.add(data); - } - authorVos.put("authorList", authorList); - info.put("log_id", id); - info.put("server_type", "author"); - authorVos.put("info", info); - status.put("code", 1000); - status.put("msg", "success"); - authorVos.put("status", status); - return authorVos; - } - HashMap data = new HashMap<>(); - HashMap info = new HashMap<>(); - HashMap status = new HashMap<>(); - if (resultList.size() == 0) { - status.put("code", 5001); - status.put("msg", "没有该资源的权限"); - authorVos.put("status", status); - return authorVos; - } - for (WxCUserAuthority wxCUserAuthority : resultList) { - data.put("username", wxCUserAuthority.getUserName()); + if (resultList.size() == 1) { + HashMap data = new HashMap<>(); + WxCUserAuthority wxCUserAuthority = resultList.get(0); data.put("type", wxCUserAuthority.getType()); data.put("resource_id", wxCUserAuthority.getResourceId()); @@ -75,14 +43,8 @@ public class WxCUserAuthorityServiceImpl implements WxCUserAuthorityService { data.put("class", EnumClassType.SHARE.getCode()); data.put("current_time", new Date(System.currentTimeMillis() / 1000)); data.put("expire_time", wxCUserAuthority.getExpireTime().getTime() / 1000); + return data; } - authorVos.put("data", data); - info.put("log_id", id); - info.put("server_type", "author"); - authorVos.put("info", info); - status.put("code", 1000); - status.put("msg", "success"); - authorVos.put("status", status); - return authorVos; + return null; } } diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxCUserBasicInfoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxCUserBasicInfoServiceImpl.java index 1b75922..146d642 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxCUserBasicInfoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxCUserBasicInfoServiceImpl.java @@ -629,8 +629,7 @@ public class WxCUserBasicInfoServiceImpl implements WxCUserBasicInfoService,IExc @Override public PageInfo listAsPage(WxCUserBasicInfo record, Integer pageIndex, Integer pageSize) { - return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo( - () -> wxCUserBasicInfoMapper.findList(record)); + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> wxCUserBasicInfoMapper.findList(record)); } @Override @@ -1540,5 +1539,27 @@ public class WxCUserBasicInfoServiceImpl implements WxCUserBasicInfoService,IExc } return null; } + + @Override + public void reducePoints(Long id,String finalTenantId, Integer reducePoints) { + wxCUserBasicInfoMapper.reducePoints(id, finalTenantId, reducePoints); + } + + @Override + public void addPoints(Long id, String finalTenantId, Integer addPoints) { + wxCUserBasicInfoMapper.addPoints(id, finalTenantId, addPoints); + } + + @Override + public List findIdsListByPhone(String finalTenantId, String phone) { + WxCUserBasicInfo user = new WxCUserBasicInfo(); + user.setPhone(phone); + return wxCUserBasicInfoMapper.findIdList(user); + } + + @Override + public List findList(WxCUserBasicInfo basicInfo) { + return wxCUserBasicInfoMapper.findList(basicInfo); + } } diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxCVideoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxCVideoServiceImpl.java index fc7b6e9..50e0384 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxCVideoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxCVideoServiceImpl.java @@ -39,13 +39,12 @@ public class WxCVideoServiceImpl implements WxCVideoService, IExcelExportServer WxCVideoMapper wxCVideoMapper; @Override - public Map getById(Long id) { - List TemplateVideo = wxCVideoMapper.getById(id); - Map avatarVos = new HashMap(); + public Map getById(Long userId) { Map data = new HashMap(); + + List TemplateVideo = wxCVideoMapper.getById(userId); List authorlist = new ArrayList(); for (WxCVideoTable wxCVideoTable : TemplateVideo) { - data.put("username", wxCVideoTable.getUserName()); data.put("current_time", new Date(System.currentTimeMillis() / 1000)); Map avatar = new HashMap(); @@ -54,40 +53,35 @@ public class WxCVideoServiceImpl implements WxCVideoService, IExcelExportServer avatar.put("avatar_image", wxCVideoTable.getImage()); avatar.put("avatar_demo", wxCVideoTable.getDemo()); avatar.put("avatar_model", wxCVideoTable.getModel()); - //模板文件和预处理信息存放问题 - try { - File modelFile = new File(wxCVideoTable.getModelPath()); - avatar.put("avatar_model_md5", getFileMD5(modelFile)); - } catch (Exception e) { - e.printStackTrace(); - avatar.put("avatar_model_md5", wxCVideoTable.getModelMd5()); - } + avatar.put("avatar_model_md5", wxCVideoTable.getModelMd5()); + avatar.put("avatar_preinfo_md5", wxCVideoTable.getPreInfoMd5()); + //模板文件和预处理信息存放问题 +// try { +// File modelFile = new File(wxCVideoTable.getModelPath()); +// avatar.put("avatar_model_md5", getFileMD5(modelFile)); +// } catch (Exception e) { +// e.printStackTrace(); +// avatar.put("avatar_model_md5", wxCVideoTable.getModelMd5()); +// } +// +// try { +// File preinfoFile = new File(wxCVideoTable.getPreInfoPath()); +// avatar.put("avatar_preinfo_md5", getFileMD5(preinfoFile)); +// } catch (Exception e) { +// e.printStackTrace(); +// avatar.put("avatar_preinfo_md5", wxCVideoTable.getPreInfoMd5()); +// } - try { - File preinfoFile = new File(wxCVideoTable.getPreInfoPath()); - avatar.put("avatar_preinfo_md5", getFileMD5(preinfoFile)); - } catch (Exception e) { - e.printStackTrace(); - avatar.put("avatar_preinfo_md5", wxCVideoTable.getPreInfoMd5()); - } avatar.put("avatar_preinfo", wxCVideoTable.getPreInfo()); + avatar.put("mask", wxCVideoTable.getMask()); avatar.put("expire_time", wxCVideoTable.getExpireTime().getTime() / 1000); avatar.put("class", wxCVideoTable.getClassType()); authorlist.add(avatar); - data.put("authorlist", authorlist); } - avatarVos.put("data", data); - Map info = new HashMap(); - Map status = new HashMap(); - info.put("log_id", id); - info.put("server_type", "avatar list"); - status.put("code", 1000); - status.put("msg", "success"); - avatarVos.put("info", info); - avatarVos.put("status", status); - - return avatarVos; + data.put("authorlist", authorlist); + + return data; } @Override diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxCVoiceServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxCVoiceServiceImpl.java index c3180a7..75e63e1 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxCVoiceServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxCVoiceServiceImpl.java @@ -17,9 +17,12 @@ import com.iformall.mapper.WxCVoiceMapper; import com.iformall.service.WxCVoiceService; import com.iformall.sm.AiPreviewParam; import com.iformall.sm.AiPreviewResult; +import com.iformall.sm.AiTtsHelper; import com.iformall.sm.AiVideoHelper; import com.iformall.utils.Constant; import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.ObjectUtils; @@ -28,6 +31,7 @@ import java.util.*; @Service public class WxCVoiceServiceImpl implements WxCVoiceService { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired WxCVoiceMapper wxCVoiceMapper; @@ -43,11 +47,10 @@ public class WxCVoiceServiceImpl implements WxCVoiceService { @Override - public Map getById(Long id,String phone) { - List resultList = wxCVoiceMapper.getById(id); - HashMap result = new HashMap<>(); + public Map getById(Long userId) { HashMap data = new HashMap<>(); - data.put("username", phone); + + List resultList = wxCVoiceMapper.getById(userId); data.put("current_time", new Date(System.currentTimeMillis() / 1000)); // List audioList = new ArrayList(); Map> audioList = new HashMap(); @@ -57,6 +60,7 @@ public class WxCVoiceServiceImpl implements WxCVoiceService { audio = new HashMap<>(); audio.put("LocaleName", wxCVoiceTable.getLocalelName()); audio.put("displayname", wxCVoiceTable.getLocalDisPlayName()); + audio.put("TrialText", wxCVoiceTable.getTrialText()); audioList.put(wxCVoiceTable.getLanguageId(),audio); } List> voiceList = (List>) audio.get("voiceList"); @@ -102,44 +106,10 @@ public class WxCVoiceServiceImpl implements WxCVoiceService { } data.put("audioList", new ArrayList<>(audioList.values())); - - result.put("data", data); - HashMap info = new HashMap<>(); - HashMap status = new HashMap<>(); - info.put("log_id", id); - info.put("server_type", "audio list"); - result.put("info", info); - status.put("code", 1000); - status.put("msg", "success"); - result.put("status", status); - return result; - } - @Override - public Map voicePreview(AiPreviewParam aiPreviewParam) { - VoiceInfo voiceInfo = voiceMapper.selectOne(new LambdaQueryWrapper().eq(VoiceInfo::getIsDel, 0).eq(VoiceInfo::getId, aiPreviewParam.getVoice_id())); - if (ObjectUtils.isEmpty(voiceInfo)) { - Map status = new HashMap<>(); - status.put("code", ErrorCode.SYS_SERVER_ERROR.getCode()); - status.put("msg", "声音信息不存在"); - return status; - } - AiPreviewParam param = new AiPreviewParam(); - param.setGen_txt(aiPreviewParam.getGen_txt().replaceAll(Constant.text_pause, "[*]")); - param.setVoice_id(voiceInfo.getMouldSmId()); - param.setVoice_style(StringUtils.isBlank(aiPreviewParam.getVoice_style()) ? EnumSpeakType.default_0.getMessage() : aiPreviewParam.getVoice_style()); - param.setGender(voiceInfo.getSex() == 1 ? "male" : "female"); - AiPreviewResult result = AiVideoHelper.voicePreview(param); - Map resultMap = new HashMap<>(); - Map data = new HashMap<>(); - data.put("ttsurl", result.getUrl()); - Map status = new HashMap<>(); - status.put("code", 1000); - status.put("msg", "success"); - resultMap.put("data", data); - resultMap.put("status", status); - return resultMap; + return data; } + @Override public List chooseType(Long id) { List voiceInfos = voiceMapper.selectList( @@ -173,4 +143,27 @@ public class WxCVoiceServiceImpl implements WxCVoiceService { }); return voiceInfos; } + + @Override + public Map voicePreview(Long voiceId, String voiceStyle, String text, Integer speed) { + VoiceInfo voiceInfo = voiceMapper.selectById(voiceId); + if(voiceInfo == null){ + logger.error("未查询到声音{}"+voiceId); + return null; + } + + AiPreviewParam param = new AiPreviewParam(); + param.setVoice_id(voiceInfo.getMouldSmId()); + param.setVoice_style(StringUtils.isBlank(voiceStyle) ? EnumSpeakType.default_0.getMessage() : voiceStyle); + param.setGen_txt(text.replaceAll(Constant.text_pause, "[*]")); + param.setSpeed(speed==null?100:speed); + AiPreviewResult aiTtsResult = AiTtsHelper.voicePreview(param); + if(!aiTtsResult.isSuccess()){ + logger.error("tts 预览失败{}"+aiTtsResult.getMsg()); + return null; + } + Map data = new HashMap<>(); + data.put("ttsurl", aiTtsResult.getUrl()); + return data; + } } diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxMallServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxMallServiceImpl.java index f9500b1..5acbdb1 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxMallServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxMallServiceImpl.java @@ -326,10 +326,10 @@ public class WxMallServiceImpl implements WxMallService { userInfo.setPassword(wxMall.getAdminPassword()); if(userInfo.getId() == null){ - if(userInfoService.cntByUserName(userInfo.getUsername()) > 0){ + if(userInfoService.cntByUserName(userInfo.getUsername(),0) > 0){ return new ResultData(ErrorCode.USER_NAME_IS_FOUND.getCode(),"用户名已存在"); } - if(userInfoService.cntByUserPhone(userInfo.getPhone()) > 0){ + if(userInfoService.cntByUserPhone(userInfo.getPhone(),0) > 0){ return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); } if(StringUtils.isBlank(userInfo.getPassword())){ @@ -356,7 +356,7 @@ public class WxMallServiceImpl implements WxMallService { // } // } if (!oldUser.getPhone().equals(userInfo.getPhone())) { - if(userInfoService.cntByUserPhone(userInfo.getPhone()) > 0){ + if(userInfoService.cntByUserPhone(userInfo.getPhone(),0) > 0){ return new ResultData(ErrorCode.USER_PHONE_IS_FOUND.getCode(),"手机号已存在"); } bChangedPhone = true; diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxMsgValidationcodeServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxMsgValidationcodeServiceImpl.java index 20b1a27..09648dd 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxMsgValidationcodeServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxMsgValidationcodeServiceImpl.java @@ -97,9 +97,9 @@ public class WxMsgValidationcodeServiceImpl implements WxMsgValidationcodeServic @Override - public ResultData sendvalidationcode(WxMsgValidationcode wxMsgValidationcode) { + public ResultData sendvalidationcode(WxMsgValidationcode wxMsgValidationcode,int projectType) { //1、查看是否存在未过期的短信,有返回成功 没有继续 - String key = Constant.codePrev + ":" + wxMsgValidationcode.getPhone(); + String key = Constant.codePrev + ":"+projectType+":" + wxMsgValidationcode.getPhone(); Long expire = RedisCacheUtils.getExpire(redisTemplate, key); if(expire != null && expire > 60*4l){ return new ResultData(ErrorCode.MSG_REPEAT_SEND); @@ -108,6 +108,7 @@ public class WxMsgValidationcodeServiceImpl implements WxMsgValidationcodeServic //2 判断是否已超过10条 String systemTime = DateUtils.getSystemTime("yyyy-MM-dd"); wxMsgValidationcode.setCreatetimeStr(systemTime); + wxMsgValidationcode.setProjectType(projectType); Integer count = wxMsgValidationcodeMapper.findListCount(wxMsgValidationcode); if (count != null && count.intValue() > 20) { return new ResultData(ErrorCode.MSG_SEND_ERROR.getCode(), "验证码发送超限"); @@ -129,8 +130,8 @@ public class WxMsgValidationcodeServiceImpl implements WxMsgValidationcodeServic } @Override - public boolean checkCodeValid(String phone, String code) { - String key = Constant.codePrev + ":" + phone; + public boolean checkCodeValid(String phone, String code,int projectType) { + String key = Constant.codePrev + ":"+ projectType +":" + phone; String cacheCode = RedisCacheUtils.getCacheString(redisTemplate, key); if(cacheCode == null || !cacheCode.equals(code)){ return false; diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxPayBillServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxPayBillServiceImpl.java deleted file mode 100644 index 7df0c20..0000000 --- a/suimangService/src/main/java/com/iformall/service/impl/WxPayBillServiceImpl.java +++ /dev/null @@ -1,882 +0,0 @@ -package com.iformall.service.impl; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.common.Result; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxAppinfo; -import com.iformall.domain.po.WxBillSettle; -import com.iformall.domain.po.WxMerchant; -import com.iformall.domain.po.WxMerchantBUser; -import com.iformall.domain.po.WxPayAccount; -import com.iformall.domain.po.WxPayAccountBill; -import com.iformall.domain.po.WxPayBill; -import com.iformall.domain.vo.WxBillAll; -import com.iformall.enums.*; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.*; -import com.iformall.pay.*; -import com.iformall.service.*; -import com.iformall.utils.*; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Propagation; -import org.springframework.transaction.annotation.Transactional; - -import java.text.ParseException; -import java.util.*; - -/** - * @author gongbiao - */ -@Service -public class WxPayBillServiceImpl implements WxPayBillService { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - WxAppinfoService wxAppinfoService; - - @Autowired - WxPayAccountBillMapper wxPayAccountBillMapper; - - @Autowired - WxPayAccountService wxPayAccountService; - - @Autowired - WxPayBillMapper wxPayBillMapper; - - @Autowired - WxBillAllMapper wxBillAllMapper; - - @Lazy - @Autowired - WxBillAllService wxBillAllService; - - @Autowired - WxMerchantBUserMapper wxMerchantBUserMapper; - - @Lazy - @Autowired - private WxBillSettleService wxBillSettleService; - - @Lazy - @Autowired - WxMerchantBUserService wxMerchantBUserService; - - @Lazy - @Autowired - WxMerchantService wxMerchantService; - - JSONObject errorMap = JSON.parseObject("{" + - "\"NOAUTH\":{\"detail\":\"商户无此接口权限\",\"reason\":\"商户未开通此接口权限\",\"resolution\":\"请商户前往申请此接口权限\"}," + - "\"NOTENOUGH\":{\"detail\":\"余额不足\",\"reason\":\"用户帐号余额不足\",\"resolution\":\"用户帐号余额不足,请用户充值或更换支付卡后再支付\"}," + - "\"ORDERPAID\":{\"detail\":\"商户订单已支付\",\"reason\":\"商户订单已支付,无需重复操作\",\"resolution\":\"商户订单已支付,无需更多操作\"}," + - "\"ORDERCLOSED\":{\"detail\":\"订单已关闭\",\"reason\":\"当前订单已关闭,无法支付\",\"resolution\":\"当前订单已关闭,请重新下单\"}," + - "\"SYSTEMERROR\":{\"detail\":\"系统错误\t\",\"reason\":\"系统超时\",\"resolution\":\"系统异常,请用相同参数重新调用\"}," + - "\"APPID_NOT_EXIST\":{\"detail\":\"APPID不存在\",\"reason\":\"参数中缺少APPID\",\"resolution\":\"请检查APPID是否正确\"}," + - "\"MCHID_NOT_EXIST\":{\"detail\":\"MCHID不存在\",\"reason\":\"参数中缺少MCHID\",\"resolution\":\"请检查MCHID是否正确\"}," + - "\"APPID_MCHID_NOT_MATCH\":{\"detail\":\"appid和mch_id不匹配\",\"reason\":\"appid和mch_id不匹配\",\"resolution\":\"请确认appid和mch_id是否匹配\"}," + - "\"LACK_PARAMS\":{\"detail\":\"缺少参数\t\",\"reason\":\"缺少必要的请求参数\",\"resolution\":\"请检查参数是否齐全\"}," + - "\"OUT_TRADE_NO_USED\":{\"detail\":\"商户订单号重复\",\"reason\":\"同一笔交易不能多次提交\",\"resolution\":\"请核实商户订单号是否重复提交\"}," + - "\"SIGNERROR\":{\"detail\":\"签名错误\",\"reason\":\"参数签名结果不正确\",\"resolution\":\"请检查签名参数和方法是否都符合签名算法要求\"}," + - "\"XML_FORMAT_ERROR\":{\"detail\":\"XML格式错误\t\",\"reason\":\"XML格式错误\",\"resolution\":\"请检查XML参数格式是否正确\"}," + - "\"REQUIRE_POST_METHOD\":{\"detail\":\"请使用post方法\",\"reason\":\"未使用post传递参数\",\"resolution\":\"请检查请求参数是否通过post方法提交\"}," + - "\"POST_DATA_EMPTY\":{\"detail\":\"post数据为空\",\"reason\":\"post数据不能为空\",\"resolution\":\"请检查post数据是否为空\"}," + - "\"NOT_UTF8\":{\"detail\":\"编码格式错误\",\"reason\":\"未使用指定编码格式\",\"resolution\":\"请使用UTF-8编码格式\"}}"); - - JSONObject errorMapQuery = JSON.parseObject("{" + - "\"ORDERNOTEXIST\":{\"detail\":\"此交易订单号不存在\",\"reason\":\"查询系统中不存在此交易订单号\",\"resolution\":\"该API只能查提交支付交易返回成功的订单,请商户检查需要查询的订单号是否正确\"},\n" + - "\"SYSTEMERROR\":{\"detail\":\"系统错误\t\",\"reason\":\"后台系统返回错误\",\"resolution\":\"系统异常,请再调用发起查询\"}}"); - - JSONObject errorMapClose = JSON.parseObject("{" + - "\"ORDERPAID\":{\"detail\":\"订单已支付\",\"reason\":\"订单已支付,不能发起关单\",\"resolution\":\"订单已支付,不能发起关单,请当作已支付的正常交易\"}," + - "\"SYSTEMERROR\":{\"detail\":\"系统错误\",\"reason\":\"系统错误\",\"resolution\":\"系统异常,请重新调用该API\"}," + - "\"ORDERCLOSED\":{\"detail\":\"订单已关闭\",\"reason\":\"订单已关闭,无法重复关闭\",\"resolution\":\"订单已关闭,无需继续调用\"}," + - "\"SIGNERROR\":{\"detail\":\"签名错误\",\"reason\":\"参数签名结果不正确\",\"resolution\":\"请检查签名参数和方法是否都符合签名算法要求\"}," + - "\"REQUIRE_POST_METHOD\":{\"detail\":\"请使用post方法\",\"reason\":\"未使用post传递参数\",\"resolution\":\"请检查请求参数是否通过post方法提交\"}," + - "\"XML_FORMAT_ERROR\":{\"detail\":\"XML格式错误\t\",\"reason\":\"XML格式错误\",\"reason\":\"请检查XML参数格式是否正确\"}}"); - - @Override - public ResultData createPayBill(WxMerchant merchant,Integer billTypeValue,WxAppinfo appInfo, WxPayBill record, EnumPayWay payWay) { - final IdWorker idworker = IdWorker.get(); - - EnumPayShare isShare = EnumPayShare.NO; - try { - //查询账单是否存在 - WxBillAll wxBillAll = new WxBillAll(); - wxBillAll.updateTenantInfo(record); - wxBillAll.setId(record.getBillId()); - wxBillAll.setBillTypeValue(billTypeValue); - List> bills = wxBillAllService.listBill(wxBillAll,merchant,true,false,false,false); - if (bills.size()==0) { - logger.error("pay bill, bill not allow, repaymentReq: " + JSONObject.toJSONString(record) + ", payWay: " + payWay.toString()); - throw new MallinkException(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND); - } - //获取账单数据 - Map bill = bills.get(0); - Long owe = (Long) bill.get("owe"); - - if (owe.longValue() <= 0) { - logger.info("账单欠缴为0"); - return new ResultData(ErrorCode.BILL_OWE_ZERO); - } - //获取支付账户信息 - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); - Date currentDate = new Date(); - String payBillNo; - WxPayBill billParam= new WxPayBill(); - billParam.setBillId(record.getBillId()); - List list = wxPayBillMapper.findList(billParam); - //数据库不存在已有订单,新建订单 - if (list.size() <= 0) { - // 创建支付订单 - Long id = idworker.nextId(); - payBillNo = id+DateUtils.getSystemTime("yyMMddHHmmss"); - record.setId(id); - record.updateTenantInfo(record); - record.setbUserId(record.getbUserId()); - record.setCreateTime(currentDate); - record.setUpdateTime(currentDate); - record.setPayTimeStart(currentDate); - long endtime = currentDate.getTime() + 120 * 60 * 1000; - record.setPayTimeEnd(new Date(endtime)); - // 支付单号 - record.setPayBillNo(payBillNo); - record.setPayAmount((Long) bill.get("owe")); - record.setPayVendor(payWay.getCode()); - record.setPayBillStatus(EnumPayStatus.PAY_STATUS_WAIT.getCode()); - record.setShare(isShare.getCode()); - record.setBillTypeValue(billTypeValue); - int sqlRow = wxPayBillMapper.insert(record); - if (sqlRow != 1) { - logger.error("pay bill insert error: " + JSONObject.toJSONString(record)); - throw new MallinkException(ErrorCode.DB_FAIL); - } - logger.info("创建支付订单:"+record.toString()); - } else { - //数据库存在订单信息,更新支付中状态,返回之前的预支付信息 - WxPayBill wxPayBill = list.get(0); - wxPayBill.setShare(isShare.getCode()); - //更新订单状态为支付中 - wxPayBill.setPayBillStatus(EnumPayStatus.PAY_STATUS_WAIT.getCode()); - wxPayBill.setUpdateTime(currentDate); - int sqlRow = wxPayBillMapper.updateById(wxPayBill); - if (sqlRow != 1) { - logger.error("pay bill update error: " + wxPayBill.toString()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - //数据库中openId与再次传来的openId不相同那么关闭此订单再次生成新的订单 - if(!wxPayBill.getOpenId().equals(record.getOpenId())){ - String openId = record.getOpenId(); - //关闭订单 - logger.info("openId不同时关闭之前的订单:"+record.toString()); - ResultData resultData = payBillClose(appInfo, wxPayBill); - if(resultData.code!=Result.SUCCESS){ - return new ResultData(ErrorCode.ORDER_IS_FAIL); - } - record = wxPayBillMapper.selectById(wxPayBill.getId()); - record.setOpenId(openId); - //创建新的订单号 - payBillNo = record.getId()+DateUtils.getSystemTime("yyMMddHHmmss"); - record.setPayTimeStart(currentDate); - long endtime = currentDate.getTime() + 120 * 60 * 1000; - record.setPayTimeEnd(new Date(endtime)); - record.setPayBillNo(payBillNo); - record.setPayAmount((Long) bill.get("owe")); - record.setUpdateTime(currentDate); - sqlRow = wxPayBillMapper.updateById(record); - if (sqlRow != 1) { - logger.error("pay bill update error: " + JSONObject.toJSONString(record)); - throw new MallinkException(ErrorCode.DB_FAIL); - } - logger.info("新的订单数据:"+JSONObject.toJSONString(record)); - }else{ - logger.info("数据库存在订单信息,更新支付中状态,返回之前的预支付信息:"+JSONObject.toJSONString(wxPayBill)); - if (!owe.equals(wxPayBill.getPayAmount())) { - logger.info("欠缴费用与之前不同发起新的订单:" + wxPayBill.toString()); - ResultData resultData = payBillClose(appInfo, wxPayBill); - if (resultData.code != Result.SUCCESS) { - return new ResultData(ErrorCode.ORDER_IS_FAIL); - } - record = wxPayBillMapper.selectById(wxPayBill.getId()); - //创建新的订单号 - payBillNo = record.getId() + DateUtils.getSystemTime("yyMMddHHmmss"); - record.setPayTimeStart(currentDate); - long endtime = currentDate.getTime() + 120 * 60 * 1000; - record.setPayTimeEnd(new Date(endtime)); - record.setPayBillNo(payBillNo); - record.setPayAmount((Long) bill.get("owe")); - record.setUpdateTime(currentDate); - sqlRow = wxPayBillMapper.updateById(record); - if (sqlRow != 1) { - logger.error("pay bill update error: " + JSONObject.toJSONString(record)); - throw new MallinkException(ErrorCode.DB_FAIL); - } - logger.info("新的订单数据:" + JSONObject.toJSONString(record)); - } else if (wxPayBill.getPayTimeEnd().after(new Date())) { - //订单在120分钟之内没有失效,延用之前预支付订单号 - String noncestr = Utility.generate32UUID(); - String timestamp = String.valueOf(Utility.getCurrentTimeStamp()); - Map sighMap = MapUtil.getOrderMap(); - sighMap.put("appId", appInfo.getAppId()); - sighMap.put("timeStamp", timestamp); - sighMap.put("nonceStr", noncestr); - sighMap.put("package", "prepay_id=" + wxPayBill.getPrepayId()); - sighMap.put("signType", "HMAC-SHA256"); - String signAgent = WxPayment.createSignHMAC(sighMap, payAccount.getApiKey()); - Map returnMap=new HashMap<>(); - returnMap.put("timeStamp", timestamp); - returnMap.put("nonceStr", noncestr); - returnMap.put("package", "prepay_id=" + wxPayBill.getPrepayId()); - returnMap.put("paySign", signAgent); - returnMap.put("signType", "HMAC-SHA256"); - logger.info("订单在120分钟之内没有失效,延用之前预支付订单号:"+JSONObject.toJSONString(wxPayBill)); - return new ResultData(Result.SUCCESS, "创建支付订单成功", returnMap); - } else { - //超过时间关闭订单 - logger.info("超过时间关闭订单:" + wxPayBill.toString()); - ResultData resultData = payBillClose(appInfo, wxPayBill); - if(resultData.code!=Result.SUCCESS){ - return new ResultData(ErrorCode.ORDER_IS_FAIL); - } - record = wxPayBillMapper.selectById(wxPayBill.getId()); - //创建新的订单号 - payBillNo = record.getId()+DateUtils.getSystemTime("yyMMddHHmmss"); - record.setPayTimeStart(currentDate); - long endtime = currentDate.getTime() + 120 * 60 * 1000; - record.setPayTimeEnd(new Date(endtime)); - record.setPayBillNo(payBillNo); - record.setPayAmount((Long) bill.get("owe")); - record.setUpdateTime(currentDate); - sqlRow = wxPayBillMapper.updateById(record); - if (sqlRow != 1) { - logger.error("pay bill update error: " + JSONObject.toJSONString(record)); - throw new MallinkException(ErrorCode.DB_FAIL); - } - logger.info("新的订单数据:"+JSONObject.toJSONString(record)); - } - - } - - } - - // 统一下单 // 服务商模式 - String noncestr = Utility.generate32UUID(); - WxPayOrderSP wxPayBillSP = new WxPayOrderSP(); - wxPayBillSP.setSub_openid(record.getOpenId()); - wxPayBillSP.setAppid(appInfo.getParentAppId()); - wxPayBillSP.setMch_id(payAccount.getMchId()); - wxPayBillSP.setSub_appid(appInfo.getAppId()); - wxPayBillSP.setSub_mch_id(payAccount.getSubMchId()); - wxPayBillSP.setNonce_str(noncestr); - wxPayBillSP.setBody(bill.get("billType").toString()); - wxPayBillSP.setOut_trade_no(record.getPayBillNo()); - wxPayBillSP.setTotal_fee(bill.get("owe").toString()); - // 终端IP - wxPayBillSP.setSpbill_create_ip(record.getIp()); - wxPayBillSP.setNotify_url(payAccount.getPayNotifyUrl()); - // 终端类型 - wxPayBillSP.setTrade_type(WxPay.TradeType.JSAPI.name()); - // 订单ID - wxPayBillSP.setProduct_id(String.valueOf(bill.get("id").toString())); - wxPayBillSP.setTime_start(Utility.getDataFormatStringYYYYMMDDHHmmss(currentDate)); - wxPayBillSP.setTime_expire(Utility.getDataFormatStringYYYYMMDDHHmmss(record.getPayTimeEnd())); - wxPayBillSP.setSign_type("HMAC-SHA256"); - wxPayBillSP.setProfit_sharing(null); - if (isShare == EnumPayShare.YES) { - wxPayBillSP.setProfit_sharing("Y"); - } - Map payBillMap = BeanUtils.toStringMap(wxPayBillSP); - wxPayBillSP.setSign(WxPayment.createSignHMAC(payBillMap, payAccount.getApiKey())); - String response = WxPay.pushOrder(BeanUtils.toStringMap(wxPayBillSP)); - logger.info("pay bill, wechat pushBill, " + wxPayBillSP.toString() + ", response: " + response); - Map returnMap = WxPayment.xmlToMap(response); - returnMap.put("payBillId", record.getId().toString()); - String result_code = returnMap.get("result_code"); - if ("SUCCESS".equals(result_code)) { - String prepay_id = returnMap.get("prepay_id"); - // update payBill with prepay_id - record.setPrepayId(prepay_id); - record.setUpdateTime(new Date()); - try { - wxPayBillMapper.updateById(record); - } catch (Exception e) { - logger.error("pay bill update error: " + record.toString()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - String timestamp = String.valueOf(Utility.getCurrentTimeStamp()); - Map sighMap = MapUtil.getOrderMap(); - sighMap.put("appId", appInfo.getAppId()); - sighMap.put("timeStamp", timestamp); - sighMap.put("nonceStr", noncestr); - sighMap.put("package", "prepay_id=" + prepay_id); - sighMap.put("signType", "HMAC-SHA256"); - String signAgent = WxPayment.createSignHMAC(sighMap, payAccount.getApiKey()); - returnMap.put("timeStamp", timestamp); - returnMap.put("nonceStr", noncestr); - returnMap.put("package", "prepay_id=" + prepay_id); - returnMap.put("paySign", signAgent); - returnMap.put("signType", "HMAC-SHA256"); - logger.info("back to UI: " + returnMap.toString()); - return new ResultData(Result.SUCCESS, "创建支付订单成功", returnMap); - } - return updatePayBill(record, returnMap, result_code); - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - private ResultData updatePayBill(WxPayBill record, Map returnMap, String result_code) { - String errMsg = ""; - JSONObject errObj = errorMap.getJSONObject(result_code); - if (errObj != null) { - errMsg = errObj.toJSONString(); - record.setFailReason(errMsg); - } else { - errMsg = returnMap.get("return_msg"); - record.setFailReason(errMsg); - } - record.setUpdateTime(new Date()); - try { - wxPayBillMapper.updateById(record); - } catch (Exception e) { - logger.error("pay bill update error: " + record.toString()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(), errMsg, returnMap); - } - - - private String wechatPayBillQuery(WxAppinfo appInfo, WxPayBill record) { - // get payAccount - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); - if (payAccount.getType().equals(EnumPayMode.MCH.getCode())) { - // 普通商户号模式 - WxPayOrderQ payBillQ = new WxPayOrderQ(); - String noncestr = Utility.generate32UUID(); - payBillQ.setAppid(appInfo.getAppId()); - payBillQ.setMch_id(payAccount.getMchId()); - payBillQ.setNonce_str(noncestr); - payBillQ.setOut_trade_no(record.getPayBillNo()); - - try { - Map map = BeanUtils.toStringMap(payBillQ); - payBillQ.setSign(WxPayment.createSign(map, payAccount.getApiKey())); - map = BeanUtils.toStringMap(payBillQ); - String response = WxPay.orderQuery(map); - return response; - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } else { - // 服务商模式 - WxPayOrderSQ payBillSQ = new WxPayOrderSQ(); - String noncestr = Utility.generate32UUID(); - payBillSQ.setAppid(appInfo.getParentAppId()); - payBillSQ.setSub_appid(appInfo.getAppId()); - payBillSQ.setMch_id(payAccount.getMchId()); - payBillSQ.setSub_mch_id(payAccount.getSubMchId()); - payBillSQ.setNonce_str(noncestr); - payBillSQ.setOut_trade_no(record.getPayBillNo()); - payBillSQ.setSign_type("HMAC-SHA256"); - - try { - Map map = BeanUtils.toStringMap(payBillSQ); - payBillSQ.setSign(WxPayment.createSignHMAC(map, payAccount.getApiKey())); - map = BeanUtils.toStringMap(payBillSQ); - - String response = WxPay.orderQuery(map); - return response; - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - } - - /** - * 微信订单查询 - */ - @Override - public ResultData payBillQuery(WxAppinfo appInfo, WxPayBill record) { - try { - if (StringUtils.isBlank(record.getPayBillNo())) { - record.setPayBillNo(record.getPayBillNo()); - } - - String response = wechatPayBillQuery(appInfo, record); - - logger.info("pay bill query, " + record.toString() + ", response: " + response); - Map returnMap = WxPayment.xmlToMap(response); - String result_code = returnMap.get("result_code"); - if ("SUCCESS".equals(result_code)) { - String trade_state = returnMap.get("trade_state"); - //SUCCESS—支付成功 - //REFUND—转入退款 - //NOTPAY—未支付 - //CLOSED—已关闭 - //REVOKED—已撤销(刷卡支付) - //USERPAYING--用户支付中 - //PAYERROR--支付失败(其他原因,如银行返回失败) - if ("SUCCESS".equals(trade_state)) { - record.setPayBillStatus(EnumPayStatus.PAY_STATUS_SUCCESS.getCode()); - handlePayBillStatusUpdate(record); - } else if ("USERPAYING".equals(trade_state)) { - record.setPayBillStatus(EnumPayStatus.PAY_STATUS_WAIT.getCode()); - handlePayBillStatusUpdate(record); - } else { - record.setPayBillStatus(EnumPayStatus.PAY_STATUS_FAIL.getCode()); - handlePayBillStatusUpdate(record); - } - return new ResultData(Result.SUCCESS, "订单查询成功", returnMap); - } else { - return updatePayBill(record, returnMap, result_code); - } - } catch (MallinkException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - private String wechatPayBillClose(WxAppinfo appInfo, WxPayBill record) { - // get payAccount - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appInfo.getPayId()); - if (payAccount.getType().equals(EnumPayMode.MCH.getCode())) { - // 普通商户号模式 - WxPayOrderQ payBillC = new WxPayOrderQ(); - String noncestr = Utility.generate32UUID(); - payBillC.setAppid(appInfo.getAppId()); - payBillC.setMch_id(payAccount.getMchId()); - payBillC.setNonce_str(noncestr); - payBillC.setOut_trade_no(record.getPayBillNo()); - return closeOrderNormal(payAccount, payBillC); - } else { - // 服务商模式 - WxPayOrderSQ payBillSC = new WxPayOrderSQ(); - String noncestr = Utility.generate32UUID(); - payBillSC.setAppid(appInfo.getParentAppId()); - payBillSC.setSub_appid(appInfo.getAppId()); - payBillSC.setMch_id(payAccount.getMchId()); - payBillSC.setSub_mch_id(payAccount.getSubMchId()); - payBillSC.setNonce_str(noncestr); - payBillSC.setOut_trade_no(record.getPayBillNo()); - payBillSC.setSign_type("HMAC-SHA256"); - return closeOrderServer(payAccount, payBillSC); - } - } - - private String closeOrderServer(WxPayAccount payAccount, WxPayOrderSQ payBillSC) { - try { - Map map = BeanUtils.toStringMap(payBillSC); - payBillSC.setSign(WxPayment.createSignHMAC(map, payAccount.getApiKey())); - map = BeanUtils.toStringMap(payBillSC); - String response = WxPay.closeOrder(map); - return response; - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - private String closeOrderNormal(WxPayAccount payAccount, WxPayOrderQ payBillC) { - try { - Map map = BeanUtils.toStringMap(payBillC); - payBillC.setSign(WxPayment.createSign(map, payAccount.getApiKey())); - map = BeanUtils.toStringMap(payBillC); - String response = WxPay.closeOrder(map); - return response; - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - /** - * 微信关闭支付订单 - */ - @Override - public ResultData payBillClose(WxAppinfo appInfo, WxPayBill record) { - - try { - //关闭之前先查询 - ResultData resultData = payBillQuery(appInfo, record); - if(resultData.code == Result.SUCCESS) { - Map map = (Map) resultData.data; - if("SUCCESS".equals(map.get("result_code")) && "SUCCESS".equals(map.get("trade_state"))){ - return new ResultData(ErrorCode.ORDER_HAD_PAY); - } - } - - String response = wechatPayBillClose(appInfo, record); - - logger.info("pay bill close, " + record.toString() + ", response: " + response); - Map returnMap = WxPayment.xmlToMap(response); - String result_code = returnMap.get("result_code"); - if ("SUCCESS".equals(result_code)) { - try { - record.setPayBillStatus(EnumPayStatus.PAY_STATUS_CANCEL.getCode()); - wxPayBillMapper.updateById(record); - } catch (Exception e) { - logger.error("pay bill update error: " + record.toString()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - return new ResultData(Result.SUCCESS, "订单关闭成功", returnMap); - } else { - String errMsg = ""; - JSONObject errObj = errorMapClose.getJSONObject(result_code); - if (errObj != null) { - errMsg = errObj.toJSONString(); - } else { - errMsg = returnMap.get("return_msg"); - } - record.setFailReason(errMsg); - record.setUpdateTime(new Date()); - try { - wxPayBillMapper.updateById(record); - } catch (Exception e) { - logger.error("pay bill update error: " + record.toString()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - return new ResultData(ErrorCode.PAY_ORDER_ERROR.getCode(), errMsg, returnMap); - } - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - - /** - * 提供微信支付回调调用 - * - * @param paramMap 异步通知参数 - * @param payWay 支付方式 - * @return - */ - @Override - public String notify(String tenantId,Map paramMap, EnumPayWay payWay) { - // how to get wechatAppId, wechatMchId, partnerKey - logger.info("-------------"); - logger.info("微信回调返回值:" + JSONObject.toJSONString(paramMap)); - logger.info("-------------"); - String appId = paramMap.get("appid"); - String subAppId = paramMap.get("sub_appid"); - String mchId = paramMap.get("mch_id"); - String subMchId = paramMap.get("sub_mch_id"); - String attach = paramMap.get("attach"); - WxAppinfo appinfo; - boolean isNormal = true; - if (StringUtils.isBlank(subAppId) && StringUtils.isBlank(subMchId)) { - // 普通商户号 - appinfo = wxAppinfoService.getByAppIdFromRedis(appId,tenantId); - if (appinfo == null) { - throw new MallinkException(ErrorCode.APP_ID_NOT_FOUND); - } - isNormal = true; - } else { - // 服务号 现在用hmac-sha256 - appinfo = wxAppinfoService.getByAppIdFromRedis(subAppId,tenantId); - if (appinfo == null) { - throw new MallinkException(ErrorCode.APP_ID_NOT_FOUND); - } - isNormal = false; - } - - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - if (payAccount == null) { - throw new MallinkException(ErrorCode.MCH_INFO_NOT_FOUND); - } - String partnerKey = payAccount.getApiKey(); - try { - if (payWay.getType() == EnumPayWay.EnumPayWayType.WX_MINIPAY) { - boolean signVerified = false; - if (isNormal) { - // 普通商户号支付 - signVerified = WxPayment.verifyNotify(paramMap, partnerKey); - if (!signVerified) { - logger.warn("notify bill, wxpay checksign error, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - throw new MallinkException(ErrorCode.PAY_ORDER_NOTIFY_CHECK_SIGN_ERROR); - } - } else { - // 服务号 现在用hmac-sha256 - signVerified = WxPayment.verifyNotifyHMAC(paramMap, partnerKey); - if (!signVerified) { - logger.warn("notify bill, wxpay checksign error, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - throw new MallinkException(ErrorCode.PAY_ORDER_NOTIFY_CHECK_SIGN_ERROR); - } - } - - if (!"SUCCESS".equals(paramMap.get("return_code"))) { - logger.warn("notify bill, wxpay status not success, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", "订单状态码非SUCCESS"); - return XmlUtil.getRequestXml(resultMap); - } - - String payBillNo = paramMap.get("out_trade_no"); - String timEndStr = paramMap.get("time_end"); - Long payBillId = Long.valueOf(payBillNo.substring(0,payBillNo.length()-12)); - WxPayBill payBill = wxPayBillMapper.selectById(payBillId); - if (payBill == null) { - logger.warn("notify bill, wxpay check pay bill not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", "订单不存在"); - return XmlUtil.getRequestXml(resultMap); - } - // 验证支付金额 - if (!paramMap.get("total_fee").equals(payBill.getPayAmount().toString())) { - logger.warn("notify bill, wxpay check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", "订单总金额不一致"); - return XmlUtil.getRequestXml(resultMap); - } - - Date timeEnd = null; - - try { - timeEnd = Utility.getDateFromString(timEndStr); - } catch (ParseException e) { - logger.error("解析timeEnd失败"); - timeEnd = new Date(); - } - payBill.setPayTimeEnd(timeEnd); - - // 处理支付成功 - handleBillPaySuccess(payBill, paramMap.get("transaction_id")); - logger.info("notify bill, wxpay checksign success, paramMap:{}, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "SUCCESS"); - resultMap.put("return_msg", "OK"); - return XmlUtil.getRequestXml(resultMap); - } - } catch (RuntimeException e) { - logger.warn("notify bill, checksign error, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR); - } - - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", "FAILED"); - return XmlUtil.getRequestXml(resultMap); - } - - - @Override - public WxPayBill getById(Long id) { - return wxPayBillMapper.selectById(id); - } - - @Override - public void updatePayBillStatus(WxPayBill payBill) { - try { - logger.info("更新支付订单"); - wxPayBillMapper.updateById(payBill); - }catch (MallinkException e){ - logger.info("更新支付订单失败"); - throw new MallinkException(ErrorCode.ORDER_UPDATE_ERR); - } - } - - @Override - public WxPayBill queryPayBill(WxPayBill payBill) { - List select = wxPayBillMapper.selectList(new QueryWrapper(payBill)); - if(select.size()>0){ - return select.get(0); - } - return null; - } - - @Override - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public void handleBillPaySuccess(WxPayBill record, String transactionId) { - Date currentDate = new Date(); - EnumPayStatus payStatus = EnumPayStatus.getEnum(record.getPayBillStatus()); - // 判断支付状态 - if (payStatus == EnumPayStatus.PAY_STATUS_SUCCESS) { - // 已经是成功状态,只更新transactionId - try { - record.setUpdateTime(currentDate); - record.setTransactionId(transactionId); - wxPayBillMapper.updateById(record); - WxBillAll wxBillAll = new WxBillAll(); - wxBillAll.setId(record.getBillId()); - wxBillAll.setBillTypeValue(record.getBillTypeValue()); - WxMerchantBUser buser = wxMerchantBUserService.getById(record.getbUserId()); - WxMerchant wxMerchant = wxMerchantService.getById(buser.getMerchantId()); - List> bills = wxBillAllService.listBill(wxBillAll, wxMerchant,false, false, false, false); - if (bills.size() > 0) { - Map bill = bills.get(0); - bill.put("userId", record.getbUserId()); - wxBillAllService.updateBill(bill); - } - } catch (Exception e) { - logger.error(e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL); - } - return; - } - WxBillAll wxBillAll = new WxBillAll(); - wxBillAll.setId(record.getBillId()); - wxBillAll.updateTenantInfo(record); - List> bills = wxBillAllService.listBill(wxBillAll, null,false, false, false, false); - if (bills.size()==0) { - logger.error("pay success handle, bill " + record.getBillId() + " not found , payBillNo : " + record.getPayBillNo()); - throw new MallinkException(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND); - } - Map bill; - bill = bills.get(0); - bill.put("userId", record.getbUserId()); - // 修改支付订单状态 - WxPayBill updateBill = new WxPayBill(); - updateBill.setId(record.getId()); - updateBill.setBillId(record.getBillId()); - updateBill.setUpdateTime(currentDate); - updateBill.setPayBillStatus(EnumPayStatus.PAY_STATUS_SUCCESS.getCode()); - updateBill.setTransactionId(transactionId); - try { - wxPayBillMapper.updateById(updateBill); - } catch (Exception e) { - logger.error("支付订单数据库更新失败: " + e.getMessage()); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "支付订单数据库更新失败: " + e.getMessage()); - } - - //修改账单状态 - try { - wxBillAllService.updateBill(bill); - } catch (Exception e) { - logger.error(e.getMessage()); - throw new MallinkException(ErrorCode.BILL_UPDATE_FAILED); - } - - } - - @Override - @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class}) - public void handlePayBillStatusUpdate(WxPayBill record) { - // 判断支付状态 - if (record.getPayBillStatus().equals(EnumPayStatus.PAY_STATUS_WAIT.getCode())) { - logger.error("pay handle, payBill " + record.getPayBillNo() + - "is complete, billId : " + record.getBillId()); - return; - } - WxBillAll wxBillAll = new WxBillAll(); - wxBillAll.setId(record.getBillId()); - wxBillAll.setBillTypeValue(record.getBillTypeValue()); - WxMerchantBUser buser = wxMerchantBUserService.getById(record.getbUserId()); - WxMerchant wxMerchant = wxMerchantService.getById(buser.getMerchantId()); - List> bills = wxBillAllService.listBill(wxBillAll, wxMerchant,false, false, false, false); - if (bills.size()==0) { - logger.error("pay handle, bill " + record.getBillId() + " not found , payBillNo : " + record.getPayBillNo()); - throw new MallinkException(ErrorCode.ORDER_IS_NOT_FIND); - } - Map bill = bills.get(0); - if (record.getId() > 0) { - // 1. get appinfo - WxAppinfo appInfo = null; - WxAppinfo appinfoQ = new WxAppinfo(); - appinfoQ.setTenantId(bill.get("tenantId").toString()); - appinfoQ.setType(EnumAppType.B.getCode()); - List appList = wxAppinfoService.getList(appinfoQ); - if (appList.size() > 0) { - appInfo = appList.get(0); - } - - // 检查支付订单状态 - WxPayBill payBillQ = new WxPayBill(); - payBillQ.setId(record.getId()); - payBillQ.setTenantId(bill.get("tenantId").toString()); - payBillQ.setBillId(record.getBillId()); - WxPayBill updateBill; - try { - updateBill = wxPayBillMapper.selectOne(new QueryWrapper(payBillQ)); - } catch (Exception e) { - logger.error(e.getMessage()); - throw new MallinkException(ErrorCode.PAY_ORDER_NOT_FOUND); - } - - if (record.getPayBillStatus().equals(EnumPayStatus.PAY_STATUS_FAIL.getCode())) { - // 支付订单取消 - if (updateBill.getPayAmount() > 0) { - payBillQ = new WxPayBill(); - payBillQ.setTenantId(bill.get("tenantId").toString()); - payBillQ.setBillId(record.getBillId()); - List payBills = wxPayBillMapper.selectList(new QueryWrapper(payBillQ)); - for (WxPayBill payBill : payBills) { - if(payBill.getPayTimeEnd().before(new Date())){ - payBillClose(appInfo, payBill); - } - } - } - } else { - // 支付订单成功? - if (updateBill.getPayBillStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) { - if (!StringUtils.isBlank(updateBill.getTransactionId())) { - // 回调已设置成功 - wxBillAllService.updateBill(bill); - // 继续修改订单状态 - } else { - // 回调异常 - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "transactionId未获取"); - } - } else if (updateBill.getPayBillStatus().equals(EnumPayStatus.PAY_STATUS_WAIT.getCode())) { - // 回调未返回,主动检查支付订单状态 - try { - record.setPayBillNo(String.valueOf(record.getId())); - String response = wechatPayBillQuery(appInfo, record); - logger.info("pay bill query, " + record.toString() + ", response: " + response); - Map returnMap = WxPayment.xmlToMap(response); - String result_code = returnMap.get("result_code"); - if ("SUCCESS".equals(result_code)) { - String trade_state = returnMap.get("trade_state"); - //SUCCESS—支付成功 - //REFUND—转入退款 - //NOTPAY—未支付 - //CLOSED—已关闭 - //REVOKED—已撤销(刷卡支付) - //USERPAYING--用户支付中 - //PAYERROR--支付失败(其他原因,如银行返回失败) - if ("SUCCESS".equals(trade_state)) { - // 查询支付订单 -- 已支付 - // 继续更改状态 - wxBillAllService.updateBill(bill); - } else { - // 支付订单未成功,返回异常 - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "支付订单未成功"); - } - } - } catch (MallinkException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (RuntimeException e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), e.getMessage()); - } - } - } - } - - } - - -} diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxRefundOrderServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxRefundOrderServiceImpl.java index 06faaf3..fb86277 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxRefundOrderServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxRefundOrderServiceImpl.java @@ -586,26 +586,6 @@ public class WxRefundOrderServiceImpl implements WxRefundOrderService { } } - /** - * 微信退款结果通知 - * - * @param paramMap 异步通知参数 - * @param payWay 支付方式 - * @return - */ - @Override - public String notify(Map paramMap, EnumPayWay payWay,EnumPayVersion payVersion) { - RefundNotifyAdapterResult notifyResult = payServiceFactory.getRefundPayAdapterService(payWay.getCode(),payVersion.getCode()).notify(paramMap, payWay); - if (!notifyResult.isSuccess()) { - return notifyResult.getReturnJson(); - }else { - if (null != notifyResult.getRefundOrder()) { - handleRefundSuccess(notifyResult.getRefundOrder()); - } - return notifyResult.getReturnJson(); - } - } - @Override public void callback(Map paramMap, EnumPayWay payWay) { diff --git a/suimangService/src/main/java/com/iformall/service/impl/WxThirdPartyApiServiceImpl.java b/suimangService/src/main/java/com/iformall/service/impl/WxThirdPartyApiServiceImpl.java index 00ba72c..c5998a6 100644 --- a/suimangService/src/main/java/com/iformall/service/impl/WxThirdPartyApiServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/impl/WxThirdPartyApiServiceImpl.java @@ -1,12 +1,25 @@ package com.iformall.service.impl; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; -import com.iformall.domain.po.WxAppinfo; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.CommonConstants; +import com.iformall.common.ErrorCode; +import com.iformall.common.IdWorker; +import com.iformall.domain.dto.sm.SaveThirdPartyApiDTO; +import com.iformall.domain.dto.sm.UpdateThirdPartyApiStatusDTO; import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.exception.BizException; +import com.iformall.mapper.ServiceInfoMapper; import com.iformall.mapper.WxThirdPartyApiMapper; import com.iformall.service.WxThirdPartyApiService; import com.iformall.utils.Constant; import com.iformall.utils.RedisCacheUtils; +import com.iformall.utils.sign.AppUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -25,6 +38,8 @@ public class WxThirdPartyApiServiceImpl implements WxThirdPartyApiService { @Autowired WxThirdPartyApiMapper wxThirdPartyApiMapper; + @Autowired + private ServiceInfoMapper serviceInfoMapper; @Autowired @Qualifier("objectCommonRedisTemplate") @@ -48,8 +63,73 @@ public class WxThirdPartyApiServiceImpl implements WxThirdPartyApiService { WxThirdPartyApi apiQ = new WxThirdPartyApi(); apiQ.setAppId(appId); apiQ.setAppKey(appKey); + apiQ.setStatus(CommonConstants.STATUS_NORMAL); apiConfig = wxThirdPartyApiMapper.selectOne(new QueryWrapper<>(apiQ)); RedisCacheUtils.cache(redisTemplate, Constant.publicApi + appId, apiConfig,0l); return apiConfig; } + + @Override + public PageInfo pageThirdPartyApi(WxThirdPartyApi thirdPartyApi, Integer pageNum, Integer pageSize) { + return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> wxThirdPartyApiMapper.listThirdPartyApi(thirdPartyApi)); + } + + @Override + public void saveThirdPartyApi(SaveThirdPartyApiDTO dto) { + WxThirdPartyApi thirdPartyApi = buildThirdPartyApi(dto); + wxThirdPartyApiMapper.insert(thirdPartyApi); + } + + @Override + public void updateThirdPartyApiStatus(UpdateThirdPartyApiStatusDTO dto) { + WxThirdPartyApi thirdPartyApi = wxThirdPartyApiMapper.selectOne(new LambdaQueryWrapper().eq(WxThirdPartyApi::getId, dto.getId())); + if (thirdPartyApi == null) { + throw new BizException(ErrorCode.SECRET_NOT_EXISTS); + } + ServiceInfo serviceInfo = serviceInfoMapper.selectOne(new LambdaQueryWrapper().eq(ServiceInfo::getId, thirdPartyApi.getServiceId())); + if (serviceInfo == null || CommonConstants.STATUS_ABNORMAL.equals(serviceInfo.getStatus())) { + throw new BizException(ErrorCode.SERVICE_LOCKED); + } + wxThirdPartyApiMapper.update(null, new LambdaUpdateWrapper() + .set(WxThirdPartyApi::getStatus, dto.getStatus()) + .eq(WxThirdPartyApi::getId, dto.getId())); + } + + @Override + public WxThirdPartyApi getThirdPartyApi(Long id) { + WxThirdPartyApi thirdPartyApi = new WxThirdPartyApi(); + thirdPartyApi.setId(id); + List vos = wxThirdPartyApiMapper.listThirdPartyApi(thirdPartyApi); + return !CollectionUtils.isEmpty(vos) ? vos.get(0) : null; + } + + @Override + public WxThirdPartyApi getThirdPartyApiByServiceId(Long serviceId) { + WxThirdPartyApi thirdPartyApi = new WxThirdPartyApi(); + thirdPartyApi.setServiceId(serviceId); + List vos = wxThirdPartyApiMapper.listThirdPartyApi(thirdPartyApi); + return !CollectionUtils.isEmpty(vos) ? vos.get(0) : null; + } + + /** + * 构建秘钥实体 + * + * @param dto + * @return {@link WxThirdPartyApi} + */ + private WxThirdPartyApi buildThirdPartyApi(SaveThirdPartyApiDTO dto) { + WxThirdPartyApi thirdPartyApi = new WxThirdPartyApi(); + thirdPartyApi.setId(IdWorker.get().nextId()); + thirdPartyApi.setType(dto.getType()); + thirdPartyApi.setName(dto.getName()); + thirdPartyApi.setServiceId(dto.getServiceId()); + String appId = AppUtils.getAppId(); + String appKey = AppUtils.getAppKey(appId); + String signKey = AppUtils.getSignKey(appId, appKey); + thirdPartyApi.setAppId(appId); + thirdPartyApi.setAppKey(appKey); + thirdPartyApi.setSignKey(signKey); + thirdPartyApi.setStatus(CommonConstants.STATUS_NORMAL); + return thirdPartyApi; + } } diff --git a/suimangService/src/main/java/com/iformall/service/msg/impl/FmInsideNotifyRefundSuccessMsgServiceImpl.java b/suimangService/src/main/java/com/iformall/service/msg/impl/FmInsideNotifyRefundSuccessMsgServiceImpl.java deleted file mode 100644 index a236e8f..0000000 --- a/suimangService/src/main/java/com/iformall/service/msg/impl/FmInsideNotifyRefundSuccessMsgServiceImpl.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.iformall.service.msg.impl; - -import com.alibaba.fastjson.JSON; -import com.iformall.domain.po.msg.BaseMsg; -import com.iformall.domain.po.msg.FmInsideNotifyRefundSuccessMsg; -import com.iformall.enums.EnumPayVersion; -import com.iformall.enums.EnumPayWay; -import com.iformall.service.WxRefundOrderService; -import com.iformall.service.msg.MsgSendService; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Map; - -/** - * - * @author Stormeye Wu - * @date 2019/5/10 - */ -@Service -public class FmInsideNotifyRefundSuccessMsgServiceImpl implements MsgSendService { - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - private WxRefundOrderService wxRefundOrderService; - - @Override - public void send(BaseMsg baseMsg) throws Exception { - FmInsideNotifyRefundSuccessMsg msg = (FmInsideNotifyRefundSuccessMsg)baseMsg; - Map paramMap = JSON.parseObject(msg.getJsonMsg(), Map.class); - wxRefundOrderService.notify(paramMap, EnumPayWay.getEnum(msg.getPayWay()),EnumPayVersion.getEnum(msg.getPayVersion())); - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/ParkAdapterService.java b/suimangService/src/main/java/com/iformall/service/park/ParkAdapterService.java deleted file mode 100644 index a187ba1..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/ParkAdapterService.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.iformall.service.park; - -import java.util.Map; - -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; - -/** - * 新的用NewParkAdapterService - * @author alascor - * - */ -public interface ParkAdapterService { - - ResultData parkInitConfig(WxPark park) throws Exception; - - /** - * 停车场初始化登陆 - * @param paramMap - * @param park - * @param member - * @return vendorPersonId 停车场的会员编号 - */ - String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception; - - /** - * 绑定车牌 - * @param paramMap - * @param park - * @param cuUserId - * @return vendorPersonId 停车场的会员编号 - */ - String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception; - - /** - * 解绑车牌 - */ - void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception; - - /** - * 获取停车费, 给老的集成用 - */ - ResultData carStopFee(Map paramMap, WxPark park) throws Exception; - - /** - * 是否忽略使用券缓存,不忽略,则走系统,根据停车场出入场通知来控制。忽略,则不需要此判断来判定停车券是否已经使用 - * @return - */ - boolean ignoreUseCouponCache(); - - /** - * 停车券使用, 给老的集成用 - */ - ResultData useCoupon(Map paramMap,WxPark park,WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) throws Exception; - - /** - * 查询停车场状态, 给老的集成用 - */ - ResultData getParkStatus(WxPark park) throws Exception; -} diff --git a/suimangService/src/main/java/com/iformall/service/park/ParkBatchCallBackAdapterService.java b/suimangService/src/main/java/com/iformall/service/park/ParkBatchCallBackAdapterService.java deleted file mode 100644 index 1624c3a..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/ParkBatchCallBackAdapterService.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.iformall.service.park; - -import java.util.List; -import java.util.Map; - -import com.iformall.service.park.entity.ParkNotifyParam; - -/** - * 停车场回调 -- 批量传回 - * @author alascor - * - */ -public interface ParkBatchCallBackAdapterService { - - /** - * 解析车辆入场通知参数 - * @param param - */ - List parseInNoticyParam(Object param); - - /** - * 解析车辆出场通知参数 - * @param param - */ - List parseOutNoticyParam(Object param); - - /** - * 解析车辆解绑通知参数 - * @param param - */ - List parseUnbindNoticyParam(Object param); - - /** - * 解析支付结果通知参数 - * @param param - */ - List parsePaidNoticyParam(Object param); -} diff --git a/suimangService/src/main/java/com/iformall/service/park/ParkCallBackAdapterService.java b/suimangService/src/main/java/com/iformall/service/park/ParkCallBackAdapterService.java deleted file mode 100644 index cff99ce..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/ParkCallBackAdapterService.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.iformall.service.park; - -import java.util.Map; - -import com.iformall.service.park.entity.ParkNotifyParam; - -/** - * 停车场回调 - * @author alascor - * - */ -public interface ParkCallBackAdapterService { - - /** - * 解析车辆入场通知参数 - * @param param - */ - ParkNotifyParam parseInNoticyParam(Object param); - - /** - * 解析车辆出场通知参数 - * @param param - */ - ParkNotifyParam parseOutNoticyParam(Object param); - - /** - * 解析车辆解绑通知参数 - * @param param - */ - ParkNotifyParam parseUnbindNoticyParam(Object param); - - /** - * 解析支付结果通知参数 - * @param param - */ - ParkNotifyParam parsePaidNoticyParam(Object param); -} diff --git a/suimangService/src/main/java/com/iformall/service/park/ParkFactory.java b/suimangService/src/main/java/com/iformall/service/park/ParkFactory.java deleted file mode 100644 index 24899d8..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/ParkFactory.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.iformall.service.park; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.iformall.common.ErrorCode; -import com.iformall.enums.EnumCarVendor; -import com.iformall.exception.MallinkException; -import com.iformall.service.park.impl.bolink.BoLinkParkService; -import com.iformall.service.park.impl.cyf.CYFParkCallbackService; -import com.iformall.service.park.impl.cyf.CYFParkService; -import com.iformall.service.park.impl.dahua.DaHuaParkService; -import com.iformall.service.park.impl.haikangweishi.HaiKangWeiShiParkCallbackService; -import com.iformall.service.park.impl.haikangweishi.HaiKangWeiShiParkService; -import com.iformall.service.park.impl.jieshun.JieShunParkCallbackService; -import com.iformall.service.park.impl.jieshun.JieShunParkService; -import com.iformall.service.park.impl.shangan.ShangAnParkService; -import com.iformall.service.park.impl.tjd.TJDParkService; - -@Service -public class ParkFactory { - - @Autowired - CYFParkService cyfService; - @Autowired - BoLinkParkService bolinkService; - @Autowired - DaHuaParkService daHuaService; - @Autowired - ShangAnParkService shangAnService; - @Autowired - TJDParkService tjdService; - @Autowired - JieShunParkService jieshunService; - @Autowired - HaiKangWeiShiParkService haikangWeishiService; - - @Autowired - CYFParkCallbackService cyfCallbackService; - @Autowired - JieShunParkCallbackService jieshunCallBackService; - @Autowired - HaiKangWeiShiParkCallbackService haikangWeishiCallBackService; - - private Map parkServiceMap ; - private Map enumMap ; - private Map callBackServiceMap;//推送单条 - private Map batchCallBackServiceMap;//推送多条 - - private Map getServiceMap() { - if (null != parkServiceMap ) { - return parkServiceMap; - } - parkServiceMap = new ConcurrentHashMap(); - //车易付 - parkServiceMap.put(EnumCarVendor.CAE_CYF.getCode(), cyfService); - parkServiceMap.put(EnumCarVendor.CAR_BOLINK.getCode(), bolinkService); - parkServiceMap.put(EnumCarVendor.CAR_DAHUA.getCode(), daHuaService); - parkServiceMap.put(EnumCarVendor.CAR_SHANGAN.getCode(), shangAnService); - parkServiceMap.put(EnumCarVendor.CAR_TJD.getCode(), tjdService); - parkServiceMap.put(EnumCarVendor.CAR_JIESHUN.getCode(), jieshunService); - parkServiceMap.put(EnumCarVendor.CAR_HAIKANGWEISHI.getCode(), haikangWeishiService); - return parkServiceMap; - - } - - private Map getEnumMap() { - if (null != enumMap) { - return enumMap; - } - enumMap = new ConcurrentHashMap(); - for (EnumCarVendor v : EnumCarVendor.values()) { - enumMap.put(v.getCode(), v); - } - return enumMap; - } - - private Map getCallBackServiceMap() { - if (null != callBackServiceMap) { - return callBackServiceMap; - } - callBackServiceMap = new ConcurrentHashMap(); - callBackServiceMap.put(EnumCarVendor.CAE_CYF.getCode(), cyfCallbackService); - return callBackServiceMap; - } - - private Map getBatchCallBackServiceMap() { - if (null != batchCallBackServiceMap) { - return batchCallBackServiceMap; - } - batchCallBackServiceMap = new ConcurrentHashMap(); - batchCallBackServiceMap.put(EnumCarVendor.CAR_JIESHUN.getCode(), jieshunCallBackService); - batchCallBackServiceMap.put(EnumCarVendor.CAR_HAIKANGWEISHI.getCode(), haikangWeishiCallBackService); - return batchCallBackServiceMap; - } - - - public ParkAdapterService getParkService(Integer code) { - EnumCarVendor vendor = getEnumMap().get(code); - if (null == vendor) { - throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "车厂["+code+"]不持支。"); - } - return getServiceMap().get(vendor.getCode()); - } - - public ParkCallBackAdapterService getParkCallbackService(Integer code) { - EnumCarVendor vendor = getEnumMap().get(code); - if (null == vendor) { - throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "车厂["+code+"]不支持."); - } - return getCallBackServiceMap().get(vendor.getCode()); - } - - public ParkBatchCallBackAdapterService getParkBatchCallbackService(Integer code) { - EnumCarVendor vendor = getEnumMap().get(code); - if (null == vendor) { - throw new MallinkException(ErrorCode.SYS_PARAMETER_ERROR.getCode(), "车厂["+code+"]不支持."); - } - return getBatchCallBackServiceMap().get(vendor.getCode()); - } - - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/entity/ParkNotifyParam.java b/suimangService/src/main/java/com/iformall/service/park/entity/ParkNotifyParam.java deleted file mode 100644 index f56ac6c..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/entity/ParkNotifyParam.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.iformall.service.park.entity; - -import java.io.Serializable; -import java.util.Date; - -import lombok.Data; - -@Data -public class ParkNotifyParam implements Serializable{ - - private static final long serialVersionUID = -8295607395328571534L; - - String parkId; - - String synId; - - String parkName; - - String carNumber; - - Date entranceTime; - - Date outTime; - - String fee; - - String parkOrderId; - - Date payTime; - - String paidServiceFee;//支付服务费 - - Object sourceParam; - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/entity/ParkStopFee.java b/suimangService/src/main/java/com/iformall/service/park/entity/ParkStopFee.java deleted file mode 100644 index 7a58005..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/entity/ParkStopFee.java +++ /dev/null @@ -1,121 +0,0 @@ -package com.iformall.service.park.entity; - -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; - -public class ParkStopFee implements Serializable{ - - private static final long serialVersionUID = 6478840764729191197L; - - /*停车场返回的订单ID**/ - private String orderId=""; - /*入场时间 格式:yyyy-MM-dd HH:mm:ss**/ - private String entranceTime=""; - /*计费结束时间 格式:yyyy-MM-dd HH:mm:ss**/ - private String exitTime=""; - /*停车费**/ - private String remainingFee=""; - /*跳转的停车费支付小程序appId**/ - private String appId=""; - /*支付小程序页面路径**/ - private String payPath=""; - /*给支付小程序的额外数据**/ - private Map extraData=new HashMap(); - /*备注**/ - private String remark=""; - private String sysNotice="";//系统提示,非车厂提示; - - - public ParkStopFee(String orderId,Date startTime,Date endTime,String fee,String appId,String payPath,Map extraData,String remark,String sysNotice) { - if (!StringUtils.isBlank(orderId)) { - this.orderId = orderId; - } - if (null != startTime) { - this.entranceTime = getLocalDate(startTime); - } - if (null != endTime) { - this.exitTime = getLocalDate(endTime); - } - if (!StringUtils.isBlank(fee)) { - this.remainingFee = fee; - } - if (!StringUtils.isBlank(appId)) { - this.appId = appId; - } - if (!StringUtils.isBlank(payPath)) { - this.payPath = payPath; - } - if (null != extraData) { - this.extraData = extraData; - } - if (!StringUtils.isBlank(remark)) { - this.remark = remark; - } - if (!StringUtils.isBlank(sysNotice)) { - this.sysNotice = sysNotice; - } - } - - - private String getLocalDate(Date date){ - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - return sdf.format(date); - } - - public String getOrderId() { - return orderId; - } - public void setOrderId(String orderId) { - this.orderId = orderId; - } - public String getEntranceTime() { - return entranceTime; - } - public void setEntranceTime(String entranceTime) { - this.entranceTime = entranceTime; - } - public String getExitTime() { - return exitTime; - } - public void setExitTime(String exitTime) { - this.exitTime = exitTime; - } - public String getRemainingFee() { - return remainingFee; - } - public void setRemainingFee(String remainingFee) { - this.remainingFee = remainingFee; - } - public String getAppId() { - return appId; - } - public void setAppId(String appId) { - this.appId = appId; - } - public String getPayPath() { - return payPath; - } - public void setPayPath(String payPath) { - this.payPath = payPath; - } - public Map getExtraData() { - return extraData; - } - public void setExtraData(Map extraData) { - this.extraData = extraData; - } - public String getRemark() { - return remark; - } - public void setRemark(String remark) { - this.remark = remark; - } - public String getSysNotice() { - return sysNotice; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/BaseParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/BaseParkService.java deleted file mode 100644 index b374729..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/BaseParkService.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.iformall.service.park.impl; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxPark; -import com.iformall.service.park.impl.util.ParkHelper; - -@Service -public class BaseParkService { - - @Autowired - ParkHelper parkHelper; - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkParkService.java deleted file mode 100644 index 993c86b..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkParkService.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.iformall.service.park.impl.bolink; - -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.impl.BaseParkService; - -@Service -public class BoLinkParkService extends BaseParkService implements ParkAdapterService { - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return null; - } - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return member.getId().toString(); - } - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - } - - @Override - public ResultData carStopFee(Map paramMap, WxPark park) { - return bolinkCarStopFee(paramMap, park); - } - - private ResultData bolinkCarStopFee(Map paramMap, WxPark park) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString(BoLinkUtil.BOLINK_URL); - String comid = objParams.getString(BoLinkUtil.BOLINK_COMID); - String unionId = objParams.getString(BoLinkUtil.BOLINK_UNION_ID); - String key = objParams.getString(BoLinkUtil.BOLINK_KEY); - String ret = BoLinkUtil.getStopFee(url, comid, unionId, key, carNumber); - if (ret != null) { - JSONObject retObj = JSON.parseObject(ret); - JSONObject dataObj = retObj.getJSONObject(BoLinkUtil.BOLINK_DATA); - if (dataObj.getIntValue(BoLinkUtil.BOLINK_STATE) == BoLinkUtil.BOLINK_SUCCESS) { - return new ResultData(dataObj); - } else { - return new ResultData(ErrorCode.BOLINK_STOP_FEE_FAIL); - } - } else { - return new ResultData(ErrorCode.BOLINK_STOP_FEE_FAIL); - } - } - - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) { - String orderId = paramMap.get("orderId"); - if (StringUtils.isBlank(orderId)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString(BoLinkUtil.BOLINK_URL); - String comid = objParams.getString(BoLinkUtil.BOLINK_COMID); - String unionId = objParams.getString(BoLinkUtil.BOLINK_UNION_ID); - String key = objParams.getString(BoLinkUtil.BOLINK_KEY); - - String amount = ""; - if (coupon.getUnit().equals(EnumCouponUnit.MONEY.getCode())) { - amount = coupon.getPriceStr(); - } else { - amount = String.valueOf(coupon.getPrice()* 60); - } - - String ret = BoLinkUtil.couponSend(url, comid, unionId, key, - carNumber, - orderId, - coupon.getUnit().toString(), amount); - JSONObject retObj = JSON.parseObject(ret); - JSONObject dataObj = retObj.getJSONObject(BoLinkUtil.BOLINK_DATA); - if (dataObj.getIntValue(BoLinkUtil.BOLINK_STATE) == BoLinkUtil.BOLINK_SUCCESS) { - return new ResultData(dataObj); - } else { - return new ResultData(ErrorCode.CAR_DEDUCE_FEE_FAIL); - } - } - - @Override - public ResultData getParkStatus(WxPark park) { - return null; - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } - - - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkUtil.java deleted file mode 100644 index 912c2aa..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/bolink/BoLinkUtil.java +++ /dev/null @@ -1,258 +0,0 @@ -package com.iformall.service.park.impl.bolink; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.exception.MallinkException; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -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.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * 尚安停车 - */ -public class BoLinkUtil { - private final static Logger logger = LoggerFactory.getLogger(BoLinkUtil.class); - - public static final String BOLINK_URL = "url"; - public static final String BOLINK_COMID = "comid"; - public static final String BOLINK_UNION_ID = "union_id"; - public static final String BOLINK_KEY = "key"; - public static final String BOLINK_CAR_NUMBER = "car_number"; - public static final String BOLINK_ORDER_ID = "order_id"; - public static final String BOLINK_PAY_TIME = "pay_time"; - public static final String BOLINK_ACT_TOTAL = "act_total"; - public static final String BOLINK_DEDUCTION_TIME = "deduction_time"; - public static final String BOLINK_DEDUCTION_MONEY = "deduction_money"; - - public static final String URL = "https://yun.bolink.club"; - public static final String COMID = "30536"; - public static final String UNION_ID = "200389"; - public static final String KEY = "Y29PZH9KDT1V7Y1E"; - public static final String PARK_NUM = "京88888"; - - public static final String BOLINK_DATA = "data"; - public static final String BOLINK_STATE = "state"; - public static final int BOLINK_SUCCESS = 1; - public static final int BOLINK_FAIL = 0; - public static final String BOLINK_ERROR = "errmsg"; - - - public static void main(String[] args) throws Exception { - String carNumber = "京88888"; - - String result = getStopFee(URL, COMID, UNION_ID, KEY, carNumber); - - - } - - /** - * md5算法 - * @param data - * @return - * @throws NoSuchAlgorithmException - */ - - public static String md5(String data) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(data.getBytes()); - StringBuilder buf = new StringBuilder(); - byte[] bits = md.digest(); - for(int i=0;i") || resp.startsWith("")) { - return true; - } - return false; - } - - public static String getStopFee(String baseUrl, String comid, String unionId, String key, String carNumber) { - String stopFeeUrl = "/zld/queryorderprice"; - String url = baseUrl + stopFeeUrl; - Map params = new HashMap<>(); - params.put(BOLINK_COMID, comid); - params.put(BOLINK_UNION_ID, unionId); - params.put(BOLINK_CAR_NUMBER, carNumber); - try { - String sign = getSign(key, JSON.toJSONString(params)); - } catch (Exception e) { - logger.error(e.getMessage()); - } - - try { - String result = Proc(url, key, params); - if(result == null) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - if(checkRespFailed(result)) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - return result; - } catch (Exception e) { - return null; - } - } - - public static String couponSend(String baseUrl, String comid, String unionId, String key, - String carNumber, - String orderId, - String unit, String amount) { - String couponUrl = "/zld/openservice/paynoticetopark"; - String url = baseUrl + couponUrl; - Map params = new HashMap<>(); - params.put(BOLINK_COMID, comid); - params.put(BOLINK_UNION_ID, unionId); - params.put(BOLINK_CAR_NUMBER, carNumber); - params.put(BOLINK_ORDER_ID, orderId); - params.put(BOLINK_PAY_TIME, new Date().getTime()); - params.put(BOLINK_ACT_TOTAL, "0"); - if (unit.equals(EnumCouponUnit.MONEY.getCode())) { - // 金额 - params.put(BOLINK_DEDUCTION_MONEY, amount); - } else { - // 小时 - params.put(BOLINK_DEDUCTION_TIME, amount); - } - try { - String sign = getSign(key, JSON.toJSONString(params)); - } catch (Exception e) { - logger.error(e.getMessage()); - } - - try { - String result = Proc(url, key, params); - if(result == null) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - if(checkRespFailed(result)) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - return result; - } catch (Exception e) { - return null; - } - } - - private static String Proc(String url, String key, Map paramMap) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader("Accept-Encoding", "UTF-8"); - - StringBuilder sb = new StringBuilder(); - String sign = null; - try{ - String dataStr = JSON.toJSONString(paramMap); - sb.append("{\"data\":").append(dataStr); - sign = getSign(key, dataStr); - sb.append(",\"sign\":\"").append(sign).append("\"}"); - }catch(NoSuchAlgorithmException e) { - logger.error(e.getLocalizedMessage()); - } - - String bodyStr = sb.toString(); - logger.info(bodyStr); - - final Base64.Encoder encoder = Base64.getEncoder(); - final Base64.Decoder decoder = Base64.getDecoder(); - - try { - byte[] bodyByte = bodyStr.getBytes("UTF-8"); - String encodeStr = encoder.encodeToString(bodyByte); - StringEntity se = new StringEntity(encodeStr, Consts.UTF_8); - se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8")); - httpPost.setEntity(se); - } catch (Exception e) { - logger.error(e.getMessage()); - } - - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - String result = null; - - //打印StatusLine - logger.debug("StatusLine: " + response.getStatusLine()); - if (response.getStatusLine().getStatusCode() != 200) { - logger.error("status error: " + response.getStatusLine().getReasonPhrase()); - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - String encodeResStr = EntityUtils.toString(httpEntity, "UTF-8"); - result = new String(decoder.decode(encodeResStr), "UTF-8"); - logger.debug(result); - // {"data":{"errmsg":"查询价格返回超时,请联系车场管理员","state":0,"plate_number":"京88888"},"sign":"DE81DCA41E6C1ACA978906F998A7BC1D"} - - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - logger.error(e.getLocalizedMessage()); - } - - JSONObject resultObj = JSON.parseObject(result); - String resSign = resultObj.getString("sign"); - if (!resSign.equals(sign)) { - logger.error("data sign: " + resSign); - throw new MallinkException(ErrorCode.BOLINK_SIGN_ERR); - } - - return result; - } - - - - -} - diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkCallbackService.java b/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkCallbackService.java deleted file mode 100644 index f28d9fc..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkCallbackService.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.iformall.service.park.impl.cyf; - -import java.text.ParseException; -import java.util.Date; -import java.util.Map; - -import org.springframework.stereotype.Service; - -import com.iformall.domain.vo.WxCarCYFVo; -import com.iformall.service.park.ParkCallBackAdapterService; -import com.iformall.service.park.entity.ParkNotifyParam; -import com.iformall.service.park.impl.BaseParkService; -import com.iformall.service.park.impl.tjd.TJDUtil; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -@Service -public class CYFParkCallbackService extends BaseParkService implements ParkCallBackAdapterService { - - @Override - public ParkNotifyParam parseInNoticyParam(Object param) { - Map paramMap = (Map) param; - String carNumber = paramMap.get(CYFUtil.CYF_CAR_NUMBER).toString(); - String cyfParkId = paramMap.get(CYFUtil.CYF_PARK_ID).toString(); - String parkName = paramMap.get(CYFUtil.CYF_PARK_NAME).toString(); - String synId = paramMap.get(CYFUtil.CYF_SYN_ID).toString(); - String entranceTime = paramMap.get(CYFUtil.CYF_ENTRANCE_TIME).toString(); - - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(carNumber); - p.setParkId(cyfParkId); - p.setParkName(parkName); - p.setSynId(synId); - try { - p.setEntranceTime(CYFUtil.utcToLocal(entranceTime)); - } catch (ParseException e) { - log.error("cyf entranceTime format error",e); - return null; - } - return p; - } - - @Override - public ParkNotifyParam parseOutNoticyParam(Object param) { - WxCarCYFVo vo = (WxCarCYFVo) param; - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(vo.getPlate()); - p.setParkId(String.valueOf(vo.getParkingId())); - p.setParkName(vo.getRecordOrderId()); - p.setSynId(vo.getRecordOrderId()); - try { - p.setEntranceTime(TJDUtil.dateOutFormat.parse(vo.getInInfo().getTime())); - } catch (ParseException e) { - log.error("cyf entranceTime format error",e); - return null; - } - try { - p.setOutTime(TJDUtil.dateOutFormat.parse(vo.getOutInfo().getTime())); - } catch (ParseException e) { - log.error("cyf outTime format error",e); - return null; - } - p.setFee(String.valueOf(vo.getPayInfoList().getActualFee())); - return p; - } - - @Override - public ParkNotifyParam parseUnbindNoticyParam(Object param) { - return null; - } - - @Override - public ParkNotifyParam parsePaidNoticyParam(Object param) { - Map vo = (Map) param; - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber((String) vo.get("plate")); - p.setParkId(String.valueOf(vo.get("parkId"))); - p.setParkOrderId((String) vo.get("orderNo")); - p.setSynId((String) vo.get("orderNo")); - p.setFee(vo.get("fee").toString()); - p.setPayTime((Date) vo.get("payTime")); - return p; - } - - - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkService.java deleted file mode 100644 index 7c47f75..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFParkService.java +++ /dev/null @@ -1,203 +0,0 @@ -package com.iformall.service.park.impl.cyf; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCUserCar; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.exception.MallinkException; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.entity.ParkStopFee; -import com.iformall.service.park.impl.BaseParkService; -import com.iformall.service.park.impl.util.ParkHelper; - -@Service -public class CYFParkService extends BaseParkService implements ParkAdapterService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ParkHelper parkHelper; - - CYFUtil cyf = new CYFUtil(); - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - WxCUserCar car = parkHelper.getOne(park, member.getId(), carNumber, EnumCarVendor.CAE_CYF); - if (null != car) { - return car.getVendorPersonId(); - } - return null; - } - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - return cyfBindCar(paramMap,park,member); - } - - /** - * @description 车易付会员车辆信息注册 - * @Params [paramMap, park, wxCUser] - * @return com.iformall.common.ResultData - * @Author furunxin - * @Date 2020/7/8 下午10:23 - **/ - private String cyfBindCar(Map paramMap, WxPark park,WxCUserBasicInfo member) throws Exception { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String token = objParams.getString("token"); - int feeGroupId = objParams.getIntValue("feeGroupId"); - String ret = cyf.registerCar(token,park.getNumber(),feeGroupId,park.getParkingId(),carNumber,null,member.getNickName()); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("result") == 1){ - return retObj.get("localPersonId").toString(); - }else { - logger.error("cyfBindCar error. paramMap: {} . cyfResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("strError"); - throw new MallinkException(ErrorCode.CAR_BIND_FAIL.getCode(), "绑车牌失败:"+msg); - //return new ResultData(, "绑车牌失败", retObj); - } - } - - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String vendorPersonId = paramMap.get("vendorPersonId"); - if (StringUtils.isBlank(vendorPersonId)) { - logger.error("vendorPersonId为空"); - throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "vendorPersonId为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String token = objParams.getString("token"); - String ret = cyf.unbindCar(token, park.getParkingId(), vendorPersonId); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("result") == 1){ - }else { - logger.error("cyfUnbindCar error. paramMap: {} . cyfResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("strError"); - throw new MallinkException(ErrorCode.CAR_BIND_FAIL.getCode(), "解绑车牌失败:"+msg); - //return new ResultData(, "绑车牌失败", retObj); - } - } - - - @Override - public ResultData carStopFee(Map paramMap, WxPark park) throws Exception{ - return cyfCarStopFee(paramMap, park); - } - - private ResultData cyfCarStopFee(Map paramMap, WxPark park) throws Exception{ - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String token = objParams.getString("token"); - String ret = cyf.getCarStopFee(token,park.getParkingId(),carNumber); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("result") == 1){ - Integer createTime = retObj.getInteger("inTime");//计费时间 - Integer endTime = retObj.getInteger("endTime");//离场时间 - String msg = retObj.getString("warmPrompt"); - String appId = ""; - String payPath = "http://wechat.cheyifu2016.com/fm-pay/#/transit?encodeURIComponent('orderNo=123&couponFee=2&actualFee=20')"; - return new ResultData(new ParkStopFee(retObj.getString("orderId"), cyf.utcToLocal(String.valueOf(createTime)), - cyf.utcToLocal(String.valueOf(endTime)), String.valueOf(retObj.getDouble("fee")),appId,payPath,null,msg,null)); - }else { - logger.error("cyfCarStopFee error. paramMap: {} . cyfResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("strError"); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "停车费获取失败:"+msg); - } - } - - /** - * 优惠券支付流程:(1):调取openapi/getFee路径获取当前停车费,入参:plate,parkingId,token - (2):调用地址:http://wechat.cheyifu2016.com/fm-pay/#/transit?encodeURIComponent('orderNo=123&couponFee=2&actualFee=20') - 注: 详细参考接口文档参数 - * @param token - * @param orderNo - * @param couponFee - * @param actualFee - * @return - */ - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) throws Exception{ - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String token = objParams.getString("token"); - //先获取停车费,然后再提交停车费 - String ret = cyf.getCarStopFee(token,park.getParkingId(),carNumber); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("result") == 1){ - String orderId = retObj.getString("orderId"); - if (StringUtils.isBlank(orderId)) { - logger.error("cyfCarStopFee error. paramMap: {} . cyfResult: {}",JSON.toJSONString(paramMap),ret); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "车易付停车费查询未返回订单编号:"+orderId); - } - if (!coupon.getUnit().equals(EnumCouponUnit.MONEY.getCode())) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "车易付只能支持金额券,不能使用小时券:"+orderId); - } - int fee = retObj.getInteger("fee"); - int amount = Integer.parseInt(coupon.getPriceStr()); - Map retmap = new HashMap(); - retmap.put("orderNo", orderId); - retmap.put("couponFee", amount); - retmap.put("actualFee", fee-amount); - return new ResultData(); - }else { - logger.error("cyfCarStopFee error. paramMap: {} . cyfResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("strError"); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "停车费获取失败:"+msg); - } - } - - @Override - public ResultData getParkStatus(WxPark park) throws Exception{ - return new ResultData(); - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFUtil.java deleted file mode 100644 index 72f5921..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/cyf/CYFUtil.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.iformall.service.park.impl.cyf; - -import com.alibaba.fastjson.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -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.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.TimeZone; - - -/** - * @author: furunxin - * @Date: 2020/7/1 17:16 - * @Description: 车易付接口对接参数类 - */ - -@Slf4j -public class CYFUtil { - - public static final String CYF_PARK_ID = "parkingId"; - public static final String CYF_CAR_NUMBER = "plate"; - public static final String CYF_PARK_NAME = "parking"; - public static final String CYF_SYN_ID = "recordOrderId"; - public static final String CYF_ENTRANCE_TIME = "inTime"; - - public static final String CYF_IS_RESULT = "result"; - public static final String CYF_ERR_MSG = "strError"; - public static final int CYF_SUC = 1; - public static final int CYF_ERR = 0; - - - //会员车辆信息注册接口地址 - public static final String REGISTER_CAR_URL = "http://open.cheyifu2016.com:8892/openapi/personCar"; - - //获取停车费 - public static final String GET_CAR_STOPFEE = "http://open.cheyifu2016.com:8892/openapi/getFee"; - - //解绑车辆 - public static final String UNBIND_CAR = "http://oepn.cheyifu2016.com:8892/openapi/personCar/delete"; - - //优惠券缴费接口 - public static final String COUPON_FEE = "http://oepn.cheyifu2016.com:8892/openapi/couponFee"; - - - - /** - * @description UTC时间转化为本地时间 - * @Params [utcTime] - * @return java.util.Date - * @Author furunxin - * @Date 2020/7/8 下午12:45 - **/ - public static Date utcToLocal(String seconds) throws ParseException { - String format = "yyyy-MM-dd HH:mm:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(format); - String d = sdf.format(new Date(Long.valueOf(seconds+"000"))); - Date date=sdf.parse(d); - return date; - } - - public static String getLocalDate(){ - LocalDateTime ldt = LocalDateTime.now(); - DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String nowDate = ldt.format(dtf); - return nowDate; - } - - - - /** - * @description 会员车辆信息注册 - * @Params [token, carport, feeGroupId, parkingId, plates, personId, personName] - * @return java.lang.String - * @Author furunxin - * @Date 2020/7/8 下午10:12 - **/ - public String registerCar(String token,int carport,int feeGroupId,String parkingId,String plates,Long personId,String personName){ - String[] plate = new String[1]; - plate[0] = plates; - Map paramMap = new HashMap<>(); - paramMap.put("token",token); - paramMap.put("parkingId",Integer.valueOf(parkingId)); - paramMap.put("beginTime",getLocalDate()); - paramMap.put("endTime",getLocalDate()); - paramMap.put("feeGroupId",feeGroupId); - paramMap.put("lotNumber",carport); - //paramMap.put("personId",personId); - paramMap.put("personName",personName); - paramMap.put("plates",plate); - String result = Proc(REGISTER_CAR_URL, paramMap); - return result; - } - - /** - * @description 根据车牌号获取停车费 - * @Params [token, parkingId, plates] - * @return java.lang.String - * @Author furunxin - * @Date 2020/7/12 下午3:51 - **/ - public String getCarStopFee(String token,String parkingId,String plates){ - Map paramMap = new HashMap<>(); - paramMap.put("token",token); - paramMap.put("parkingId",Integer.valueOf(parkingId)); - paramMap.put("plate",plates); - paramMap.put("carOutTime",0); - String result = Proc(GET_CAR_STOPFEE, paramMap); - return result; - } - - /** - * @description 解绑车辆 - * @param token - * @param parkingId - * @param personId - * @return - */ - public String unbindCar(String token,String parkingId,String vendorPersonId) { - Map paramMap = new HashMap<>(); - paramMap.put("token",token); - paramMap.put("parkingId",Integer.valueOf(parkingId)); - paramMap.put("personId",Integer.valueOf(vendorPersonId)); - String result = Proc(UNBIND_CAR, paramMap); - return result; - } - - private static String Proc(String url, Map paramMap) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Accept-Encoding", "UTF-8"); - - String jsonstr = JSON.toJSONString(paramMap); - log.info("请求报文:"+jsonstr); - - try { - StringEntity se = new StringEntity(jsonstr, Consts.UTF_8); - se.setContentType("application/json"); - se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8")); - httpPost.setEntity(se); - } catch (Exception e) { - log.error(e.getMessage()); - } - - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - } - - String result = null; - - //打印StatusLine - log.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - log.debug(result); - } catch (Exception e) { - log.error(e.getLocalizedMessage()); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - log.error(e.getLocalizedMessage()); - } - return result; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaParkService.java deleted file mode 100644 index 13796e4..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaParkService.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.iformall.service.park.impl.dahua; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.impl.BaseParkService; - -@Service -public class DaHuaParkService extends BaseParkService implements ParkAdapterService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return null; - } - - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return member.getId().toString(); - } - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - - } - - @Override - public ResultData carStopFee(Map paramMap, WxPark park) { - return dahuaCarStopFee(paramMap, park); - } - - private ResultData dahuaCarStopFee(Map paramMap, WxPark park) { - String carNumber = paramMap.get("carNumber"); - String result = DaHuaUtil.plateCharge(carNumber, park.getParkId()); - logger.info("大华查询车辆费用接口返回值:{}", result); - JSONObject jsonObject = JSONObject.parseObject(result); - String code = jsonObject.getString("code"); - if (!code.equals(DaHuaUtil.SUCCESS_CODE)) { - return new ResultData(ErrorCode.CAR_VENDOR_NOT_SUPPORT.getCode(), "停车费获取失败"); - } - Object data = jsonObject.get("data"); - return new ResultData(data); - } - - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) { - return new ResultData(); - } - - - @Override - public ResultData getParkStatus(WxPark park) { - return new ResultData(); - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaUtil.java deleted file mode 100644 index 0c293ac..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/dahua/DaHuaUtil.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.iformall.service.park.impl.dahua; - -import com.alibaba.fastjson.JSONObject; -import com.iformall.utils.AesUtils; -import com.iformall.utils.HttpUtil; - -import java.util.HashMap; -import java.util.Map; - -/** - * 大华 停车管理 - */ -public class DaHuaUtil { - - public static final String KEY = "8G5M4Ff9hel6fUA7"; - - public static final String IV = "g8v90drvOmIx1PuR"; - - public static final String URL = "http://47.106.104.196:8025/external/common"; - - public static final String SUCCESS_CODE = "0000"; - - public static String parkInfo(String appId) { - Map requestParams = new HashMap<>(); - requestParams.put("method", "parkInfo"); - return request(requestParams, appId); - } - - public static String plateCharge(String carNum, String appId) { - Map requestParams = new HashMap<>(); - Map data = new HashMap<>(); - data.put("carNum", carNum); - requestParams.put("data", data); - requestParams.put("method", "plateCharge"); - return request(requestParams, appId); - } - - public static String request(Map requestParams, String appId) { - String cipher = AesUtils.encryptCtrMode(JSONObject.toJSONString(requestParams), KEY, IV); - Map params = new HashMap<>(); - params.put("appId", appId); - params.put("cipher", cipher); - params.put("timestamp", System.currentTimeMillis()); - try { - //return HttpUtil.doPost(URL, JSONObject.toJSONString(params)); - return null; - } catch (Exception e) { - return null; - } - } - - -} - diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/etcp/ETCPUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/etcp/ETCPUtil.java deleted file mode 100644 index f25398a..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/etcp/ETCPUtil.java +++ /dev/null @@ -1,987 +0,0 @@ -package com.iformall.service.park.impl.etcp; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.exception.MallinkException; -import okhttp3.*; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.math.BigDecimal; -import java.security.MessageDigest; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -/** - * @Title: OpenapiCaller - * @Package: cn.etcp.openplatform.service - * @Description: ETCP开放平台接口调用示例 - * @author: zhiyong.fan - * @date: 2018/3/8 17:41 - * @version: V1.0 - */ -public class ETCPUtil { - - public static final String ETCP_PARK_ID = "parkId"; - public static final String ETCP_CAR_NUMBER = "plateNumber"; - public static final String ETCP_SYN_ID = "synId"; - public static final String ETCP_PARK_NAME = "parkName"; - public static final String ETCP_USER_TYPE = "userType"; - public static final String ETCP_ENTRANCE_TIME = "entranceTime"; - public static final String ETCP_FIX_PARKING_ID = "fixParkingId"; - public static final String ETCP_REMAINING_DAYS = "remainingDays"; - public static final String ETCP_EXIT_TIME = "exitTime"; - public static final String ETCP_STAYED_TIME = "stayedTime"; - public static final String ETCP_ORDER_ID = "orderId"; - public static final String ETCP_PAID_SERVICE_FEE = "paidServiceFee"; - public static final String ETCP_TIME = "time"; - public static final String ETCP_FEE = "fee"; - - private static final Logger logger = LoggerFactory.getLogger(ETCPUtil.class); - - /** - * 域名地址 - */ -// private static final String domain = "http://mapi.test.etcp.cn"; - private static final String domain = "http://mapi.etcp.cn"; - - // - private static final String appId = "FMLK"; - - private static final int payType = 5; - - /** - * 商户号 测试时请换成ETCP开放平台为商户平台分配的商户号 - */ -// private static final String merchantNo = "C7AEAF80BA8C44ADB42F3DB3CBC7D18A"; - private static final String merchantNo = "24E6DD2767F44F75A4AD916ECBFE4FA1"; - - /** - * 商户密钥 测试时请换成ETCP开放平台为商户平台分配的商户密钥 - */ -// private static final String merchantKey = "C292FFC7DCFB46AFB02792CD43F6DCC7"; - private static final String merchantKey = "B6751C6B37254C4390031F098738B5D9"; - - - /** - * 接口服务版本号 - */ - private static final String version = "1.0.0"; - - /** - * 6.1. 联合登录 - */ - private static final String userSigninUrl = "/merchant/open/{version}/openapi/usersigin"; - - /** - * 7.1. 车牌绑定 - */ - private static final String bindCarUrl = "/merchant/open/{version}/openapi/bindcar"; - - /** - * 7.2. 车牌解绑 - */ - private static final String unbindCarUrl = "/merchant/open/{version}/openapi/unbindcar"; - - /** - * 7.3. 车牌认证 - */ - private static final String carAuthUrl = "/merchant/open/{version}/openapi/carauth"; - - /** - * 7.4. 车牌找回 - */ - private static final String carRetrieveUrl = "/merchant/open/{version}/openapi/carretrieve"; - - /** - * 7.5. 已绑车辆信息查询 - */ - private static final String carNumUrl = "/merchant/open/{version}/openapi/carnum"; - - /** - * 8.1. 停车费查询 - */ - private static final String orderUnpayUrl = "/merchant/open/{version}/openapi/orderunpay"; - - /** - * 8.2. 优惠券查询 - */ - private static final String couponListUrl = "/merchant/open/{version}/openapi/couponlist"; - - /** - * 8.3. 历史停车查询 - */ - private static final String orderHistoryUrl = "/merchant/open/{version}/openapi/orderhistory"; - - /** - * 9.1. 主动支付(ETCP 收款) - */ - private static final String orderpayUrl = "/merchant/open/{version}/openapi/orderpay"; - - /** - * 9.2. 主动支付(商户平台收款) - */ - private static final String orderPaidUrl = "/merchant/open/{version}/openapi/orderpaid"; - - /** - * 10.1. 签约地址获取 - */ - private static final String signUrl = "/merchant/open/{version}/withhold/sign"; - - /** - * 10.2. 签约状态查询 - */ - private static final String statusUrl = "/merchant/open/{version}/withhold/status"; - - /** - * 11.1. 车场信息查询 - */ - private static final String parkingInfoUrl = "/merchant/open/{version}/openapi/surroundingparking"; - - /** - * 11.2. 车场状态查询 - */ - private static final String parkingStatusUrl = "/merchant/open/{version}/openapi/parkingstatus"; - - /** - * 12.1. 坏账查询 - */ - private static final String getDebtUrl = "/merchant/open/{version}/openapi/getdebt"; - - /** - * 12.2. 坏账清缴 - */ - private static final String repayDebtUrl = "/merchant/open/{version}/openapi/repaydebt"; - - /** - * 13.1. 商家优免券模板查询 - */ - private static final String bCouponListUrl = "/merchant/open/{version}/openapi/b/coupon/list"; - - /** - * 13.2. 商家优免券发放 - */ - private static final String bCouponRecordUrl = "/merchant/open/{version}/openapi/b/coupon/record"; - - /** - * 14.1. 车辆进出场模拟接口 - */ - private static final String bCarSimulationUrl = "/merchant/open/{version}/openapi/car/simulation"; - - private final OkHttpClient client = new OkHttpClient(); - - private DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); - - /** 错误码 - * 0 成功 - * 1 失败 - * 2 服务器异常 - * 3 时间戳超时 - * 4 签名校验非法 - * 5 没有找到商户密钥 - * 6 参数错误 - * 7 更新订单失败 - * 8 生产订单失败 - * 20100 操作失败 - * 20101 无效 token - * 20102 缺少必要参数 - * 20106 参数错误 - * 20201 手机号错误 - * 20202 获取验证码失败 - * 20203 手机验证码错误 - * 20206 支付金额与应付金额不匹配 - * 20207 60s 内只能发送一次验证码 - * 20208 APP 未有该权限 - * 20209 优惠金额与应付金额不匹配 - * 20301 签约失败 - * 20302 签约成功 - * 20401 无效车架号 - * 20407 车辆信息不匹配 - * 20408 操作失败,请稍后重试 - * 20501 操作失败,请稍后重试 - * 20602 returnUrl 为空 - * 20603 未查询到费用 - * 20604 请先清偿坏账 - * 20605 synId 错误 - * 20606 待支付费用为 0,无需支付 - * 20607 支付链接失效 - * 20608 查费失败 - * 20701 appId 错误 - * 20801 未绑定该车辆 - * 20802 该车辆已被他人绑定 - * 20803 绑定数量超限 - * 20804 30 天内最多绑定 4 辆不同的车 - * 20805 在场车辆不可解绑 - * 20901 车辆不在场 - * 20902 车场不支持电子支付 - * 20903 没有车场查费权限 - * 20904 用户未绑定该查费车牌 - * 20905 查询费用异常 - * 20906 用户不存在 - * 20907 商户未配置查费车场 - * 20908 长租车,费用为 0 - * 20909 车牌错误 - * 21001 查询失败 - * 21002 请稍后再试 - * 21003 未查询到坏账 - * 21004 错误支付类型 - * 21101 签约号已存在 - */ - - public static void main(String[] args) { - ETCPUtil caller = new ETCPUtil(); - String ret = ""; - JSONObject objret = null; - String etcpToken = "899e94d7-a3a5-46d4-87a3-288b18d0b189"; - String carNumber = "京D12345"; - String parkId = "Wj7YdvqyiYM="; - String businessId = "IgWGUtpAX68="; - String couponFreeId = "5627"; - - //caller.carSimulation(domain, appId, merchantNo, merchantKey, version, carNumber); - /* {"code":0,"message":"ok","data":{"isInPark":0}} */ - - //caller.getBCouponList(domain, merchantNo, merchantKey, version, parkId, businessId); - // {"code":0,"message":"查询成功","data":{"count":1,"couponPlatformModels":[{"id":5627,"parkId":"Wj7YdvqyiYM=","businessId":"IgWGUtpAX68=","businessName":"fmtest5678","name":"优免现金1元","category":"2","categoryValue":"1.00","amount":100,"status":"1","effectiveStart":"2018-08-20","effectiveEnd":"2018-08-25","couponType":"0","avaliavleNum":100}]}} - //caller.bCouponRecord(domain, merchantNo, merchantKey, version, etcpToken, parkId, businessId, carNumber, couponFreeId); - // 联合登录测试 - - //etcp 登陆 - ret = caller.userSignin(domain, appId, merchantNo, merchantKey, version, "13597837191"); - System.out.println(ret); - - objret = JSON.parseObject(ret); - if (objret.getIntValue("code") != 0) - return; - - etcpToken = objret.getJSONObject("data").getString("token"); - System.out.println(etcpToken); - - // 绑定的车牌查询 - ret = caller.carNum(domain, merchantNo, merchantKey, version, etcpToken); - System.out.println(ret); -// objret = JSON.parseObject(ret); -// if (objret.getIntValue("code") != 0) -// return; -// JSONObject data = objret.getJSONObject("data"); -// if (data.getIntValue("number") <= 0) { -// // 车牌绑定测试 -// ret = caller.bindCar(domain, etcpToken, carNumber, null, merchantNo, merchantKey, version); -// objret = JSON.parseObject(ret); -// if (objret.getIntValue("code") != 0) -// return; -// } -// JSONArray carArry = data.getJSONArray("carList"); -// carNumber = JSON.toJSONString(carArry.get(0)); -// carNumber = carNumber.substring(1, carNumber.length() -1); -// System.out.println(carNumber); -// // 停车费查询 -// ret = caller.orderUnpay(domain, appId, merchantNo, merchantKey, version, etcpToken, carNumber); -// System.out.println(ret); -// objret = JSON.parseObject(ret); -// if (objret.getIntValue("code") != 0) -// return; -// JSONArray payArr = objret.getJSONArray("data"); -// JSONObject payObj = payArr.getJSONObject(0); -// String orderId = payObj.getString("orderId"); -// // 微信h5支付 -// ret = caller.orderPay(domain, merchantNo, merchantKey, version, etcpToken, orderId, "http://test.cn", null); -// System.out.println(ret); - - // 车牌解绑测试 - //caller.unbindCar(merchantNo, merchantKey, version, etcpToken, carNumber); - - - //String orderId = "867C6F2F-4F3A-4767-890E-BA7F53F9C601"; - //caller.orderPay(etcpToken, 5, orderId, "test.cn", null); - - // 支付完成通知测试 - /*caller.orderPaid(etcpToken, "51C3E00A-4F87-43FB-A71B-C1287ED956CB", - "201803120000001", BigDecimal.valueOf(8.85), "2018-03-12 11:58:31", - "FSED9JvxgAU6XJUd8YRF5f7OuzyQ/lGJch0h8dVVkNaHUpPISCLBshnn0AIoEdIdi2aQMOrrcmdVz2Smy+UbQ8pXl95Mv50aPNnUgaDlxSDqHQ8iOD6FT5XV7ikozZ0800CJKDkvQrmCZS2O21G+xg==", - "ETCP");*/ - } - - public static int getPayType() { - return payType; - } - - private boolean checkRespFailed(String resp) { - if(resp.startsWith("") || resp.startsWith("")) { - return true; - } - return false; - } - - /** - * 6.1. 联合登录 - * - * @param appId appId(非空) - * @param merchantNo merchantNo(非空) - * @param merchantKey merchantKey(非空) - * @param version version(非空) - * @param mobilePhone 手机号(非空) - * @return 联合登录响应信息 - * { - * "code": 0, - * "data": { - * "token": "0b59582d-ea6f-4bf1-a570-e803cc24ebe0" - * }, - * "message": "ok" - * } - */ - public String userSignin(String baseUrl, String appId, String merchantNo, String merchantKey, String version, - String mobilePhone) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("appId", appId); - jsonObject.put("mobilePhone", mobilePhone); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + userSigninUrl.replaceAll("\\{version}", version), data, sign, - timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 7.1. 车牌绑定 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param plateNumber 车牌号(非空) - * @param plateColor 车牌颜色(可空) - * @return 绑牌响应信息 - * { - * "code": 0, - * "message": "ok" - * } - */ - public String bindCar(String baseUrl, String merchantNo, String merchantKey, String version, - String etcpToken, - String plateNumber, String plateColor) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("plateNumber", plateNumber); - if ("1".equals(plateColor) || "2".equals(plateColor) || "3".equals(plateColor) - || "4".equals(plateColor)) { - jsonObject.put("plateColor", plateColor); - } - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + bindCarUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 7.2. 车牌解绑 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param plateNumber 车牌号(非空) - * @return 车牌解绑响应信息 - * { - * "code": 0, - * "message": "ok" - * } - */ - public String unbindCar(String baseUrl, String merchantNo, String merchantKey, String version, - String etcpToken, - String plateNumber) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("plateNumber", plateNumber); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + unbindCarUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 7.3. 车牌认证 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param carFrameNum 车架号(非空) - * @param plateNumber 车牌号(非空) - * @param carEngineNum 发动机号(非空) - * @return 车牌解绑响应信息 - * { - * "code": 0, - * "message": "ok" - * } - */ - public String carAuth(String baseUrl, String merchantNo, String merchantKey, String version, - String etcpToken, - String carFrameNum, String plateNumber, String carEngineNum - ) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("carFrameNum", carFrameNum); - jsonObject.put("plateNumber", plateNumber); - jsonObject.put("carEngineNum", carEngineNum); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + carAuthUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 7.4. 车牌找回 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param carFrameNum 车架号(非空) - * @param plateNumber 车牌号(非空) - * @param carEngineNum 发机号(非空) - * @param plateColor 车牌颜色(1 蓝 2 黑 3 黄 4 白) - * @return 车牌找回响应信息 - * { - * "code": 0, - * "message": "ok" - * } - */ - public String carRetrieve(String baseUrl, String merchantNo, String merchantKey, String version, - String etcpToken, - String carFrameNum, String plateNumber, String carEngineNum, String plateColor ) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("carFrameNum", carFrameNum); - jsonObject.put("plateNumber", plateNumber); - jsonObject.put("carEngineNum", carEngineNum); - if (!StringUtils.isBlank(plateColor)) - jsonObject.put("plateColor", plateColor); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + carRetrieveUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 7.5. 已绑车辆信息查询 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @return 已绑车辆信息查询响应信息 - * { - * "code": 0, - * "msg": "ok", - * "data": { - * "number": 3, - * "carList": [ - * "晋 BMZ105", - * "云 C12345" - * ] - * } - * } - */ - public String carNum(String baseUrl, String merchantNo, String merchantKey, String version, - String etcpToken) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doGet(baseUrl + carNumUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 8.1. 停车费查询 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param plateNumber 车牌号(非空) - * @param appId appId(可空) - * @return 停车费查询响应信息 - */ - public String orderUnpay(String baseUrl, - String appId, String merchantNo, String merchantKey, String version, - String etcpToken, - String plateNumber) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("plateNumber", plateNumber); - if (appId != null && appId.length() > 0) { - jsonObject.put("appId", appId); - } - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doGet(baseUrl + orderUnpayUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 8.2. 优惠券查询 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @param lastCode 上一分页代码(可空) - * @param pageSize 1-200 之间的分页每页数量(非空) - * @return 停车费查询响应信息 - */ - public String couponList(String baseUrl, - String merchantNo, String merchantKey, String version, - String etcpToken, - String lastCode, String pageSize) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - if (!StringUtils.isBlank(lastCode)) - jsonObject.put("lastCode", lastCode); - jsonObject.put("pageSize", pageSize); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doGet(baseUrl + couponListUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 8.3.历史停车查询 - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin}) (非空) - * @return 停车费查询响应信息 - */ - public String orderHistory(String baseUrl, - String merchantNo, String merchantKey, String version, - String etcpToken) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doGet(baseUrl + orderHistoryUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 9.1. 主动支付(ETCP 收款) - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin})(非空) - * @param orderId 停车记录ID ({@link ETCPUtil#orderUnpay})(非空) - * @param returnUrl 外部支付流水号(商户平台生成)(非空) - * @param couponCode 支付金额 ({@link ETCPUtil#orderUnpay})(非空) - * @return - */ - public String orderPay(String baseUrl, - String merchantNo, String merchantKey, String version, - String etcpToken, String orderId, - String returnUrl, String couponCode) throws MallinkException { - // payType 支付方式(1 微信公众号内支付 2 支付宝 H5 支付 3 微信二维码 4 支付宝二维码 5 微信 H5)(非空) - int payType = 1; - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("payType", payType); - jsonObject.put("synId", orderId); - jsonObject.put("returnUrl", returnUrl); - if (couponCode != null && couponCode.length() > 0) { - jsonObject.put("couponCode", couponCode); - } - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + orderpayUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 9.2. 主动支付(商户平台收款) - * - * @param etcpToken 商户平台调用联合接口获取的token({@link ETCPUtil#userSignin})(非空) - * @param orderId 停车记录ID ({@link ETCPUtil#orderUnpay})(非空) - * @param externalOrderId 外部支付流水号(商户平台生成)(非空) - * @param payment 支付金额 ({@link ETCPUtil#orderUnpay})(非空) - * @param payTime 支付时间, 格式:yyyy-MM-dd HH:mm:ss(非空) - * @param verificationInfo 验证信息串 ({@link ETCPUtil#orderUnpay})(非空) - * @param appId appId(可空) - * @return - */ - public String orderPaid(String baseUrl, - String appId, String merchantNo, String merchantKey, String version, - String etcpToken, - String orderId, String externalOrderId, - BigDecimal payment, String payTime, String verificationInfo) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("orderId", orderId); - jsonObject.put("externalOrderId", externalOrderId); - jsonObject.put("payment", payment); - jsonObject.put("payTime", payTime); - jsonObject.put("verificationInfo", verificationInfo); - if (appId != null && appId.length() > 0) { - jsonObject.put("appId", appId); - } - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + orderPaidUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 11.1. 车场信息查询 - * - * @param lat, lon, radius - * @return 车场信息查询 - */ - public String parkingInfo(String baseUrl, - String merchantNo, String merchantKey, String version, - String lat, String lon, String radius) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("lat", lat); - jsonObject.put("lon", lon); - jsonObject.put("radius", radius); - jsonObject.put("payType", "1"); // 1:电子支付 - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + parkingInfoUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 11.2. 车场状态查询 - * - * @param parkingId 车场ID(非空) - * @return 车场状态查询响应信息 - */ - public String parkingStatus(String baseUrl, - String merchantNo, String merchantKey, String version, - String parkingId) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("parkingId", parkingId); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + parkingStatusUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)){ - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 12.1. 坏账查询 - * - * @param etcpToken - * @return 车场状态查询响应信息 - */ - public String getDebt(String baseUrl, - String appId, String merchantNo, String merchantKey, String version, - String etcpToken, String carNumber) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("appId", appId); - jsonObject.put("plateNumber", carNumber); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + parkingStatusUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 12.2. 坏账清缴 - * - * @param etcpToken - * @param - * @param returnUrl - * @return 车场状态查询响应信息 - */ - public String repayDebt(String baseUrl, - String merchantNo, String merchantKey, String version, - String etcpToken, String returnUrl) throws MallinkException { - // payType(1:支付宝 2:微信H5) - int payType = 2; - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("payType", payType); - jsonObject.put("returnUrl", returnUrl); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + parkingStatusUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 13.1. 商家优免券模板查询 - * - * @return 商家优免券模板查询结果 - */ - public String getBCouponList(String baseUrl, - String merchantNo, String merchantKey, String version, - String parkId, String businessId) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("parkId", parkId); - jsonObject.put("businessId", businessId); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + bCouponListUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 13.2. 商家优免券发放 - * - * @param etcpToken - * @return 商家优免券发放结果 - */ - public String bCouponRecord(String baseUrl, - String merchantNo, String merchantKey, String version, - String etcpToken, - String parkId, String businessId, String carNumber, String couponFreeId) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("token", etcpToken); - jsonObject.put("parkId", parkId); - jsonObject.put("businessId", businessId); - jsonObject.put("vehicleNo", carNumber); - jsonObject.put("couponFreeId", couponFreeId); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + bCouponRecordUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - /** - * 14.1. 车辆进出场模拟接口 - * - * @param appId, plateNumber - * @return 车场状态查询响应信息 - */ - public String carSimulation(String baseUrl, - String appId, String merchantNo, String merchantKey, String version, - String plateNumber) throws MallinkException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("appId", appId); - jsonObject.put("plateNumber", plateNumber); - - String data = jsonObject.toJSONString(); - String timeStamp = dateTimeFormatter.format(LocalDateTime.now()); - String sign = genSign(data, merchantKey, timeStamp); - - String respStr = doPost(baseUrl + bCarSimulationUrl.replaceAll("\\{version}", version), - data, sign, timeStamp, merchantNo); - if(respStr == null) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - if(checkRespFailed(respStr)) { - throw new MallinkException(ErrorCode.ETCP_CMD_FAIL); - } - return respStr; - } - - private String doPost(String url, String data, String sign, String timeStamp, String merchantNo) { - logger.info("请求url地址:{}, 请求参数为:data={}, sign={}, time_stamp={}, merchant_no={}", url, data, - sign, timeStamp, merchantNo); - RequestBody body = new FormBody.Builder().add("data", data).add("sign", sign) - .add("time_stamp", timeStamp).add("merchant_no", merchantNo).build(); - Request request = new Request.Builder().url(url).post(body).build(); - try (Response response = client.newCall(request).execute()) { - String responseStr = response.body().string(); - logger.info("post接口响应信息为:{}", responseStr); - return responseStr; - } catch (IOException e) { - logger.error(e.getMessage(),e); - } - return null; - } - - private String doGet(String sourceUrl, String data, String sign, String timeStamp, String merchantNo) { - logger.info("请求url地址:{}, 请求参数为:data={}, sign={}, time_stamp={}, merchant_no={}", sourceUrl, - data, sign, timeStamp, merchantNo); - HttpUrl url = HttpUrl.parse(sourceUrl).newBuilder().addQueryParameter("data", data) - .addQueryParameter("sign", sign).addQueryParameter("time_stamp", timeStamp) - .addQueryParameter("merchant_no", merchantNo).build(); - Request request = new Request.Builder().url(url).build(); - try (Response response = client.newCall(request).execute()) { - String responseStr = response.body().string(); - logger.info("get请求接口响应信息为:{}", responseStr); - return responseStr; - } catch (IOException e) { - logger.error(e.getMessage(),e); - } - return null; - } - - // 签名 - private String genSign(String param, String merchantKey, String time) { - String preparedString = new StringBuilder(param).append(merchantKey).append(time).toString(); - return md5Encode(preparedString.replaceAll("[ \r\t\n]", "")); - } - - private String md5Encode(String content) { - StringBuilder sb = new StringBuilder(); - try { - if (content == null || content.length() == 0) { - return null; - } - MessageDigest digestInstance = MessageDigest.getInstance("MD5"); - digestInstance.update(content.getBytes("UTF-8")); - byte[] md = digestInstance.digest(); - for (int i = 0; i < md.length; ++i) { - int val = md[i] & 0xff; - if (val < 16) { - sb.append("0"); - } - sb.append(Integer.toHexString(val)); - } - } catch (Exception ex) { - logger.error(ex.getMessage(),ex); - } - return sb.toString().toUpperCase(); - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/etcp/EtcpHelper.java b/suimangService/src/main/java/com/iformall/service/park/impl/etcp/EtcpHelper.java deleted file mode 100644 index c326a17..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/etcp/EtcpHelper.java +++ /dev/null @@ -1,488 +0,0 @@ -package com.iformall.service.park.impl.etcp; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.Result; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCUserCar; -import com.iformall.domain.po.WxCouponOrder; -import com.iformall.domain.po.WxMerchant; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.po.base.TenantEntity; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.domain.vo.WxMerchantVo; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumCouponOrderStatus; -import com.iformall.enums.EnumETCPCode; -import com.iformall.exception.MallinkException; -import com.iformall.service.WxCUserBasicInfoService; -import com.iformall.service.WxCUserCarService; -import com.iformall.service.WxCouponOrderService; -import com.iformall.service.WxMerchantService; -import com.iformall.service.park.impl.util.ParkHelper; - -@Service -public class EtcpHelper { - - private final Logger logger = LoggerFactory.getLogger(EtcpHelper.class); - - private ETCPUtil etcp = new ETCPUtil(); - - @Autowired - WxCUserBasicInfoService wxCUserBasicInfoService; - - @Autowired - WxCUserCarService wxCUserCarService; - - @Autowired - WxMerchantService wxMerchantService; - - @Autowired - WxCouponOrderService wxCouponOrderService; - - @Autowired - ParkHelper parkHelper; - - public ResultData initForEtcp(Map paramMap, Long userId, WxPark park) { - String phone = paramMap.get("phone"); - WxCUserBasicInfo user = wxCUserBasicInfoService.getById(userId,park.getFinalTenantId()); - if (null == user) { - logger.error("暂未成为会员,请授权手机号"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "暂未成为会员,请授权手机号"); - } - if (StringUtils.isBlank(phone) && StringUtils.isBlank(user.getPhone())) { - logger.error("暂未成为会员,请授权手机号"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "暂未成为会员,请授权手机号"); - } - if (!StringUtils.isBlank(user.getPhone()) && !user.getPhone().contains("*")) { - phone = user.getPhone(); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String appId = objParams.getString("appId"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - - String ret = ""; - try { - ret = etcp.userSignin(url, appId, merchantNo, merchantKey, version, phone); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == EnumETCPCode.SUCCESS.getCode()) { - // 获取绑定的车牌 - JSONObject dataObj = retObj.getJSONObject("data"); - dataObj.put("vendor", EnumCarVendor.CAR_ETCP.getCode()); - String etcpToken = dataObj.getString("token"); - try { - JSONObject dataObj1 = etcpSyncCarNumbers(park, user.getId(), park.getVendorType(), - url, merchantNo, merchantKey, version, - etcpToken); - } catch (MallinkException e) { - logger.error("ETCP cmd error: " + e.getMessage()); - } - // c端必须保存此token - return new ResultData(dataObj); - } else { - logger.error("共同登录失败: " + phone); - return new ResultData(ErrorCode.ETCP_LOGIN_FAIL.getCode(), "共同登录失败"); - } - } - - /** - * ETCP同步 - * - * @param tenantEntity - * @param cUserId - * @param iVendorType - * @param url - * @param merchantNo - * @param merchantKey - * @param version - * @param etcpToken - * @return - */ - private JSONObject etcpSyncCarNumbers(TenantEntity tenantEntity, Long cUserId, int iVendorType, - String url, String merchantNo, String merchantKey, String version, - String etcpToken) { - String ret; - JSONObject retObj; - /*{"code": 0,"msg": "ok","data": {"number": 3,"carList": ["晋 BMZ105","云 C12345"]}} */ - try { - ret = etcp.carNum(url, merchantNo, merchantKey, version, etcpToken); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - throw new MallinkException(e.getErrorCode(), e.getMessage()); - } - retObj = JSON.parseObject(ret); - JSONObject dataObj1 = retObj.getJSONObject("data"); - dataObj1.put("vendor", iVendorType); - JSONArray arr = dataObj1.getJSONArray("carList"); - WxCUserCar queryUserCar = new WxCUserCar(); - queryUserCar.setCUserId(cUserId); - List uclist = wxCUserCarService.getList(queryUserCar); - if(null != uclist ) { - List ucclist = new ArrayList(); - ucclist.addAll(uclist); - // 删除ETCP不存在 - for (WxCUserCar userCar : uclist) { - boolean bExist = isExistInArray(arr, userCar.getCarNumber()); - if (!bExist) { - wxCUserCarService.deleteById(userCar.getId()); - ucclist.remove(userCar); - } - } - // 添加ETCP的 - for (int i = 0; i < arr.size(); i++) { - String _carNum = arr.getString(i); - boolean bExist = isExistInList(ucclist, _carNum); - if (!bExist) { - Date curr = new Date(); - WxCUserCar userCar = new WxCUserCar(); - userCar.setCUserId(cUserId); - userCar.updateTenantInfo(tenantEntity); - userCar.setCarNumber(_carNum); - userCar.setVendorType(EnumCarVendor.CAR_ETCP.getCode()); - userCar.setCreateDate(curr); - userCar.setUpdateDate(curr); - wxCUserCarService.saveOrUpdate(userCar); - } - } - } - return dataObj1; - } - - private boolean isExistInArray(JSONArray arr, String carNumber) { - boolean bExist = false; - for (int i = 0; i < arr.size(); i++) { - // check carNum+cUserId是否存在, 不存在新建 - String _carNum = arr.getString(i); - - if (carNumber.equals(_carNum)) { - bExist = true; - break; - } - } - return bExist; - } - - private boolean isExistInList(List list, String carNumber) { - boolean bExist = false; - for (WxCUserCar userCar : list) { - if (carNumber.equals(userCar.getCarNumber())) { - bExist = true; - break; - } - } - return bExist; - } - - - public ResultData etcpBindCar(Map paramMap, WxPark park, Long cuUserId) { - String etcpToken = paramMap.get("etcpToken"); - if (StringUtils.isBlank(etcpToken)) { - logger.error("etcpToken为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "etcpToken为空"); - } - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - - String ret = ""; - try { - ret = etcp.bindCar(url, merchantNo, merchantKey, version, etcpToken, carNumber, null); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == 0) { - parkHelper.addCarInfoToDB(carNumber, EnumCarVendor.CAR_ETCP, park, cuUserId,"etcpUser"); - JSONObject dataObj = retObj.getJSONObject("data"); - return new ResultData(dataObj); - } else { - String message = retObj.getString("message"); - logger.error("绑车牌失败: " + carNumber); - return new ResultData(ErrorCode.ETCP_BIND_FAIL.getCode(), message, retObj); - } - } - - - public ResultData etcpUnbindCar(Map paramMap, WxPark park, Long cuUserId) { - String etcpToken = paramMap.get("etcpToken"); - if (StringUtils.isBlank(etcpToken)) { - logger.error("etcpToken为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "etcpToken为空"); - } - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - - String ret = ""; - try { - ret = etcp.unbindCar(url, merchantNo, merchantKey, version, etcpToken, carNumber); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == 0) { - try { - WxCUserCar userCar = new WxCUserCar(); - userCar.setCUserId(cuUserId); - userCar.updateTenantInfo(park); - userCar.setCarNumber(carNumber); - wxCUserCarService.deleteByObj(userCar); - } catch (Exception e) { - logger.error(e.getMessage()); - return new ResultData(ErrorCode.DB_FAIL.getCode(), "解绑车牌数据库错误, e:" + e.getMessage()); - } - - return new ResultData(); - } else { - String message = retObj.getString("message"); - logger.error("解绑车牌失败"); - return new ResultData(ErrorCode.ETCP_UNBIND_FAIL.getCode(), message, retObj); - } - } - - public ResultData etcpCarStopFee(@RequestBody Map paramMap, WxPark park) { - String etcpToken = paramMap.get("etcpToken"); - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(etcpToken)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "etcpToken为空"); - } - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String appId = objParams.getString("appId"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - - String ret = ""; - try { - ret = etcp.orderUnpay(url, appId, merchantNo, merchantKey, version, etcpToken, carNumber); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == 0) { - JSONObject feeObj = retObj.getJSONArray("data").getJSONObject(0); - /* - Date currentDate = new Date(); - WxCarCmdLog wxCarCmdLog = new WxCarCmdLog(); - wxCarCmdLog.setTenantId(user.getTenantId()); - wxCarCmdLog.setVendorType(EnumCarVendor.CAR_ETCP.getCode()); - wxCarCmdLog.setCmdType(EnumCarCmd.CAR_ETCP_CALLBACK_UNPAY.getCode()); - String feeStr = JSON.toJSONString(feeObj); - wxCarCmdLog.setCmdJson(feeStr); - wxCarCmdLog.setCreateDate(currentDate); - wxCarCmdLog.setUpdateDate(currentDate); - try { - wxCarCmdLogService.saveOrUpdate(wxCarCmdLog); - } catch (Exception e) { - logger.error("etcpOrderUnpay: 入库错误:" + feeStr); - return new ResultData(ErrorCode.DB_FAIL.getCode(), "入库错误", feeStr); - } - */ - return new ResultData(Result.SUCCESS, "停车费获取成功", feeObj); - } else { - String message = retObj.getString("message"); - return new ResultData(ErrorCode.ETCP_STOP_FEE_FAIL.getCode(), message, retObj); - } - } - - - private String getETCPBusinessID(Long merchantId) { - String businessId; - WxMerchant wxMerchant = wxMerchantService.getById(merchantId); - String carParams = wxMerchant.getCarParams(); - JSONObject objParams1 = JSON.parseObject(carParams); - businessId = objParams1.getString("businessId"); - return businessId; - } - - public ResultData getCoupon(Map paramMap,WxPark park,WxCouponOrderCarCVo userCar,String carNumber) { - String etcpToken = paramMap.get("etcpToken"); - if (StringUtils.isBlank(etcpToken)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "etcpToken为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - String businessId = ""; - // 获取merchantId - WxMerchantVo merchantVo = null; - if (null != userCar.getMerchantVoList() && userCar.getMerchantVoList().size() > 0) { - merchantVo = userCar.getMerchantVoList().get(0); - } - - // 优先从从商户表里取 - businessId = getETCPBusinessID(merchantVo.getId()); - if (StringUtils.isBlank(businessId)) { - // 1期只有一个虚拟商户,可以写在商场配置里 - businessId = objParams.getString("businessId"); - } - - String ret = ""; - try { - - String couponFreeId = couponFreeIdFromJson(userCar.getVendorParams()); - if (StringUtils.isBlank(couponFreeId)) { - return new ResultData(ErrorCode.DB_FAIL.getCode(), "vendorParams解析错误"); - } - ret = etcp.bCouponRecord(url, merchantNo, merchantKey, version, - etcpToken, park.getParkId(), businessId, carNumber, couponFreeId); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == EnumETCPCode.SUCCESS.getCode()) { - - try { - updateWxCouponOrderUsed(userCar, park); - return new ResultData(); - } catch (Exception e) { - return new ResultData(ErrorCode.DB_FAIL.getCode(), "券包状态更新失败"); - } - - } else { - return new ResultData(ErrorCode.ETCP_QUAN_SEND_FAIL.getCode(), retObj.getString("message")); - } - } - - private String couponFreeIdFromJson(String json) { - if (StringUtils.isBlank(json)) { - return null; - } - JSONObject object = JSON.parseObject(json); - if (null != object) { - Integer id = object.getInteger("id"); - if (null != id) { - return String.valueOf(id); - } - } - return null; - } - - public void updateWxCouponOrderUsed(WxCouponOrderCarCVo userCar,WxPark park) throws Exception { - // 券状态设为已使用 - WxCouponOrder couponOrder = new WxCouponOrder(); - couponOrder.setId(userCar.getId()); - couponOrder.updateTenantInfo(park); - couponOrder.setUpdateDate(new Date()); - couponOrder.setCouponOrderStatus(EnumCouponOrderStatus.COUPON_ORDER_USED.getCode()); - try { - wxCouponOrderService.saveOrUpdate(couponOrder); - } catch (Exception e) { - logger.error("券包状态更新失败:" + couponOrder.getId(),e); - throw new MallinkException(ErrorCode.DB_FAIL.getCode(), "券包状态更新失败"); - } - } - - - public ResultData etcpParkStatus(WxPark park) { - String params = park.getVendorParams(); - if (params == null) { - return new ResultData(ErrorCode.CAR_VENDOR_NOT_SUPPORT.getCode(), "车场不支持"); - } - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String merchantNo = objParams.getString("merchantNo"); - String merchantKey = objParams.getString("merchantKey"); - String version = objParams.getString("version"); - if (park.getParkingId() == null) { - // those code is not supported - /* - String lat = objParams.getString("lat"); - String lon = objParams.getString("lon"); - String radius = objParams.getString("radius"); - String ret = etcp.parkingInfo(url, merchantNo, merchantKey, version, lat, lon, radius); - logger.info(ret); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == EnumETCPCode.SUCCESS.getCode()) { - JSONObject retData = retObj.getJSONObject("data"); - if (retData != null) { - JSONArray retDataList = retData.getJSONArray("list"); - if (retDataList != null) { - JSONObject parkData = retDataList.getJSONObject(0); - if (parkData != null) { - String parkId = parkData.getString("id"); - objParams.put("parkId", parkId); - params = JSON.toJSONString(objParams); - park.setVendorParams(params); - park.setParkingId(parkId); - wxParkService.saveOrUpdate(park); - } - } - } - } - */ - } - - if (park.getParkingId() != null) { - String ret = ""; - try { - ret = etcp.parkingStatus(url, merchantNo, merchantKey, version, park.getParkingId()); - } catch (MallinkException e) { - logger.error("ETCP failed: " + e.getMessage()); - return new ResultData(e.getErrorCode(), e.getMessage()); - } - - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("code") == EnumETCPCode.SUCCESS.getCode()) { - if (retObj.get("data") != null) { - return new ResultData(retObj.getJSONObject("data")); - } - } - } - return null; - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkCallbackService.java b/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkCallbackService.java deleted file mode 100644 index 731f13a..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkCallbackService.java +++ /dev/null @@ -1,235 +0,0 @@ -package com.iformall.service.park.impl.haikangweishi; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.domain.po.WxCarJSOrder; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCarCYFVo; -import com.iformall.enums.EnumCarVendor; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.WxCarJSOrderMapper; -import com.iformall.service.WxParkService; -import com.iformall.service.park.ParkBatchCallBackAdapterService; -import com.iformall.service.park.ParkCallBackAdapterService; -import com.iformall.service.park.entity.ParkNotifyParam; -import com.iformall.service.park.impl.BaseParkService; - -import lombok.extern.slf4j.Slf4j; - - -/** - * 海康文档 3.1.8 - * @author alascor - * - */ -@Slf4j -@Service -public class HaiKangWeiShiParkCallbackService extends BaseParkService implements ParkBatchCallBackAdapterService { - - - @Autowired - HaiKangWeiShiParkService haiKangWeiShiParkService; - - @Autowired - WxParkService wxParkService; - - - /** - *{ - "method":"OnEventNotify", - "params":{ - "ability":"vehicle_pass_in_event", - "eventType":771760131, - "events":[ - { - "crossTime":"2021-07-01T17:29:27+08:00", - "crossType":1, - "eventIndexCode":"74b64514-4888-4f42-8cf7-22fed37d5dc8", - "eventType":3, - "resource":{ - "deviceId":"3715149265421676", - "deviceSerial":"R20150664", - "direction":0, - "entranceId":"2063867554789264", - "entranceName":"前门1", - "parkId":"2064637172217744", - "parkName":"车库", - "resType":"roadway", - "roadWayId":"2064272439342992", - "roadWayName":"前门入口" - }, - "stopType":11, - "vehicle":{ - "plateColor":12, - "plateNo":"苏A23658", - "plateType":8, - "vehicleColor":12, - "vehicleType":12 - } - } - ], - "sendTime":"2021-07-01T17:29:29.315+08:00" - } -} - */ - @Override - public List parseInNoticyParam(Object param) { - Map paramm = (Map) param; - Map params = (Map) paramm.get("params"); - if (null != params) { - List list = (List)params.get("events"); - if (null != list && list.size() > 0 ) { - List retList = new ArrayList(); - for (int i = 0 ; i < list.size() ; i ++) { - Map map = (Map) list.get(i); - ParkNotifyParam ret = parseInNoticyParamSingle(map); - if (null != ret ) { - retList.add(ret); - } - } - return retList; - } - } - return null; - } - - private ParkNotifyParam parseInNoticyParamSingle(Map paramMap) { - Map vehicle = (Map)paramMap.get("vehicle"); - Map resource = (Map)paramMap.get("resource"); - - String carNumber = vehicle.get("plateNo").toString(); - String parkCode = resource.get("parkId").toString(); - String parkName = resource.get("parkName").toString(); - - String synId = paramMap.get("eventIndexCode").toString(); - String entranceTime = paramMap.get("crossTime").toString(); - - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(carNumber); - p.setParkId(parkCode); - p.setParkName(parkName); - p.setSynId(synId); -// try { -// p.setEntranceTime(JieShunUtil.utcToLocal(entranceTime)); -// } catch (ParseException e) { -// log.error("jieshun entranceTime format error",e); -// return null; -// } - return p; - } - - - /** - * { - "method":"OnEventNotify", - "params":{ - "ability":"vehicle_pass_out_event", - "eventType":771760134, - "events":[ - { - "crossTime":"2021-07-01T17:31:17+08:00", - "crossType":1, - "eventIndexCode":"a5464f46-ba7b-4059-b657-5ebc2f3774a9", - "eventType":4, - "resource":{ - "deviceId":"370573791833424", - "deviceSerial":"9b1037b5-8a95-4657-81f0-edf27f71d92f", - "direction":1, - "entranceId":"2063867554789264", - "entranceName":"前门1", - "parkId":"2064637172217744", - "parkName":"车库", - "resType":"roadway", - "roadWayId":"2064664422217616", - "roadWayName":"前门出口test" - }, - "stopType":11, - "vehicle":{ - "plateColor":12, - "plateNo":"苏A23658", - "plateType":8, - "vehicleColor":12, - "vehicleType":12 - } - } - ], - "sendTime":"2021-07-01T17:31:17.337+08:00" - } -} - */ - @Override - public List parseOutNoticyParam(Object param) { - Map paramm = (Map) param; - Map params = (Map) paramm.get("params"); - if (null != params) { - List list = (List)params.get("events"); - if (null != list && list.size() > 0 ) { - List retList = new ArrayList(); - for (int i = 0 ; i < list.size() ; i ++) { - Map map = (Map) list.get(i); - ParkNotifyParam ret = parseOutNoticyParamSingle(map); - if (null != ret ) { - retList.add(ret); - } - } - return retList; - } - } - return null; - } - - - private ParkNotifyParam parseOutNoticyParamSingle(Map paramMap) { - Map vehicle = (Map)paramMap.get("vehicle"); - Map resource = (Map)paramMap.get("resource"); - - String carNumber = vehicle.get("plateNo").toString(); - String parkCode = resource.get("parkId").toString(); - String parkName = resource.get("parkName").toString(); - - String synId = paramMap.get("eventIndexCode").toString(); - String entranceTime = paramMap.get("crossTime").toString(); - - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(carNumber); - p.setParkId(parkCode); - p.setParkName(parkName); - p.setSynId(synId); -// try { -// p.setEntranceTime(JieShunUtil.utcToLocal(entranceTime)); -// } catch (ParseException e) { -// log.error("cyf entranceTime format error",e); -// return null; -// } -// try { -// p.setOutTime(JieShunUtil.utcToLocal(entranceTime)); -// } catch (ParseException e) { -// log.error("cyf outTime format error",e); -// return null; -// } - return p; - } - - @Override - public List parseUnbindNoticyParam(Object param) { - return null; - } - - @Override - public List parsePaidNoticyParam(Object param) { - return null; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkService.java deleted file mode 100644 index f335371..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiParkService.java +++ /dev/null @@ -1,250 +0,0 @@ -package com.iformall.service.park.impl.haikangweishi; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -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.Qualifier; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.common.Result; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCarJSOrder; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.domain.vo.WxParkCouponConfig; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.WxCarJSOrderMapper; -import com.iformall.service.WxParkService; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.entity.ParkStopFee; -import com.iformall.service.park.impl.BaseParkService; -import com.iformall.service.park.impl.util.ParkHelper; -import com.iformall.service.park.utils.ParkCacheUtils; -import com.iformall.utils.RedisCacheUtils; -import com.iformall.utils.RedisLock; - -/** - * 认证平台 https://www.hikyun.com 武汉富茂链客/zfy151431113 - * - * pms.hikyun.com 停车场管理云平台 账号sdw1112131,密码mcgc123456 - * https://open.hikyun.com/1/document/0 - - - @配置说明 - clientId,clientSecret 停车场管理系统控制台的。 - productCode: 停车场管理系统产品在云耀注册的id,固定。 - pmsName,pmsPassword : 停车场管理系统pms.hikyun.com 的账号密码 - projectId,ak : 停车场管理系统在云曜推送接口上创建的一个认证标识,联系 超云(开发)给提供 - * @author alascor - * - */ -@Service -public class HaiKangWeiShiParkService extends BaseParkService implements ParkAdapterService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ParkHelper parkHelper; - - @Autowired - @Qualifier("objectCommonRedisTemplate") - RedisTemplate redisTemplate; - - @Autowired - RedisLock redisLock; - - HaiKangWeiShiUtil haikang = new HaiKangWeiShiUtil(); - - - private String getCacheToken(WxPark park) { - String token = RedisCacheUtils.getCacheString(redisTemplate, "carStop:haikangtoken:"+park.getId()); - if (StringUtils.isBlank(token)) { - String lockKey = "carStop:haikangtokenlock:"+park.getTenantId(); - long time = System.currentTimeMillis() + 2000; - String timeStr = String.valueOf(time); - if (redisLock.lock2(lockKey, timeStr)) { - token = haikang.getToken(park); - if (!StringUtils.isBlank(token)) { - setCacheToken(park, token); - } - redisLock.unlock(lockKey, timeStr); - } else { - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - }finally { - redisLock.unlock(lockKey, timeStr); - } - } - } - return RedisCacheUtils.getCacheString(redisTemplate, "carStop:haikangtoken:"+park.getId()); - } - - private void setCacheToken(WxPark park,String token) { - RedisCacheUtils.cache(redisTemplate, "carStop:haikangtoken:"+park.getId(), token, 36000); - } - - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - Map retMap = new HashMap(); - try { - JSONObject retObj = haikang.subscription(park, getCacheToken(park),haikang.getAuthorization(park,getCacheToken(park))); - if (retObj.getString("code").equals("0")){ - return new ResultData(); - }else { - logger.error("haikangweishi parkInitConfig error. haikangResult: {}",retObj); - String msg = retObj.getString("msg"); - return new ResultData(retObj.getIntValue("code"), "当前海康威视停车场初始化配置失败:"+msg); - } - }catch(Exception e) { - return new ResultData(Result.ERROR, "当前海康威视停车场初始化配置失败:"+e.getMessage()); - } - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - return null; - } - - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - return "haikaiweishi"; - } - - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - } - - - /** - * 每一次查询都会产生订单,然后根据订单号查询 - */ - @Override - public ResultData carStopFee(Map paramMap, WxPark park) throws Exception{ - return haiKangWeiShiCarStopFee(paramMap, park); - } - - private ResultData haiKangWeiShiCarStopFee(Map paramMap, WxPark park) throws Exception{ - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - - //如果车牌号是鄂AAAAAA, 为测试车牌 - if (carNumber.equals("鄂AAAAAA")) { - return new ResultData(new ParkStopFee("-111",haikang.utcToLocal("2020-12-16 00:00:00"),haikang.utcToLocal("2020-12-17 00:00:00"), - "0.01","","payPath",null,"测试车牌,仅测试用",null)); - }else if(carNumber.equals("鄂AAAAAB")) { - return new ResultData(21000,"车辆未入场"); - } - - JSONObject attribute = haikang.getFee(park, carNumber, getCacheToken(park),haikang.getAuthorization(park,getCacheToken(park))); - - String appId = ""; - String parkOrderId = attribute.getString("id"); - String _createTime = attribute.getString("entranceTime");//计费时间,格式为“yyyy-MM-dd HH:mi:ss” - String _endTime = attribute.getString("costTime");//离场时间,格式为“yyyy-MM-dd HH:mi:ss” - String payPath = ""; - return new ResultData(new ParkStopFee(parkOrderId,haikang.utcToLocal(_createTime),haikang.utcToLocal(_endTime), - String.valueOf(attribute.getDouble("shouldCost")),appId,payPath,null,null,"0元请勿使用优惠券,无法退回。支付后15分钟内离场")); - } - - /** - * 使用3.5.9.1接口进行车牌和优惠信息绑定优惠券后,车辆出场时我们会自动抵扣。 - * @return - */ - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) throws Exception{ - if (null == userCar) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"当前用户未查询到优惠券!"); - } - - if (StringUtils.isBlank(userCar.getCUserPhone())) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"当前用户未查询到手机号!"+userCar.getcUserId()); - } - - Map valueMap = WxParkCouponConfig.parseValue(userCar.getVendorParams()); - if (null == valueMap) { - return new ResultData(ErrorCode.COUPON_IS_EMPTY.getCode(),"当前停车券没有关联停车场优惠券配置。"+coupon.getTitle()); - } - - String orderNo = paramMap.get("parkOrderId"); - String planNo = valueMap.get("couponNo"); - if (StringUtils.isBlank(planNo)) { - return new ResultData(ErrorCode.COUPON_IS_EMPTY.getCode(),"当前停车券没有关联停车场优惠券配置[ruleId]。"+coupon.getTitle()); - } - - //查询临停信息,判断缓存是否已经存在 - String inRecordSyscode = ""; - JSONObject stopInfo = haikang.getCarStopInfo(park, getCacheToken(park), haikang.getAuthorization(park,getCacheToken(park)), carNumber); - if (stopInfo.getString("code").equals("0")){ - JSONObject dataobject = stopInfo.getJSONObject("data"); - if (null == dataobject) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "当前未查询海康威视临停信息["+carNumber+"]"); - } - JSONArray listobject = dataobject.getJSONArray("list"); - if (null == listobject || listobject.size() <= 0 ) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "当前未查询海康威视临停信息["+carNumber+"]"); - } - JSONObject currentStopInfo = listobject.getJSONObject(0); - inRecordSyscode = currentStopInfo.getString("inRecordSyscode"); - if (StringUtils.isBlank(inRecordSyscode)) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "当前未查询海康威视临停信息["+carNumber+"]"); - } - - Integer used = RedisCacheUtils.getCacheInteger(redisTemplate, "carStop:haikangStopInfoUseCoupon:"+carNumber+":"+inRecordSyscode); - if (null == used || (null != used && used.intValue() < 1) ) { - //do nothing - }else { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "已经使用过优惠券, 不能重复使用."); - } - - }else { - logger.error("haikangweishi stopInfo error. paramMap: {} . haikangResult: {}",JSON.toJSONString(paramMap),stopInfo); - String msg = stopInfo.getString("msg"); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "当前查询海康威视临停信息失败:["+stopInfo.getString("code")+"]"+msg); - } - - - JSONObject retObj = haikang.useCoupon(park,planNo,carNumber,orderNo, getCacheToken(park),haikang.getAuthorization(park,getCacheToken(park))); - if (retObj.getString("code").equals("0")){ - RedisCacheUtils.cache(redisTemplate, "carStop:haikangStopInfoUseCoupon:"+carNumber+":"+inRecordSyscode, 1, 24*3600); - return new ResultData(); - }else { - logger.error("haikangweishi useCoupon error. paramMap: {} . haikangResult: {}",JSON.toJSONString(paramMap),retObj); - String msg = retObj.getString("msg"); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "当前用户领用到海康威视停车券失败:["+retObj.getString("code")+"]"+msg); - } - } - - @Override - public ResultData getParkStatus(WxPark park) throws Exception{ - return new ResultData(); - } - - @Override - public boolean ignoreUseCouponCache() { - return true; - } - - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiUtil.java deleted file mode 100644 index d836176..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/HaiKangWeiShiUtil.java +++ /dev/null @@ -1,464 +0,0 @@ -package com.iformall.service.park.impl.haikangweishi; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.domain.po.WxPark; -import com.iformall.exception.MallinkException; -import com.iformall.service.park.impl.haikangweishi.entity.ChallengeCode; -import com.iformall.utils.HashUtil; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.entity.mime.HttpMultipartMode; -import org.apache.http.entity.mime.MultipartEntity; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.entity.mime.content.StringBody; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * @author: furunxin - * @Date: 2020/7/1 17:16 - * @Description: 车易付接口对接参数类 - */ - -@Slf4j -public class HaiKangWeiShiUtil { - - public static final String TOKEN_URL = "https://open.hikyun.com/artemis/oauth/token"; - public static final String CHALLENGE_CODE = "https://open.hikyun.com/artemis/api/eits/v1/challengeCode"; - public static final String AUTHROZITAION = "https://open.hikyun.com/artemis/api/eits/v1/login"; - public static final String GET_FEE = "https://pmsopen.hikyun.com/artemis/api/pmsc/v1/pay/quickGetVehicleBill"; - public static final String COUPON_USE = "https://pmsopen.hikyun.com/artemis/api/pmsc/v1/coupon/addition"; - public static final String SUBSCRIPTION = "https://pmsopen.hikyun.com/artemis/api/pmsc/v1/sub/subscription"; - public static final String CAR_STOP_INFO = "https://pmsopen.hikyun.com/artemis/api/pmsc/v1/tempCarInRecords/page"; - - - /** - * @description UTC时间转化为本地时间 - * @Params [utcTime] - * @return java.util.Date - * @Author furunxin - * @Date 2020/7/8 下午12:45 - **/ - public static Date utcToLocal(String seconds) throws ParseException { - String format = "yyyy-MM-dd HH:mm:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(format); - Date date=sdf.parse(seconds); - return date; - } - - public static String getLocalDate(){ - LocalDateTime ldt = LocalDateTime.now(); - DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String nowDate = ldt.format(dtf); - return nowDate; - } - - public String getToken(WxPark wxPark) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - String clientId = vp.getString("clientId"); - String clientSecret = vp.getString("clientSecret"); - return getToken(clientId,clientSecret); - } - - private ChallengeCode getChallengeCode(WxPark wxPark,String accessToken) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map params = new HashMap(); - params.put("name", vp.getString("pmsName"));//pms.hikyun.com 的账号 - params.put("productCode", vp.getString("productCode")); - params.put("type", "1"); - String retCode = ProcBussiness(CHALLENGE_CODE, params,accessToken,null); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getChallengeCode error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang getChallengeCode error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("200") ) { - String message = result.getString("msg"); - throw new MallinkException(result.getInteger("code"), "haikang getChallengeCode error."+message); - } - JSONObject attribute = result.getJSONObject("data"); - if (null == attribute) { - throw new MallinkException(result.getInteger("code"), "haikang getChallengeCode error. no result"); - } - return new ChallengeCode(attribute.getString("pwdStatus"),attribute.getString("codeId"),attribute.getString("salt"),attribute.getString("vCode")); - } - - private static String entryPmsPassword(String password,String salt,String vCode) { - return HashUtil.sha256(HashUtil.sha256(password+salt)+vCode); - } - - //使用后不能再次使用,并且有很短的过期时间 - public String getAuthorization(WxPark wxPark,String accessToken) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - ChallengeCode challengeCode = getChallengeCode(wxPark,accessToken); - Map params = new HashMap(); - params.put("name", vp.getString("pmsName"));//pms.hikyun.com 的账号 - params.put("productCode", vp.getString("productCode")); - params.put("type", "1"); - params.put("codeId", challengeCode.getCodeId()); - params.put("password", entryPmsPassword(vp.getString("pmsPassword"),challengeCode.getSalt(),challengeCode.getVCode())); - String retCode = ProcBussiness(AUTHROZITAION, params,accessToken,null); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getAuthorization error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang getAuthorization error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("200") ) { - String message = result.getString("msg"); - throw new MallinkException(result.getInteger("code"), "haikang getAuthorization error."+message); - } - JSONObject attribute = result.getJSONObject("data"); - if (null == attribute) { - throw new MallinkException(result.getInteger("code"), "haikang getAuthorization error. no result"); - } - return attribute.getString("Authorization"); - - } - - private String getToken(String clientId,String clientSecret) { - String result = ProcLogin(clientId, clientSecret); - if (StringUtils.isBlank(result)) { - return null; - } - JSONObject res = JSON.parseObject(result); - Integer errStatus = res.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang access_token error.["+res.getString("error")+"]"+res.getString("message")); - } - - String accessToken = res.getString("access_token"); - if (null != accessToken ) { - return accessToken; - }else { - throw new MallinkException(500,"haikang access_token error.["+res.getString("error")+"]"+res.getString("error_description")); - } - } - - /** - * 查询停车费 3.5.5 快速获取账单接口 - * @return - */ - public JSONObject getFee(WxPark wxPark,String carNumber,String token,String Authrozitaion) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map params = new HashMap(); - params.put("chargeSource", "THIRD");//商户编号 - params.put("parkId", wxPark.getParkingId()); - params.put("plateNo", carNumber); - String retCode= ProcBussiness(GET_FEE, params, token,Authrozitaion); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getFee error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang getFee error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("0") ) { - String message = result.getString("msg"); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getFee error.["+result.getString("code")+"]"+message); - } - JSONObject attribute = result.getJSONObject("data"); - if (null == attribute) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getFee error. no result ["+result.getInteger("code")+"]"+carNumber); - } - return attribute; - } - - - /** - * 3.5.7 查询停车信息 - * - * "inRecordSyscode": "h45h45h45ghhn45tg245g45r", - "parkId": "6534543543554", - "parkName": "停车库 1", - "plateNo": "浙 A12345", - "plateNoPicId": "hj53h4h45t45t45t3t234t2t2t45t45t", - "vehiclePicId": "u65h45g45yh56y54y34y34y345y3" - "inTime": "2018-07-26T15:00:00+08:00", - "parkTime": "3 小时 10 分钟" - */ - public JSONObject getCarStopInfo(WxPark wxPark,String token,String Authrozitaion,String carNumber) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map params = new HashMap(); - params.put("pageNo", 1); - params.put("pageSize", 1); - params.put("parkId", wxPark.getParkingId());//商户编号 - params.put("plateNo", carNumber); - String retCode = ProcBussiness(CAR_STOP_INFO, params,token,Authrozitaion); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang getCarStopInfo error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang getCarStopInfo error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("0") ) { - String message = result.getString("msg"); - throw new MallinkException(result.getInteger("code"), "haikang getCarStopInfo error."+message); - } - return result; - } - - /** - * 2、有优惠券方式 - 发优惠券的时候是会返回一个优惠券id(3.5.9.1), - 在用户出场的时候,获取停车账单(3.5.3), - 使用停车账单和优惠券id获取优惠账单(3.5.4), - 调用账单支付确认接口(3.5.6); - 完成一次优惠缴费 - * 使用优惠券 3.5.9.1接口进行车牌和优惠信息绑定优惠券后,车辆出场时会自动抵扣 - **/ - public JSONObject useCoupon(WxPark wxPark,String couponNo,String carNumber,String orderNo,String token,String Authrozitaion){ - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - - Map params = new HashMap(); - Map couponmap = new HashMap(); - couponmap.put("plateNo", carNumber); - couponmap.put("ruleId", couponNo); - List coupons = new ArrayList(); - coupons.add(couponmap); - params.put("coupons", coupons);//商户编号 - String retCode = ProcBussiness(COUPON_USE, params,token,Authrozitaion); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang useCoupon error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang useCoupon error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("0") ) { - String message = result.getString("msg"); - throw new MallinkException(result.getInteger("code"), "haikang useCoupon error."+message); - } - return result; - } - - /** - * 消息订阅 3.1.8 - * * 这个接口需要你们实现的时候规定下: -1、POST格式, -2、接口返回参数JSON格式:{errcode:0, errmsg: "success",data:null} -3、接口建议接收到过车事件,立即返回接收成功 - -我这边根据这个 0 状态来判断你们是否接收成功,如果没成功,我这边会重发3次的 - * - * @param clientId - * @param clientSecret - * @return - */ - public JSONObject subscription(WxPark wxPark,String token,String Authrozitaion){ - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map params = new HashMap(); - params.put("partnerAppKey", vp.getString("ak"));//商户编号 - params.put("projectId", vp.getString("projectId")); - params.put("eventTypes", new Integer[] {771760131,771760134}); - params.put("subUrl", vp.getString("subUrl")); - String retCode = ProcBussiness(SUBSCRIPTION, params,token,Authrozitaion); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "haikang subscription error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - - Integer errStatus = result.getInteger("status"); - if (null != errStatus) { - throw new MallinkException(errStatus,"haikang subscription error.["+result.getString("error")+"]"+result.getString("message")); - } - - if (!result.getString("code").equals("0") ) { - String message = result.getString("msg"); - throw new MallinkException(result.getInteger("code"), "haikang subscription error."+message); - } - return result; - } - - /*token认证登陆**/ - private static String ProcLogin(String clientId,String clientSecret) { - ArrayList list = new ArrayList(); - list.add(new BasicNameValuePair("client_id", clientId)); - list.add(new BasicNameValuePair("client_secret", clientSecret)); - return formData(TOKEN_URL,list,null,null); - } - - - - private static String ProcBussiness(String url,Map list,String token,String authorization) { - try { - return Proc(url,list,token,authorization); - } catch (Exception e) { - log.error("haikang request error.",e); - } - return null; - } - - private static String Proc(String url, Map pairs,String token,String authorization) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); - if (!StringUtils.isBlank(token)) { - httpPost.addHeader("access_token",token); - } - if (!StringUtils.isBlank(authorization)) { - httpPost.addHeader("Authorization",authorization); - } - - if (null != pairs) { - try { - StringEntity entity = new StringEntity(JSON.toJSONString(pairs),"UTF-8"); - entity.setContentType("application/json"); - httpPost.setEntity(entity); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - } - - long currentTime = System.currentTimeMillis(); - StringBuffer requestlog = new StringBuffer(); - if (null != pairs) { - log.info("haikangweishi httpRequest:[url]"+url+"[params]"+JSON.toJSONString(pairs)); - requestlog.append("haikangweishi httpRequest:[url]").append(url).append("[params]").append(JSON.toJSONString(pairs)); - }else { - log.info("haikangweishi httpRequest:[url]"+url); - requestlog.append("haikangweishi httpRequest:[url]").append(url); - } - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - long responseCostTime = System.currentTimeMillis()-currentTime; - String result = null; - - //打印StatusLine - log.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - requestlog.append("[response]").append(result).append("[costTime(ms)]").append(responseCostTime); - log.debug(requestlog.toString()); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - log.error(e.getLocalizedMessage()); - } - return result; - } - - private static String formData(String url,List pairs,String token,String authorization) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost(url); - if (!StringUtils.isBlank(token)) { - httpPost.addHeader("access_token",token); - } - if (!StringUtils.isBlank(authorization)) { - httpPost.addHeader("Authorization",authorization); - } - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - if (null != pairs) { - for (NameValuePair nvp : pairs) { - builder.addPart(nvp.getName(), new StringBody(nvp.getValue(),ContentType.TEXT_PLAIN)); - } - } - HttpEntity entity = builder.build(); - httpPost.setEntity(entity); - long currentTime = System.currentTimeMillis(); - StringBuffer requestlog = new StringBuffer(); - if (null != pairs) { - log.info("haikangweishi httpRequest start :[url]"+url+"[params]"+JSON.toJSONString(pairs)); - requestlog.append("haikangweishi httpRequest:[url]").append(url).append("[params]").append(JSON.toJSONString(pairs)); - }else { - log.info("haikangweishi httpRequest start :[url]"+url); - requestlog.append("haikangweishi httpRequest:[url]").append(url); - } - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - long responseCostTime = System.currentTimeMillis()-currentTime; - String result = null; - - //打印StatusLine - log.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - requestlog.append("[response]").append(result).append("[costTime(ms)]").append(responseCostTime); - log.debug(requestlog.toString()); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - log.error(e.getLocalizedMessage()); - } - - return result; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/entity/ChallengeCode.java b/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/entity/ChallengeCode.java deleted file mode 100644 index a36022e..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/haikangweishi/entity/ChallengeCode.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.iformall.service.park.impl.haikangweishi.entity; - -import lombok.AllArgsConstructor; -import lombok.Data; - -@Data -@AllArgsConstructor -public class ChallengeCode { - - private String pwdStatus; - private String codeId; - private String salt; - private String vCode; - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkCallbackService.java b/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkCallbackService.java deleted file mode 100644 index ab53e3c..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkCallbackService.java +++ /dev/null @@ -1,190 +0,0 @@ -package com.iformall.service.park.impl.jieshun; - -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.domain.po.WxCarJSOrder; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCarCYFVo; -import com.iformall.enums.EnumCarVendor; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.WxCarJSOrderMapper; -import com.iformall.service.WxParkService; -import com.iformall.service.park.ParkBatchCallBackAdapterService; -import com.iformall.service.park.ParkCallBackAdapterService; -import com.iformall.service.park.entity.ParkNotifyParam; -import com.iformall.service.park.impl.BaseParkService; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -@Service -public class JieShunParkCallbackService extends BaseParkService implements ParkBatchCallBackAdapterService { - - - @Autowired - JieShunParkService jieshunParkService; - - @Autowired - WxParkService wxParkService; - - @Autowired - WxCarJSOrderMapper wxCarJSOrderMapper; - - private String handleCarNumber(String carNumber) { - if (StringUtils.isBlank(carNumber)) { - return "空车牌"; - } - if (carNumber.contains("-")) { - carNumber = carNumber.replaceAll("-", ""); - } - return carNumber; - } - - /** - * {dataItems=[{"inTime":"2020-12-09 11:21:15","carNumber":"浙-AF81797","inCarPhoto":"p201127315/NISSP_IMG_PARK_IN/20201209/a9f1130651b9493f8eab64f14afbdd47","isReal":0,"itemId":"a9f1130651b9493f8eab64f14afbdd47","inOperator":"超级管理员","equipName":"东门入口","parkName":"杭州东站西子国际","vehicleInfo":"{\"plateNo\":\"浙-AF81797\",\"plateColor\":\"GREEN\",\"plateBackColor\":0,\"plateWordColor\":0,\"vehicleColor\":null,\"vehicleLogo\":null,\"vehicleModel\":null,\"mainModel\":0,\"subModel\":0,\"vehicleModelTrust\":0,\"mainModelTrust\":0,\"subModelTrust\":0,\"plateNoTrust\":1,\"vehicleLogoTrust\":0,\"vehicleColorTrust\":0}","equipCode":"208202496","parkCode":"p201127315"}], pno=dzxzgj, sn=6C958D99D2769AA16F3A3F06E962263F, tn=-2, ts=20201209112118886, ve=1.0} - */ - @Override - public List parseInNoticyParam(Object param) { - Map paramm = (Map) param; - String liststr = (String) paramm.get("dataItems"); - JSONArray list = JSONArray.parseArray(liststr); - if (null != list && list.size() > 0 ) { - List retList = new ArrayList(); - for (int i = 0 ; i < list.size() ; i ++) { - Map map = (Map) list.get(i); - ParkNotifyParam ret = parseInNoticyParamSingle(map); - if (null != ret ) { - retList.add(ret); - } - } - return retList; - } - return null; - } - - private ParkNotifyParam parseInNoticyParamSingle(Map paramMap) { - String carNumber = paramMap.get("carNumber").toString(); - String parkCode = paramMap.get("parkCode").toString(); - String parkName = paramMap.get("parkName").toString(); - - String synId = paramMap.get("itemId").toString(); - String entranceTime = paramMap.get("inTime").toString(); - - ParkNotifyParam p = new ParkNotifyParam(); - String realCarNumber = handleCarNumber(carNumber); - p.setCarNumber(realCarNumber); - p.setParkId(parkCode); - p.setParkName(parkName); - p.setSynId(synId); - try { - p.setEntranceTime(JieShunUtil.utcToLocal(entranceTime)); - } catch (ParseException e) { - log.error("jieshun entranceTime format error",e); - return null; - } - return p; - } - - @Override - public List parseOutNoticyParam(Object param) { - Map paramm = (Map) param; - String liststr = (String) paramm.get("dataItems"); - JSONArray list = JSONArray.parseArray(liststr); - if (null != list && list.size() > 0 ) { - List retList = new ArrayList(); - for (int i = 0 ; i < list.size() ; i ++) { - Map map = (Map) list.get(i); - ParkNotifyParam ret = parseOutNoticyParamSingle(map); - if (null != ret ) { - retList.add(ret); - } - } - return retList; - } - return null; - } - - - private ParkNotifyParam parseOutNoticyParamSingle(Map paramMap) { - String carNumber = paramMap.get("carNumber").toString(); - String parkCode = paramMap.get("parkCode").toString(); - String parkName = paramMap.get("parkName").toString(); - - String synId = paramMap.get("itemId").toString(); - String entranceTime = paramMap.get("outTime").toString(); - - String realCarNumber = handleCarNumber(carNumber); - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(realCarNumber); - p.setParkId(parkCode); - p.setParkName(parkName); - p.setSynId(synId); - try { - p.setEntranceTime(JieShunUtil.utcToLocal(entranceTime)); - } catch (ParseException e) { - log.error("cyf entranceTime format error",e); - return null; - } - try { - p.setOutTime(JieShunUtil.utcToLocal(entranceTime)); - } catch (ParseException e) { - log.error("cyf outTime format error",e); - return null; - } - p.setFee(String.valueOf(paramMap.get("ssMoney"))); - return p; - } - - @Override - public List parseUnbindNoticyParam(Object param) { - return null; - } - - @Override - public List parsePaidNoticyParam(Object param) { - Map paramm = (Map) param; - String liststr = (String) paramm.get("dataItems"); - JSONArray list = JSONArray.parseArray(liststr); - if (null != list && list.size() > 0 ) { - List retList = new ArrayList(); - for (int i = 0 ; i < list.size() ; i ++) { - Map map = (Map) list.get(i); - ParkNotifyParam ret = parsePaidNoticyParamSingle(map); - if (null != ret ) { - retList.add(ret); - } - } - return retList; - } - return null; - } - - JieShunUtil jieshun = new JieShunUtil(); - private ParkNotifyParam parsePaidNoticyParamSingle(Map vo) { - ParkNotifyParam p = new ParkNotifyParam(); - p.setCarNumber(handleCarNumber((String) vo.get("carNumber"))); - p.setParkId(String.valueOf(vo.get("parkCode"))); - p.setParkOrderId((String) vo.get("itemId")); - p.setSynId((String) vo.get("itemId")); - p.setFee(vo.get("ssMoney").toString()); - try { - p.setPayTime(jieshun.utcToLocal((String)vo.get("feesTime"))); - } catch (ParseException e) { - e.printStackTrace(); - } - return p; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkService.java deleted file mode 100644 index 9e38e40..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunParkService.java +++ /dev/null @@ -1,359 +0,0 @@ -package com.iformall.service.park.impl.jieshun; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -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.Qualifier; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.IdWorker; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCarJSOrder; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.domain.vo.WxParkCouponConfig; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.exception.MallinkException; -import com.iformall.mapper.WxCarJSOrderMapper; -import com.iformall.service.WxParkService; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.entity.ParkStopFee; -import com.iformall.service.park.impl.BaseParkService; -import com.iformall.service.park.impl.util.ParkHelper; -import com.iformall.service.park.utils.ParkCacheUtils; -import com.iformall.utils.RedisCacheUtils; -import com.iformall.utils.RedisLock; - -/** - * 跳转捷停车小程序参数:(生产环境) - appid:wx24b70f0ad2a9a89a - - 1>小程序首页 - path:pages/index/index - - 2>小程序订单页(车牌+车场编号 ) path: pages/thirdPayOrder/payOrder?carNo=车牌&parkCode=车场编号 - - 3>小程序订单页(订单编号) path: pages/thirdPayOrderByNo/payOrder?orderNo=订单编号 - -* 捷顺商户平台:http://merchant.jslife.com.cn/merchant/index.html#/auth/login -* 捷顺门店平台:http://merchant.jslife.com.cn/store/index.html#/auth/login - * wxParK配置: - * { - * "cid": "000000008032172", //获取token cid. [http://www.jslife.com.cn/jsaims/login] - * "psw": "000000008032172", //获取token pwd. [http://www.jslife.com.cn/jsaims/login] - * "usr": "000000008032172", //获取token usr. [http://www.jslife.com.cn/jsaims/login] - * "signkey": "71f1a4ab8c544379a192e1bf1b7e7d9e", //加密key - * "version": "2", //加密version - * "parkCode": "p201127315", //停车场编号 - * "loginUser": "000000008032172000003", //捷顺门店平台登录账号 - * "loginPassword": "ycHqp61Acudxz", //捷顺门店平台登录密码 - * "businesserCode": "000000008032172" //捷顺商户编号 - * } - - * @author alascor - * - */ -@Service -public class JieShunParkService extends BaseParkService implements ParkAdapterService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ParkHelper parkHelper; - - @Autowired - @Qualifier("objectCommonRedisTemplate") - RedisTemplate redisTemplate; - - @Autowired - RedisLock redisLock; - - @Autowired - WxCarJSOrderMapper wxCarJSOrderMapper; - - - JieShunUtil jieshun = new JieShunUtil(); - - - private String getCacheToken(WxPark park) { - String token = RedisCacheUtils.getCacheString(redisTemplate, "carStop:jieshuntoken:"+park.getId()); - if (StringUtils.isBlank(token)) { - String lockKey = "carStop:jieshuntokenlock:"+park.getTenantId(); - long time = System.currentTimeMillis() + 2000; - String timeStr = String.valueOf(time); - if (redisLock.lock2(lockKey, timeStr)) { - token = jieshun.getToken(park); - if (!StringUtils.isBlank(token)) { - setCacheToken(park, token); - } - redisLock.unlock(lockKey, timeStr); - } else { - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - }finally { - redisLock.unlock(lockKey, timeStr); - } - } - } - return RedisCacheUtils.getCacheString(redisTemplate, "carStop:jieshuntoken:"+park.getId()); - } - - private void setCacheToken(WxPark park,String token) { - RedisCacheUtils.cache(redisTemplate, "carStop:jieshuntoken:"+park.getId(), token, 3600); - } - - /** - * 先去捷顺注册,调用登陆获取令牌,然后根据令牌调用别的接口 - * http://ap.jieshun.cn:9088/apply/ 注册信息地址 fumao/iformall2020 - * - * 捷顺商户平台:http://merchant.jslife.com.cn/merchant/index.html#/auth/login - * 捷顺门店平台:http://merchant.jslife.com.cn/store/index.html#/auth/login - * 门店商户号 000000008032172000003 密码 ycHqp61Acudxz - * - * - * API对接注意事项: - 1、token有效期两个小时,每两小时内登录一次获取token,调业务接口不需要频繁登录用,建议获取一次token存本地缓存,之后从本地获取,两小时内刷新一次, - 为避免调业务接口时刚好token被刷新,导致token失效(无效的令牌或令牌已过期),可以做下容错,重新登录获取token或用最新token重新调业务接口。 - 2、token是和ip是一对一绑定,新的ip服务器调捷顺的接口会出现ip不合法,需把ip提供捷顺方,添加白名单。多个服务调捷顺接口共用一个ip情况下,只能共用一套登录获取token机制,各自登录会冲突。 - 3、所有接口要带车牌的一律带横杠。格式如:粤-B12345。 - 4、无效的数据签名是指sn加密方式不对。sn加密方式是对p+signkey进行Md5加密,加密后的字符串大写。 - */ - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - return null; - } - - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - return "jieshun"; - } - - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) throws Exception{ - } - - - /** - * 每一次查询都会产生订单,然后根据订单号查询 - */ - @Override - public ResultData carStopFee(Map paramMap, WxPark park) throws Exception{ - return jieshunCarStopFee(paramMap, park); - } - - private ResultData jieshunCarStopFee(Map paramMap, WxPark park) throws Exception{ - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - - //如果车牌号是鄂AAAAAA, 为测试车牌 - if (carNumber.equals("鄂AAAAAA")) { - return new ResultData(new ParkStopFee("-111",jieshun.utcToLocal("2020-12-16 00:00:00"),jieshun.utcToLocal("2020-12-17 00:00:00"), - "0.01","wx24b70f0ad2a9a89a","payPath",null,"测试车牌,仅测试用",null)); - }else if(carNumber.equals("鄂AAAAAB")) { - return new ResultData(21000,"车辆未入场"); - } - - //下订单; - String retCode = jieshun.createOrder(park, carNumber, getCacheToken(park)); - if (StringUtils.isBlank(retCode)) { - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(), "jieshun createOrder error. has no result"); - } - JSONObject result = JSON.parseObject(retCode); - if (result.getInteger("resultCode") != 0 ) { - String message = result.getString("message"); - throw new MallinkException(result.getInteger("resultCode"), "jieshun createOrder error."+message); - } - JSONArray arrays = result.getJSONArray("dataItems"); - if (null == arrays || arrays.size() == 0) { - throw new MallinkException(result.getInteger("resultCode"), "jieshun createOrder error. no order result"+carNumber); - } - JSONObject attribute = arrays.getJSONObject(0).getJSONObject("attributes"); - Double totalFee = attribute.getDouble("totalFee"); - String appId = "wx24b70f0ad2a9a89a"; - String parkOrderId = attribute.getString("orderNo"); - if (totalFee <= 0 ) { - String _createTime = attribute.getString("startTime");//计费时间,格式为“yyyy-MM-dd HH:mi:ss” - String _endTime = attribute.getString("endTime");//离场时间,格式为“yyyy-MM-dd HH:mi:ss” - String msg = attribute.getString("retmsg"); - if (!StringUtils.isBlank(msg)) { - if (msg.contains("未入场")) { - return new ResultData(new ParkStopFee(null,jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), - "0.00",appId,"payPath",null,msg,null)); - }else { - //0元订单结清,查询是否用过打折方案,如果用过,则需要调用接口结清订单 - Integer used = ParkCacheUtils.getCarCouponUseCacheLock(redisTemplate, EnumCarVendor.CAR_JIESHUN.getMessage(), carNumber); - if (null == used || (null != used && used.intValue() < 1)) { - //未使用停车券 - return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), - "0.00",appId,"payPath",null,msg,null)); - }else { - return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), - "0.00",appId,"payPath",null,msg,"用券抵扣后账单为0,获得15分钟免费出场时间")); -// String notifyResult = jieshun.notifyOrderResult(park, parkOrderId, getCacheToken(park)); -// JSONObject notiryRetObj = JSON.parseObject(notifyResult); -// String noticeErrorMsg = notiryRetObj.getString("message"); -// if (notiryRetObj.getIntValue("resultCode") == 0){ -// JSONArray notiryRetArrays = notiryRetObj.getJSONArray("dataItems"); -// if (null != notiryRetArrays && notiryRetArrays.size() == 0 ) { -// JSONObject notifyRetObject = notiryRetArrays.getJSONObject(0).getJSONObject("attributes"); -// if(notifyRetObject.getIntValue("retCode") == 0) { -// return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), -// "0.00",appId,"payPath",null,msg,"用券抵扣后账单为0,获得15分钟免费出场时间")); -// }else { -// return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), -// "0.00",appId,"payPath",null,msg,"用券抵扣后账单为0,但是结清订单失败["+noticeErrorMsg+"],无免费出场时间,请下拉刷新")); -// } -// }else { -// return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), -// "0.00",appId,"payPath",null,msg,"用券抵扣后账单为0,但是结清订单失败["+noticeErrorMsg+"],无免费出场时间,请下拉刷新")); -// } -// }else { -// return new ResultData(new ParkStopFee("-999",jieshun.utcToLocal(_createTime),jieshun.utcToLocal(_endTime), -// "0.00",appId,"payPath",null,msg,"用券抵扣后账单为0,但是结清订单失败["+noticeErrorMsg+"],无免费出场时间,请下拉刷新")); -// } - } - } - } - } - - - String ret = jieshun.getCarStopFee(park, parkOrderId, getCacheToken(park)); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("resultCode") == 0){ - JSONArray retArrays = retObj.getJSONArray("dataItems"); - if (null == retArrays || retArrays.size() == 0 ) { - throw new MallinkException(result.getInteger("resultCode"), "jieshun getCarStopFee error. no order result"+carNumber); - } - - JSONObject retObject = retArrays.getJSONObject(0).getJSONObject("attributes"); - String createTime = retObject.getString("startTime");//计费时间,格式为“yyyy-MM-dd HH:mi:ss” - String endTime = retObject.getString("endTime");//离场时间,格式为“yyyy-MM-dd HH:mi:ss” - String payPath = "pages/thirdPayOrder/payOrder?carNo="+jieshun.handleCarNumber(carNumber)+"&parkCode="+park.getParkingId(); - return new ResultData(new ParkStopFee(parkOrderId,jieshun.utcToLocal(createTime),jieshun.utcToLocal(endTime), - String.valueOf(retObject.getDouble("totalFee")),appId,payPath,null,null,"请支付后15分钟内离场")); - }else { - logger.error("jieshunCarStopFee error. paramMap: {} . jieshunResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("message"); - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(), "停车费获取失败:"+msg); - } - } - - /** - * 使用3.8打折方案,3.9有限制如果领券了之后未使用,不能再次领券。导致出现异常之后,用户永远无法使用优惠券。 - * @return - */ - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) throws Exception{ - if (null == userCar) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"当前用户未查询到优惠券!"); - } - - if (StringUtils.isBlank(userCar.getCUserPhone())) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"当前用户未查询到手机号!"+userCar.getcUserId()); - } - - Map valueMap = WxParkCouponConfig.parseValue(userCar.getVendorParams()); - if (null == valueMap) { - return new ResultData(ErrorCode.COUPON_IS_EMPTY.getCode(),"当前停车券没有关联停车场优惠券配置。"+coupon.getTitle()); - } - //String orderNo = paramMap.get("parkOrderId"); - String planNo = valueMap.get("couponNo"); - if (StringUtils.isBlank(planNo)) { - return new ResultData(ErrorCode.COUPON_IS_EMPTY.getCode(),"当前停车券没有关联停车场优惠券配置[planNo]。"+coupon.getTitle()); - } - //String ret = jieshun.getCoupon(park, planNo,userCar.getCUserPhone(), getCacheToken(park)); - //打折登陆验证 - String ret = jieshun.verifyuser(park, getCacheToken(park)); - logger.info("jieshun verifyuser result:"+ret); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getIntValue("resultCode") == 0){ - JSONArray verfyArrays = retObj.getJSONArray("dataItems"); - if (null != verfyArrays && verfyArrays.size() > 0 ) { - JSONObject verfy = verfyArrays.getJSONObject(0).getJSONObject("attributes"); - String userId = verfy.getString("userId"); - //查询门店下打折方案 - String queryPlanRet = jieshun.querySalePlan(park, getCacheToken(park), userId); - logger.info("jieshun querySalePlan result:"+queryPlanRet); - JSONObject queryPlantRetObj = JSON.parseObject(queryPlanRet); - if (queryPlantRetObj.getIntValue("resultCode") == 0){ - JSONArray planArrays = queryPlantRetObj.getJSONArray("dataItems"); - if (null != planArrays && planArrays.size() > 0 ) { - boolean hasPlan = false; - for (int i = 0 ; i < planArrays.size(); i++) { - JSONObject plan = planArrays.getJSONObject(i); - String planId = plan.getJSONObject("attributes").getString("planId"); - if (planNo.equals(planId)) { - hasPlan = true; - break; - } - } - if (!hasPlan) { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"当前优惠券配置的捷顺编号无效,请联系管理员。"+coupon.getTitle()); - } - //使用打折方案 - String executeRet = jieshun.executediscount(park, planNo, userId, carNumber, getCacheToken(park)); - logger.info("jieshun executediscount result:"+executeRet); - JSONObject executeRetObj = JSON.parseObject(executeRet); - if (executeRetObj.getIntValue("resultCode") == 0){ - return new ResultData(); - }else { - return new ResultData(executeRetObj.getIntValue("resultCode"),"当前用户使用捷顺停打折方案失败。"+executeRetObj.getString("message")); - } - - }else { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"捷顺查询门店未查询到打折信息,请联系管理员。"+userCar.getcUserId()); - } - - }else { - logger.error("jieshun querySalePlan error. paramMap: {} . jieshunResult: {}",JSON.toJSONString(paramMap),queryPlanRet); - String msg = queryPlantRetObj.getString("message"); - return new ResultData(queryPlantRetObj.getIntValue("resultCode"), "捷顺查询门店打折方案失败:"+msg); - } - }else { - return new ResultData(ErrorCode.CYF_STOP_FEE_FAIL.getCode(),"捷顺门店账号登陆失败,请联系管理员。"+userCar.getcUserId()); - } - - }else { - logger.error("jieshun verifyuser error. paramMap: {} . jieshunResult: {}",JSON.toJSONString(paramMap),ret); - String msg = retObj.getString("message"); - return new ResultData(retObj.getIntValue("resultCode"), "当前用户领用到捷顺停车券失败:"+msg); - } - } - - @Override - public ResultData getParkStatus(WxPark park) throws Exception{ - return new ResultData(); - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunUtil.java deleted file mode 100644 index 8c4b9e4..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/jieshun/JieShunUtil.java +++ /dev/null @@ -1,378 +0,0 @@ -package com.iformall.service.park.impl.jieshun; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.domain.po.WxPark; -import com.iformall.exception.MallinkException; - -import lombok.extern.slf4j.Slf4j; - -import org.apache.commons.lang3.StringUtils; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpPost; -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.BasicHeader; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - - -/** - * @author: furunxin - * @Date: 2020/7/1 17:16 - * @Description: 车易付接口对接参数类 - */ - -@Slf4j -public class JieShunUtil { - - public static final String CYF_PARK_ID = "parkingId"; - public static final String CYF_CAR_NUMBER = "plate"; - public static final String CYF_PARK_NAME = "parking"; - public static final String CYF_SYN_ID = "recordOrderId"; - public static final String CYF_ENTRANCE_TIME = "inTime"; - - public static final String CYF_IS_RESULT = "result"; - public static final String CYF_ERR_MSG = "strError"; - public static final int CYF_SUC = 1; - public static final int CYF_ERR = 0; - - - public static final String TOKEN_URL = "http://www.jslife.com.cn/jsaims/login"; - - public static final String CREATE_ORDER = "http://www.jslife.com.cn/jsaims/as"; - - public static final String QUERY_ORDER = "http://www.jslife.com.cn/jsaims/as"; - - public static final String GET_COUPON = "http://www.jslife.com.cn/jsaims/as"; - public static final String COUPON_USE = "http://www.jslife.com.cn/jsaims/as"; - - public static final String VERIFY_USER = "http://www.jslife.com.cn/jsaims/as"; - public static final String QUERY_PLAN = "http://www.jslife.com.cn/jsaims/as"; - public static final String PLAN_EXECUTE = "http://www.jslife.com.cn/jsaims/as"; - - /** - * @description UTC时间转化为本地时间 - * @Params [utcTime] - * @return java.util.Date - * @Author furunxin - * @Date 2020/7/8 下午12:45 - **/ - public static Date utcToLocal(String seconds) throws ParseException { - String format = "yyyy-MM-dd HH:mm:ss"; - SimpleDateFormat sdf = new SimpleDateFormat(format); - Date date=sdf.parse(seconds); - return date; - } - - public static String getLocalDate(){ - LocalDateTime ldt = LocalDateTime.now(); - DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - String nowDate = ldt.format(dtf); - return nowDate; - } - - public String getToken(WxPark wxPark) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - String cid = wxPark.getParkId(); - String userName = vp.getString("usr"); - String password = vp.getString("psw"); - return getToken(cid,userName,password); - } - - private String getToken(String cid,String userName,String password) { - String result = ProcLogin(cid, userName,password); - log.info("jieshun token cid:"+cid+" userName:"+userName+" password:"+password+" result: "+result); - if (StringUtils.isBlank(result)) { - return null; - } - JSONObject res = JSON.parseObject(result); - Integer code = res.getInteger("resultCode"); - if (null == code || code.intValue() != 0) { - String msg = res.getString("message"); - throw new MallinkException(code,msg); - } - return res.getString("token"); - } - - private Map generateMap(String serviceId,Map param) { - Map map = new HashMap(); - map.put("serviceId", serviceId); - map.put("requestType", "DATA"); - map.put("attributes", param); - return map; - } - - public String handleCarNumber(String carNumber) { - if (carNumber.contains("-")) { - return carNumber; - }else { - carNumber = carNumber.substring(0,1)+"-"+carNumber.substring(1, carNumber.length()); - return carNumber; - } - } - /** - * 创建订单 - * @return - */ - public String createOrder(WxPark wxPark,String cardNumber,String token) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("businesserCode", vp.get("businesserCode"));//商户编号 - param.put("parkCode", wxPark.getParkingId()); - param.put("orderType", "VNP"); - param.put("carNo", handleCarNumber(cardNumber)); - Map map = generateMap("3c.pay.createorderbycarno",param); - log.info("jieshun create order :" + JSON.toJSONString(map)); - return ProcBussiness(CREATE_ORDER, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - /** - * 查询停车费 - **/ - public String getCarStopFee(WxPark wxPark,String orderNo,String token){ - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("orderNo", orderNo);//商户编号 - Map map = generateMap("3c.pay.queryorder",param); - log.info("jieshun getCarStopFee :" + JSON.toJSONString(map)); - return ProcBussiness(QUERY_ORDER, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - /** - * 打折登陆验证 - */ - public String verifyuser(WxPark wxPark,String token) { - try { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("userCode", vp.get("loginUser"));//商户编号 - - MessageDigest md5Tool = MessageDigest.getInstance("MD5"); - byte[] md5Data = md5Tool.digest((vp.getString("loginPassword")).getBytes("UTF-8")); - String sn = toHexString(md5Data); - param.put("password", sn.toLowerCase());//优惠券编号 - Map map = generateMap("3c.discount.verifyuser",param); - log.info("jieshun verifyuser :" + JSON.toJSONString(map)); - return ProcBussiness(VERIFY_USER, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } catch (NoSuchAlgorithmException e) { - log.error("jieshun verifyuser error.park:"+wxPark.getId(),e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"jieshun verifyuser error.park:"+wxPark.getId()+".error"+e.getMessage()); - } catch (UnsupportedEncodingException e) { - log.error("jieshun verifyuser error.park:"+wxPark.getId(),e); - throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"jieshun verifyuser error.park:"+wxPark.getId()+".error"+e.getMessage()); - } - } - - /** - * 查询门店打折方案 - */ - public String querySalePlan(WxPark wxPark,String token,String userId) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("userId", userId);//商户编号 - Map map = generateMap("3c.discount.querysaleplan",param); - log.info("jieshun querySalePlan :" + JSON.toJSONString(map)); - return ProcBussiness(QUERY_PLAN, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - /** - * 使用打折方案 - */ - public String executediscount(WxPark wxPark,String planId,String userId,String carNumber,String token) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("planId", planId);//商户编号 - param.put("userId", userId);//优惠券编号 - param.put("carOrCardNo", handleCarNumber(carNumber));//优惠券编号 - Map map = generateMap("3c.discount.executediscount",param); - log.info("jieshun executediscount :" + JSON.toJSONString(map)); - return ProcBussiness(PLAN_EXECUTE, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - - /** - * 获取优惠券 - **/ - public String getCoupon(WxPark wxPark,String planNo,String phone,String token){ - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("businesserCode", vp.get("businesserCode"));//商户编号 - param.put("planNo", planNo);//优惠券编号 - param.put("tel", phone);//商户编号 - Map map = generateMap("3c.coupons.receive.coupons",param); - log.info("jieshun getCoupon :" + JSON.toJSONString(map)); - return ProcBussiness(GET_COUPON, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - - /** - * 使用优惠券 - **/ - public String useCoupon(WxPark wxPark,String couponNo,String orderNo,String token){ - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - - Map param = new HashMap(); - param.put("businesserCode", vp.get("businesserCode"));//商户编号 - param.put("couponsNo", couponNo);//优惠券编号 - param.put("orderNo", orderNo);//商户编号 - param.put("parkCode", wxPark.getParkingId()); - Map map = generateMap("3c.coupons.use.coupons",param); - log.info("jieshun useCoupon :" + JSON.toJSONString(map)); - return ProcBussiness(COUPON_USE, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - /*token认证登陆**/ - private static String ProcLogin(String cid,String user,String password) { - String url = TOKEN_URL +"?cid="+cid+"&usr="+user+"&psw="+password; -// ArrayList list = new ArrayList(); -// list.add(new BasicNameValuePair("cid", cid)); -// list.add(new BasicNameValuePair("usr", user)); -// list.add(new BasicNameValuePair("psw",password)); - return Proc(url,null); - } - - /** - * 优惠券使用完毕,0元停车费需调用次接口结清订单 - * @param wxPark - * @param planId - * @param userId - * @param carNumber - * @param token - * @return - */ - public String notifyOrderResult(WxPark wxPark,String orderNo,String token) { - String vendroParams = wxPark.getVendorParams(); - JSONObject vp = JSON.parseObject(vendroParams); - Map param = new HashMap(); - param.put("orderNo", orderNo);//商户编号 - param.put("tradeStatus", 0);//优惠券编号 - param.put("isCallBack", 0);//优惠券编号 - Map map = generateMap("3c.pay.notifyorderresult",param); - log.info("jieshun notifyOrderResult :" + JSON.toJSONString(map)); - return ProcBussiness(PLAN_EXECUTE, wxPark.getParkId(), map, token,vp.getString("version"),vp.getString("signkey")); - } - - private static String ProcBussiness(String url,String cid,Map param,String token,String version,String signKey) { - try { - MessageDigest md5Tool = MessageDigest.getInstance("MD5"); - String p = JSON.toJSONString(param); - byte[] md5Data = md5Tool.digest((p+signKey).getBytes("UTF-8")); - String sn = toHexString(md5Data); - if (url.contains("?")) { - url = url + "&"; - }else { - url = url + "?"; - } - - url = url+"cid="+cid+"&tn="+token+"&sn="+sn+"&v="+version+"&p="+URLEncoder.encode(p, "UTF-8"); -// -// ArrayList list = new ArrayList(); -// list.add(new BasicNameValuePair("cid", cid)); -// list.add(new BasicNameValuePair("v", version));//版本号 -// list.add(new BasicNameValuePair("p",p)); -// list.add(new BasicNameValuePair("sn",sn)); -// if (!StringUtils.isBlank(token)) { -// list.add(new BasicNameValuePair("tn",token)); -// } - return Proc(url,null); - } catch (NoSuchAlgorithmException e) { - log.error("jieshun request error.",e); - } catch (UnsupportedEncodingException e) { - log.error("jieshun request error.",e); - } - return null; - } - - private static String toHexString(byte[] bytes) { - StringBuffer buffer = new StringBuffer(); - for (int i = 0; i < bytes.length; i++) { - buffer.append(String.format("%02X", bytes[i])); - } - return buffer.toString(); - } - - private static String Proc(String url, List pairs) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Accept-Encoding", "UTF-8"); - - if (null != pairs) { - HttpEntity en; - try { - en = new UrlEncodedFormEntity(pairs, HTTP.UTF_8); - httpPost.setEntity(en); - } catch (UnsupportedEncodingException e) { - log.error(e.getLocalizedMessage(),e); - return null; - } - - } - - if (null != pairs) { - log.info("jieshun httpRequest:[url]"+url+"[params]"+JSON.toJSONString(pairs)); - }else { - log.info("jieshun httpRequest:[url]"+url); - } - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - - String result = null; - - //打印StatusLine - log.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - log.debug(result); - } catch (Exception e) { - log.error(e.getLocalizedMessage(),e); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - log.error(e.getLocalizedMessage()); - } - return result; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnParkService.java deleted file mode 100644 index 713aed2..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnParkService.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.iformall.service.park.impl.shangan; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.service.WxCouponOrderService; -import com.iformall.service.WxCouponService; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.impl.BaseParkService; - -@Service -public class ShangAnParkService extends BaseParkService implements ParkAdapterService{ - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - WxCouponOrderService wxCouponOrderService; - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return null; - } - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return member.getId().toString(); - } - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - - } - - @Override - public ResultData carStopFee(Map paramMap, WxPark park) { - return new ResultData(); - } - - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) { - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString(ShangAnUtil.SHANGAN_URL); - String key = objParams.getString(ShangAnUtil.SHANGAN_KEY); - String parkNumber = objParams.getString(ShangAnUtil.SHANGAN_PARK_NUMBER); - - String couponModelId = coupon.getUnit().toString(); - String position = ""; - if (coupon.getUnit().equals(EnumCouponUnit.MONEY.getCode())) { - position = coupon.getPrice().toString(); - } else { - position = String.valueOf(coupon.getPrice()* 60); - } - - String ret = ShangAnUtil.couponSend(url, key, parkNumber, couponModelId, userCar.getExpiredTime(), carNumber, position); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getString(ShangAnUtil.SHANGAN_STATUS).equalsIgnoreCase(ShangAnUtil.SHANGAN_SUCCESS)) { - // 停车券-核销 - try { - wxCouponOrderService.shangAnVerify(userCar.getId(),park); - } catch (Exception e) { - logger.error(e.getMessage()); - } - return new ResultData(); - } else { - return new ResultData(ErrorCode.SHANGAN_COUPON_FAIL.getCode(), retObj.getString(ShangAnUtil.SHANGAN_ERROR_CODE)); - } - } - - @Override - public ResultData getParkStatus(WxPark park) { - return null; - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnUtil.java deleted file mode 100644 index 10eb20a..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/shangan/ShangAnUtil.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.iformall.service.park.impl.shangan; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.exception.MallinkException; -import com.iformall.utils.DateUtils; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -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.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -/** - * 尚安停车 - */ -public class ShangAnUtil { - private final static Logger logger = LoggerFactory.getLogger(ShangAnUtil.class); - - public static final String SHANGAN_URL = "url"; - public static final String SHANGAN_KEY = "key"; - public static final String SHANGAN_PARK_NUMBER = "parkNumber"; - - public static final String KEY = "NzMFFDDJDIFACACCM2zAezDz"; - - public static final String PARK_NUMBER = "p190829183435"; - - public static final String URL = "http://www.p-share.com/shangan-yhq/web/api/outcoupon"; - - public static final String SHANGAN_STATUS = "status"; - public static final String SHANGAN_SUCCESS = "success"; - public static final String SHANGAN_FAIL = "fail"; - public static final String SHANGAN_ERROR_CODE = "errorCode"; - - - public static final SimpleDateFormat dateInFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - - - public static void main(String[] args) throws Exception { - String carNumber = "京XAZMF1"; - Date myDate = DateUtils.getHourTimeAfter(1, new Date()); - - String result = couponSend(URL, KEY, PARK_NUMBER, "1", myDate, carNumber, "1500"); - - JSONObject obj = JSON.parseObject(result); - } - - /** - * md5算法 - * @param data - * @return - * @throws NoSuchAlgorithmException - */ - - public static String md5(String data) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(data.getBytes()); - StringBuilder buf = new StringBuilder(); - byte[] bits = md.digest(); - for(int i=0;i") || resp.startsWith("")) { - return true; - } - return false; - } - - public static String couponSend(String url, String key, String parkNumber, String couponModelId, Date expireTime, String plate, String position) { - Map params = new HashMap<>(); - params.put("parkNum", parkNumber); - params.put("couponModeId", couponModelId); - params.put("endTime", dateInFormat.format(expireTime)); - params.put("plate", plate); - params.put("position", position); - try { - String result = Proc(url, key, parkNumber, params); - if(result == null) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - if(checkRespFailed(result)) { - throw new MallinkException(ErrorCode.CAR_CMD_FAIL); - } - return result; - } catch (Exception e) { - return null; - } - } - - private static String Proc(String url, String key, String parkNumber, Map paramMap) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Accept-Encoding", "UTF-8"); - - String sign = null; - try{ - sign = getSign(key, parkNumber); - httpPost.addHeader("sign", sign); - }catch(NoSuchAlgorithmException e) { - logger.error(e.getLocalizedMessage()); - } - - String jsonstr = JSON.toJSONString(paramMap); - logger.info(jsonstr); - - try { - StringEntity se = new StringEntity(jsonstr, Consts.UTF_8); - se.setContentType("application/json"); - se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8")); - httpPost.setEntity(se); - } catch (Exception e) { - logger.error(e.getMessage()); - } - - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - String result = null; - - //打印StatusLine - logger.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - logger.debug(result); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - logger.error(e.getLocalizedMessage()); - } - - return result; - } - - - - -} - diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDParkService.java b/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDParkService.java deleted file mode 100644 index 71f3459..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDParkService.java +++ /dev/null @@ -1,262 +0,0 @@ -package com.iformall.service.park.impl.tjd; - -import java.util.Date; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.RequestBody; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserBasicInfo; -import com.iformall.domain.po.WxCUserCar; -import com.iformall.domain.po.WxCoupon; -import com.iformall.domain.po.WxPark; -import com.iformall.domain.vo.WxCouponOrderCarCVo; -import com.iformall.enums.EnumAssignTagsTrigger; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.enums.EnumScoreType; -import com.iformall.enums.EnumTJDCode; -import com.iformall.exception.MallinkException; -import com.iformall.service.WxCUserCarService; -import com.iformall.service.WxCUserTagsService; -import com.iformall.service.WxCouponService; -import com.iformall.service.WxScoreRulesService; -import com.iformall.service.park.ParkAdapterService; -import com.iformall.service.park.impl.BaseParkService; -import com.iformall.service.park.impl.util.ParkHelper; - -@Service -public class TJDParkService extends BaseParkService implements ParkAdapterService { - - private final Logger logger = LoggerFactory.getLogger(this.getClass()); - - @Autowired - ParkHelper parkHelper; - - TJDUtil tjd = new TJDUtil(); - - @Autowired - WxCUserCarService wxCUserCarService; - - @Autowired - WxScoreRulesService wxScoreRulesService; - - @Autowired - WxCUserTagsService wxCUserTagsService; - - @Autowired - WxCouponService couponService; - - @Override - public ResultData parkInitConfig(WxPark park) throws Exception { - // TODO Auto-generated method stub - return null; - } - - @Override - public String initLogin(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return null; - } - - @Override - public String bindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - return tjdBindCar(paramMap,park,member.getId()); - } - - - private String tjdBindCar(Map paramMap, WxPark park, Long cuUserId) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - //return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String carNumColor = paramMap.get("carNumColor"); - //if (StringUtils.isBlank(carNumColor)) { - // logger.error("carNumColor为空"); - // return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumColor为空"); - //} - Long newCarId = 0L; - String outCarId = paramMap.get("outCarId"); - if (StringUtils.isBlank(outCarId)) { - logger.warn("outCarId为空"); - newCarId = wxCUserCarService.getNewCarID(); - outCarId = String.valueOf(newCarId); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString("url"); - String partner = objParams.getString("partner"); - String key = objParams.getString("key"); - String version = objParams.getString("version"); - String ret = tjd.registerCar(url, partner, key, version, - carNumber, carNumColor, null, outCarId); - JSONObject retObj = JSON.parseObject(ret); - retObj.put("vendor", park.getVendorType()); - if (retObj.getString("returnCode").equalsIgnoreCase(EnumTJDCode.SUCCESS.getMessage())) { - return String.valueOf(newCarId); - }else { - throw new MallinkException(ErrorCode.CAR_BIND_FAIL.getCode(), "绑车牌失败"); - } -// if (retObj.getString("returnCode").equalsIgnoreCase(EnumTJDCode.SUCCESS.getMessage())) { -// ResultData e = tjdInsertToDB(carNumber, newCarId, retObj, park, cuUserId); -// if (e != null) return e; -// return new ResultData(retObj); -// } else { -// return new ResultData(ErrorCode.CAR_BIND_FAIL.getCode(), "绑车牌失败", retObj); -// } - } - - -// private ResultData tjdInsertToDB(String carNumber, Long newCarId, JSONObject retObj, WxPark park, Long cuUserId) { -// String carId = retObj.getString("carId"); -// // 插入车牌 -// Date curr = new Date(); -// WxCUserCar userCar = new WxCUserCar(); -// userCar.setId(newCarId); -// userCar.setCUserId(cuUserId); -// userCar.updateTenantInfo(park); -// userCar.setCarNumber(carNumber); -// userCar.setVendorType(EnumCarVendor.CAR_TJD.getCode()); -// JSONObject jo = new JSONObject(); -// jo.put("carId", carId); -// userCar.setVendorParams(JSON.toJSONString(jo)); -// userCar.setCreateDate(curr); -// userCar.setUpdateDate(curr); -// try { -// wxCUserCarService.save(userCar); -// wxScoreRulesService.addScore(userCar,EnumScoreType.BIND_CAR, userCar); -// //增加积分 -// parkHelper.addCredit(park, cuUserId); -// } catch (Exception e) { -// logger.error(e.getMessage()); -// return new ResultData(ErrorCode.DB_FAIL.getCode(), "TJD保存车牌失败, e:" + e.getMessage()); -// } -// -// wxCUserTagsService.triggerAssignTags(EnumAssignTagsTrigger.ASSIGN_TAGS_TRIGGER_CAR, cuUserId); -// return new ResultData(); -// } - - - @Override - public void unbindCar(Map paramMap, WxPark park, WxCUserBasicInfo member) { - tjdUnbindCar(paramMap,park,member.getId()); - } - - private ResultData tjdUnbindCar(Map paramMap, WxPark park, Long userId) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - WxCUserCar queryOne = new WxCUserCar(); - queryOne.setCarNumber(carNumber); - queryOne.updateTenantInfo(park); - queryOne.setCUserId(userId); - WxCUserCar userCar = wxCUserCarService.getOne(queryOne); - if (userCar != null) { - String params = userCar.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String carId = objParams.getString("carId"); - - params = park.getVendorParams(); - String url = objParams.getString("url"); - String partner = objParams.getString("partner"); - String key = objParams.getString("key"); - String version = objParams.getString("version"); - String ret = tjd.writeOffCar(url, partner, key, version, carId); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getString("returnCode").equalsIgnoreCase(EnumTJDCode.SUCCESS.getMessage())) { -// try { -// wxCUserCarService.deleteByObj(userCar); -// } catch (Exception e) { -// logger.error("解绑车牌数据库错误, e:" + e.getMessage()); -// return new ResultData(ErrorCode.DB_FAIL.getCode(), "解绑车牌数据库错误, e:" + e.getMessage()); -// } - - return new ResultData(); - } else { - return new ResultData(ErrorCode.CAR_UNBIND_FAIL, "解绑车牌失败"); - } - } - return new ResultData(); - } - - - @Override - public ResultData carStopFee(Map paramMap, WxPark park) { - return tjdCarStopFee(paramMap, park); - } - - private ResultData tjdCarStopFee(@RequestBody Map paramMap, WxPark park) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString(TJDUtil.TJD_URL); - String partner = objParams.getString(TJDUtil.TJD_ACCOUNT); - String key = objParams.getString(TJDUtil.TJD_ACCOUNT_KEY); - String version = objParams.getString(TJDUtil.TJD_VERSION); - String ret = tjd.infoForFreeMins(url, partner, key, version, carNumber); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getString(TJDUtil.TJD_RETURN_CODE).equalsIgnoreCase(EnumTJDCode.SUCCESS.getMessage())) { - return new ResultData(retObj); - } else { - return new ResultData(ErrorCode.TJD_STOP_FEE_FAIL.getCode(), "停车费获取失败"); - } - } - - - @Override - public ResultData useCoupon(Map paramMap, WxPark park, WxCouponOrderCarCVo userCar,WxCoupon coupon,String carNumber) { - String tradeId = paramMap.get("tradeId"); - String accountId = paramMap.get("accountId"); - if (StringUtils.isBlank(tradeId)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "tradeId为空"); - } - if (StringUtils.isBlank(accountId)) { - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "accountId为空"); - } - String params = park.getVendorParams(); - JSONObject objParams = JSON.parseObject(params); - String url = objParams.getString(TJDUtil.TJD_URL); - String partner = objParams.getString(TJDUtil.TJD_ACCOUNT); - String key = objParams.getString(TJDUtil.TJD_ACCOUNT_KEY); - String version = objParams.getString(TJDUtil.TJD_VERSION); - - String amount = ""; - if (coupon.getUnit().equals(EnumCouponUnit.MONEY.getCode())) { - amount = coupon.getPriceStr(); - } else { - amount = String.valueOf(coupon.getPrice()* 60); - } - - String ret = tjd.deductionForDetail(url, partner, key, version, - tradeId, accountId, String.valueOf(userCar.getId()), - coupon.getUnit().toString(), amount); - JSONObject retObj = JSON.parseObject(ret); - if (retObj.getString(TJDUtil.TJD_RETURN_CODE).equalsIgnoreCase(EnumTJDCode.SUCCESS.getMessage())) { - return new ResultData(); - } else { - return new ResultData(ErrorCode.CAR_DEDUCE_FEE_FAIL.getCode(), "停车费抵扣失败"); - } - } - - @Override - public ResultData getParkStatus(WxPark park) { - return null; - } - - @Override - public boolean ignoreUseCouponCache() { - return false; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDUtil.java b/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDUtil.java deleted file mode 100644 index 6284f44..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/tjd/TJDUtil.java +++ /dev/null @@ -1,687 +0,0 @@ -package com.iformall.service.park.impl.tjd; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.iformall.enums.EnumCouponUnit; -import com.iformall.utils.MapUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.http.Consts; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -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.BasicHeader; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.EntityUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Map; - -/** - * 停简单 停车管理 - */ -@Component -public class TJDUtil { - - public static final String TJD_URL = "url"; - public static final String TJD_ACCOUNT = "partner"; - public static final String TJD_ACCOUNT_KEY = "key"; - public static final String TJD_VERSION = "version"; - - public static final String TJD_CHARSET = "charset"; - public static final String TJD_UTF_8 = "utf-8"; - - public static final String TJD_RETURN_CODE = "returnCode"; - public static final String TJD_RETURN_SUCC = "T"; - public static final String TJD_RETURN_FAIL = "F"; - - public static final String TJD_IS_SUC = "isSuccess"; - public static final String TJD_ERR_MSG = "errorMSG"; - public static final String TJD_SUC = "0"; - public static final String TJD_ERR_1 = "1"; // 业务级失败(不进行重发) - public static final String TJD_ERR_2 = "2"; // 系统级失败(有重发机制) - public static final String TJD_PARK_ID = "parkId"; - public static final String TJD_PARK_NAME = "parkName"; - public static final String TJD_CAR_NUMBER = "carNum"; - public static final String TJD_TRADE_ID = "tradeId"; - public static final String TJD_IN_DT = "inDt"; - public static final String TJD_OUT_DT = "outDt"; - public static final String TJD_PARK_AMT = "parkAmount"; - public static final String TJD_PAY_AMT = "payAmount"; - public static final String TJD_PAY_DT = "payDt"; - public static final String TJD_FREE_MINS = "freeMins"; - public static final String TJD_ACCOUNT_ID = "accountId"; - public static final String TJD_PREPAY_TYPE = "prePayType"; - public static final String TJD_PREPAY_TYPE_3 = "3"; // 三方合作方支付 - public static final String TJD_PREPAY_TYPE_20 = "20"; // 手机场内支付 - public static final String TJD_DETAIL_LIST = "detailList"; - public static final String TJD_OUT_TRADE_NO = "outTradeNo"; - public static final String TJD_TYPE = "type"; - public static final String TJD_TYPE_DISCOUNT = "0"; - public static final String TJD_TYPE_COUPON = "1"; - public static final String TJD_COUPON_TYPE = "couponType"; - public static final String TJD_CHANNEL = "channel"; - public static final String TJD_AMOUNT = "amount"; - public static final String TJD_MINUTES = "minutes"; - public static final String TJD_CREDIT = "integral"; - public static final String TJD_MEMO = "memo"; - - public static final SimpleDateFormat dateInFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - public static final SimpleDateFormat dateOutFormat = new SimpleDateFormat("yyyyMMddHHmmss"); - - - private final static Logger logger = LoggerFactory.getLogger(TJDUtil.class); - - private static String baseurl = "http://prep.tingjiandan.com/openapi/gateway"; - - private static String partner = "fb21a5b2f7064ff5afb8288d5bb48ca8"; - private static String key = "bc2f09be8f5b4227898346cf6fe451c2"; - private static String version = "1.0"; - - // - // {"url":"http://prep.tingjiandan.com/openapi/gateway","partnerId":"fb21a5b2f7064ff5afb8288d5bb48ca8","key":"bc2f09be8f5b4227898346cf6fe451c2","parkId":"7715622dff834b34a44448b801c27607", "version":"1.0.0"} - // - - public static void main(String[] args) throws Exception { - String carNumber = "京XAZMF1"; - - String result = infoForFreeMins(baseurl, partner, key, version, carNumber); - - JSONObject obj = JSON.parseObject(result); - /* - - Map paramMap1 = MapUtil.getOrderMap(); - paramMap1.put("tradeId", obj.getString("tradeId")); - paramMap1.put("deductionAmount", obj.getString("totalAmount")); - paramMap1.put("outTradeNo", "utf-8"); - paramMap1.put("accountId", obj.getString("accountId")); - paramMap1.put(TJD_CHARSET, "utf-8"); - paramMap1.put(TJD_ACCOUNT, partner); - paramMap1.put(TJD_VERSION, version); - - deductionNotSettle(baseurl, key, paramMap1); - */ - } - - /** - * md5算法 - * @param data - * @return - * @throws NoSuchAlgorithmException - */ - - public static String md5(String data) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(data.getBytes()); - StringBuilder buf = new StringBuilder(); - byte[] bits = md.digest(); - for(int i=0;i map, String keysign) throws NoSuchAlgorithmException { - StringBuilder sb = new StringBuilder(); - for (Map.Entry entry : map.entrySet()) { - if (entry.getValue() != null || entry.getValue() != "") { - sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"); - } - } - if(StringUtils.isNotBlank(sb)){ - sb.deleteCharAt(sb.length()-1);// ? - } - sb.append(keysign); - logger.debug("签名前的字符串输出:"+sb.toString()); - String signValue = md5(sb.toString()).toUpperCase(); - logger.debug("sign: " + signValue); - return signValue; - } - - /** - * 注册车牌 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * - * { - * "carNum": "京A45781", - * "carNumColor": "blue", - * "phone": "15210501514", - * "outCarId": "45454545454", - * "partner": "5836b8b52ada463ebc6199579f029566", - * "timestamp": "2016-05-26 11:30:10", - * "version": "1.0" - * } - * @throws Exception - */ - public static String registerCar(String url, String partner, String key, String version, - String carNum, String carNumColor, String phone, String outCarId) { - String service = "parkhub.car.register"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put(TJD_CAR_NUMBER, carNum); - paramMap.put("carNumColor", carNumColor); - if (phone != null) { - paramMap.put("phone", phone); - } - if (outCarId != null) { - paramMap.put("outCardId", outCarId); - } - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - - /* - { - "timestamp": "1464235239561", - "returnCode": "T", - "errorMsg": "", - "returnMsg": "OK", - "isSuccess": "0", - "carId": "5836b8b52ada463ebc6199579f029561" - }*/ - return result; - } - - /** - * 注销车牌 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * - * { - * "service": "parkhub.car.writeOff", - * "version":"1.0", - * "sign":"3347b109a1e44f3fd5baa78b74a84948", - * "partner":"5836b8b52ada463ebc6199579f029566", - * "carId":"3347b109a1e44f3fd5baa78b74a84948", - * "timestamp":"2016-05-26 11:30:10", - * "charset":"utf-8", - * "signType":"md5" - * } - * @throws Exception - */ - public static String writeOffCar(String url, String partner, String key, String version, - String carId) { - String service = "parkhub.car.writeOff"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put("carId", carId); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - - /* - { - "timestamp": "1464235239561", - "returnCode": "T", - "errorMsg": "", - "returnMsg": "OK", - "isSuccess": "0", - }*/ - return result; - } - - - /** - * 在场订单查询 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * - * { - * "carNum": "京A45781", - * "freeMins": "0", - * "partner": "5836b8b52ada463ebc6199579f029566", - * "pmParkId": "5836b8b52ada463ebc6199579f029565", - * "timestamp": "2016-05-26 11:30:10", - * "tradeId": "5836b8b52ada463ebc6199579f029565", - * "version": "1.0" - * } - * @throws Exception - */ - public static String infoForFreeMins(String url, String partner, String key, String version, String carNum) { - String service = "parkhub.order.infoForFreeMins"; - - String freeMins = "0"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put(TJD_CAR_NUMBER, carNum); - //paramMap.put("carNumColor", ""); - //paramMap.put("pmParkId", ""); - paramMap.put(TJD_FREE_MINS, freeMins); - //paramMap.put("tradeId", ""); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - - /* - { - "wLon":"116.310335", - "returnCode":"T", - "lon":"116.316813", - "accountId":"818a6ac865e841119ec9aab21c5e5a24", - "freeThroughTime":"10", - "customerServicePhone":"400-001-0606", - "tradeId":"2ae003431584495081014428c90173ab", - "returnMsg":"OK", - "outDt":"20190920110443", - "isSuccess":"0", - "miniProgram":"{\"path\": \"pages/pre_pay/index/main\",\"extraData\": {\"prePayType\": \"16\",\"channel\": \"30166\",\"isShowDetail\": \"true\",\"partnerId\": \"956ca31ac8464cf7b6a876e8887912f3\",\"orderId\": \"2ae003431584495081014428c90173ab\"}}","pmParkId":"7715622dff834b34a44448b801c27607","unPayAmount":"88.12","timestamp":"1568948681580","errorMSG":"","parkTime":"81629","wLat":"39.93609","totalAmount":"88.12","paidAmount":"0.00","freeMinsAmount":"0.00","payUrl":"https://prep.tingjiandan.com/tcweixin/letter/prePay/pagePayInPark?prePayType=16&channel=30166&isShowDetail=true&partnerId=&orderId=2ae003431584495081014428c90173ab&returnUrl=", - "lat":"39.942078", - "inDt":"20190919122414"} - */ - return result; - } - - //// TODO - /** - * deductionNotSettle 停车费批量抵扣接口 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * type 可选值:0=抵扣、1=优惠券 - * couponType type=1时必填,可选值:0=金额、1=时长、2=全免、3=时间区间 - * channel 可选值: type=0时:5013=微信、5014=支付宝、5015=抵扣其他 - * type=1时:2202=会员等级、2203=会员积分、2204=会员卡券、2205=会员补贴、2206=会员其他 - * amount: type=0时、couponType=0必填,单位(元),保留小数点后两位,金额类型使用 - * minutes: couponType=1时必填,单位(分钟),时长类型使用 - * integral: 大于等于0的整数值,积分类型使用,如果使用了积分兑换,可填写积分值 - * expireDt: type=1时选填,格式:yyyyMMddHHmmss,如果不填,则永不过期,若填写,则出场时间在此 时间之后,认为此记录已经过期,不再使用 - * membershipGrade: 调用方系统会员等级标识,如:LV1、VIP2、金卡等,长度不超过64位 - * identityType: identityId非空时,此值必填,可选值:01=手机号、02=会员卡号、03=车牌号、04=身份证号 - * identityId: identityType非空时,此值必填,对应身份标识类型的唯一值,长度不超过100位 - * { - "service": "parkhub.order.deductionForDetail", - "partner": "120a565de377427184de35ca0f320764", - "sign": "3347b109a1e44f3fd5baa78b74a84948", - "signType": "md5", - "charset": "utf-8", - "version": "1.0", - "timestamp": "2016-05-26 11:30:10", - "tradeId": "c39d3aac49d04e12a187681e6189f841", - "accountId": "a9b2963c98344bb292e0fa3f7dd70946", - "prePayType": "3", - "giveFreeTimeOut": "false", - "detailList":"[{ - \"outTradeNo\":\"PLDKY01\", - \"identityType\":\"01\", - \"identityId\":\"17710111111\", - \"membershipGrade\":\"LV1\", - \"amount\":\"12.50\", - \"type\":\"0\", - \"channel\":\"5013\", - \"memo\":\"批量抵扣-金额-微信\" - },{ - \"outTradeNo\":\"PLDKY02\", - \"identityType\":\"01\", - \"identityId\":\"17710111111\", - \"membershipGrade\":\"LV1\", - \"couponType\":\"1\", - \"minutes\":\"60\", - \"type\":\"1\", - \"channel\":\"2204\", - \"memo\":\"批量抵扣-时长-会员卡券\" - },{ - \"outTradeNo\":\"PLDKY03\", - \"identityType\":\"01\", - \"identityId\":\"17710111111\", - \"membershipGrade\":\"LV1\", - \"couponType\":\"3\", - \"startDt\":\"20180901110000\", - \"endDt\":\"20180901170000\", - \"integral\":\"500\", - \"type\":\"1\", - \"channel\":\"2205\", \"memo\":\"批量抵扣-区间-积分-会员补贴\" - }]" - } - * @throws Exception - */ - public static String deductionForDetail( - String url, String partner, String key, String version, - String tradeId, String accountId, - String couponOrderId, String couponType, String reduceAmount) { - // 为指定订单抵扣停车费,如果此时车辆已经出场,返回isSuccess错误码为3,停简单系统不再接收此笔抵扣信息,对方系统 需要给用户发起退款。 - String service = "parkhub.order.deductionForDetail"; - Map paramMap = MapUtil.getOrderMap(); - paramMap.put(TJD_TRADE_ID, tradeId); - paramMap.put(TJD_ACCOUNT_ID, accountId); - paramMap.put(TJD_PREPAY_TYPE, TJD_PREPAY_TYPE_3); - - JSONArray detailArr = new JSONArray(); - JSONObject detailObj = new JSONObject(); - detailObj.put(TJD_OUT_TRADE_NO, couponOrderId); - detailObj.put(TJD_TYPE, TJD_TYPE_COUPON); - detailObj.put(TJD_CHANNEL, "2204"); - String memo = "会员优惠券"; - detailObj.put(TJD_COUPON_TYPE, couponType); - if (couponType.equals(String.valueOf(EnumCouponUnit.MONEY.getCode()))) { - detailObj.put(TJD_AMOUNT, reduceAmount); - memo += "-金额"; - } else { - detailObj.put(TJD_MINUTES, reduceAmount); - memo += "-时长"; - } - detailObj.put(TJD_MEMO, memo); - detailArr.add(detailObj); - paramMap.put(TJD_DETAIL_LIST, JSON.toJSONString(detailArr)); - - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - /* - "{\"timestamp\":\"1528534986636\", - \"returnCode\":\"T\", - \"prePayId\":\"7a1d52aa77ca487db4e61130394285bd\", - \"errorMSG\":\"\", - \"returnMsg\":\"OK\", - \"isSuccess\":\"0\"}[\\r][\\n]" - */ - return result; - } - - /** - * deductionNotSettle 停车费无结算抵扣 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * { - "service": "", - "version":"1.0", - "sign":"3347b109a1e44f3fd5baa78b74a84948", - "partner":"5836b8b52ada463ebc6199579f029566", - "timestamp":"2016-05-26 11:30:10", - "charset":"utf-8", - "signType":"md5", - "tradeId": "224478781859452794f2a68a756fe461", - "deductionAmount": "0.1", - "outTradeNo":"4738473847834378", - "accountId":"3347b109a1e44f3fd5baa78b74a84941", - } - * @throws Exception - */ - public static String deductionNotSettle(String url, String partner, String key, String version, - String tradeId, String outTradeNo, String accountId, String deductionAmount) { - // TODO - // 为指定订单抵扣停车费,如果此时车辆已经出场,返回isSuccess错误码为3, - // 停简单系统不再接收此笔抵扣信息,对方系统需要给用户发起退款(后续业务中无结算) - String service = "parkhub.order.deductionNotSettle"; - Map paramMap = MapUtil.getOrderMap(); - paramMap.put("tradeId", tradeId); - paramMap.put("deductionAmount", deductionAmount); - paramMap.put("outTradeNo", outTradeNo); - paramMap.put("accountId", accountId); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - /* - "{\"timestamp\":\"1528534986636\", - \"returnCode\":\"T\", - \"prePayId\":\"7a1d52aa77ca487db4e61130394285bd\", - \"errorMSG\":\"\", - \"returnMsg\":\"OK\", - \"isSuccess\":\"0\"}[\\r][\\n]" - */ - return result; - } - - /** - * bindTime 绑定时长优惠券 - * @param url - * @param partner // - * @param key // 密钥 - * @param version // 1.0 - * - * { - * "service": "parkhub.ticket.bindTime", - * "version":"1.0", - * "sign":"3347b109a1e44f3fd5baa78b74a84948", - * "partner":"5836b8b52ada463ebc6199579f029566", - * "timestamp":"2016-05-26 11:30:10", - * "charset":"utf-8", - * "signType":"md5", - * "tradeId": "224478781859452794f2a68a756fe461", - * "outTicketNo": "224478781859452794f2a68a756fe461", - * "accountId":"3347b109a1e44f3fd5baa78b74a84941", - * "prePayType": "3", - * "minutes": "30", - * "memo": "测试绑定时长优惠券" - * } - * @throws Exception - */ - public static String bindTime(String url, String partner, String key, String version, - String tradeId, String outTicketNo, String accountId, String prePayType, String minutes, String memo) throws Exception { - String service = "parkhub.ticket.bindTime"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put("tradeId", tradeId); - paramMap.put("outTicketNo", outTicketNo); - paramMap.put("accountId", accountId); - paramMap.put("prePayType", prePayType); - paramMap.put("minutes", minutes); - paramMap.put("memo", memo); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - /*{ - "timestamp": "1464247094636", - "returnCode": "T", - "errorMsg": "", - "returnMsg": "OK", - "isSuccess": "0", - "ticketId": "224478781859452794f2a68a756fe441" - }*/ - return result; - } - - /** - * 绑定区间优惠券 - * @param url - * @param partner - * @param key // 密钥 - * @param version - * - * { - * "service": "parkhub.ticket.bindPeriod", - * "version": "1.0", - * "sign": "3347b109a1e44f3fd5baa78b74a84948", - * "partner": "5836b8b52ada463ebc6199579f029566", - * "timestamp": "2016-05-26 11:30:10", - * "charset": "utf-8", - * "signType": "md5", - * "tradeId": "224478781859452794f2a68a756fe461", - * "outTicketNo": "224478781859452794f2a68a756fe461", - * "accountId": "3347b109a1e44f3fd5baa78b74a84941", - * "prePayType": "3", - * "startDt": "20160526113010", - * "endDt": "20160526123010", - * "expireDt": "20160527113010", - * "memo": "测试绑定时长优惠券" - * } - * @throws Exception - */ - public static String bindPeriod(String url, String partner, String key, String version, - String tradeId, String outTicketNo, String accountId, String prePayType, - String startDt, String EndDt, String expireDt, String memo) throws Exception { - String service = "parkhub.ticket.bindPeriod"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put("tradeId", tradeId); - paramMap.put("outTicketNo", outTicketNo); - paramMap.put("accountId", accountId); - paramMap.put("prePayType", prePayType); - paramMap.put("startDt", startDt); - paramMap.put("EndDt", EndDt); - paramMap.put("expireDt", expireDt); - paramMap.put("memo", memo); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - /*{ - "timestamp": "1464247094636", - "returnCode": "T", - "errorMsg": "", - "returnMsg": "OK", - "isSuccess": "0", - "ticketId": "224478781859452794f2a68a756fe441" - }*/ - return result; - } - - /** - * 绑定区间优惠券 - * @param url - * @param partner // 密钥 - * @param key // 密钥 - * @param version - * - * { - * "service": "parkhub.ticket.unbind", - * "version": "1.0", - * "sign": "3347b109a1e44f3fd5baa78b74a84948", - * "partner": "5836b8b52ada463ebc6199579f029566", - * "timestamp": "2016-05-26 11:30:10", - * "charset": "utf-8", - * "signType": "md5", - * "tradeId ": "3347b109a1e44f3fd5baa78b74a84948", - * "ticketId": "224478781859452794f2a68a756fe461" - * } - * @throws Exception - */ - public static String unbind(String url, String partner, String key, String version, - String tradeId, String ticketid) throws Exception { - String service = "parkhub.ticket.unbind"; - - Map paramMap = MapUtil.getOrderMap(); - paramMap.put("tradeId", tradeId); - paramMap.put("ticketid", ticketid); - paramMap.put(TJD_CHARSET, TJD_UTF_8); - paramMap.put(TJD_ACCOUNT, partner); - paramMap.put(TJD_VERSION, version); - - String result = Proc(url, key, service, paramMap); - /*{ - "timestamp": "1464247094636", - "returnCode": "T", - "errorMsg": "", - "returnMsg": "OK", - "isSuccess": "0", - }*/ - return result; - } - - private static String Proc(String url, String key, String service, Map paramMap) { - CloseableHttpClient httpClient = HttpClients.createDefault(); - - HttpPost httpPost = new HttpPost(url); - httpPost.addHeader(HTTP.CONTENT_TYPE,"application/json"); - httpPost.addHeader("Accept", "application/json"); - httpPost.addHeader("Accept-Encoding", "UTF-8"); - - String timestamp = getCurrentDate(); - paramMap.put("timestamp", timestamp); - - paramMap.put("service", service); - - String sign = null; - try{ - sign = getSign(paramMap, key); - }catch(NoSuchAlgorithmException e) { - logger.error(e.getLocalizedMessage()); - } - - paramMap.put("sign", sign); - paramMap.put("signType", "md5"); - - String jsonstr = JSON.toJSONString(paramMap); - logger.info(jsonstr); - - try { - StringEntity se = new StringEntity(jsonstr, Consts.UTF_8); - se.setContentType("application/json"); - se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8")); - httpPost.setEntity(se); - } catch (Exception e) { - logger.error(e.getMessage()); - } - - HttpResponse response = null; - try { - response = httpClient.execute(httpPost); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - String result = null; - - //打印StatusLine - logger.debug("StatusLine: " + response.getStatusLine()); - try{ - //获取实体 - HttpEntity httpEntity= response.getEntity(); - result = EntityUtils.toString(httpEntity, "UTF-8"); - logger.debug(result); - } catch (Exception e) { - logger.error(e.getLocalizedMessage()); - } - - try { //关闭流并释放资源 - httpClient.close(); - } catch (IOException e) { - logger.error(e.getLocalizedMessage()); - } - - return result; - } - -} - diff --git a/suimangService/src/main/java/com/iformall/service/park/impl/util/ParkHelper.java b/suimangService/src/main/java/com/iformall/service/park/impl/util/ParkHelper.java deleted file mode 100644 index a4d64b7..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/impl/util/ParkHelper.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.iformall.service.park.impl.util; - -import java.util.Date; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; -import com.iformall.domain.po.WxCUserCar; -import com.iformall.domain.po.WxCreditHistory; -import com.iformall.domain.po.WxPark; -import com.iformall.enums.EnumAssignTagsTrigger; -import com.iformall.enums.EnumCarVendor; -import com.iformall.enums.EnumScoreType; -import com.iformall.enums.EnumUserType; -import com.iformall.exception.MallinkException; -import com.iformall.service.WxCUserCarService; -import com.iformall.service.WxCUserTagsService; -import com.iformall.service.WxCreditHistoryService; -import com.iformall.service.WxScoreRulesService; - -@Service -public class ParkHelper { - private final Logger logger = LoggerFactory.getLogger(ParkHelper.class); - - @Autowired - WxCUserCarService wxCUserCarService; - - @Autowired - WxScoreRulesService wxScoreRulesService; - - @Autowired - WxCUserTagsService wxCUserTagsService; - - @Autowired - WxCreditHistoryService wxCreditHistoryService; - - public WxCUserCar getOne(WxPark park, Long cuUserId,String carNumber,EnumCarVendor carVendor) { - WxCUserCar userCar = new WxCUserCar(); - userCar.updateTenantInfo(park); - userCar.setCUserId(cuUserId); - userCar.setCarNumber(carNumber); - userCar.setVendorType(carVendor.getCode()); - return wxCUserCarService.getOne(userCar); - } - - public ResultData bindCar(Map paramMap, WxPark park, Long cuUserId,String vendorPersonId) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - try { - addCarInfoToDB(carNumber, EnumCarVendor.getEnum(park.getVendorType()), park, cuUserId,vendorPersonId); - } catch (MallinkException e) { - return new ResultData(e.getErrorCode(), e.getMessage()); - } catch (Exception e) { - return new ResultData(500, e.getMessage()); - } - return new ResultData(vendorPersonId); - } - - public void addCarInfoToDB(String carNumber, EnumCarVendor carVendor, WxPark park, Long cuUserId,String vendorPersonId) { - // 插入车牌 - Date curr = new Date(); - WxCUserCar userCar = new WxCUserCar(); - userCar.setCUserId(cuUserId); - userCar.updateTenantInfo(park); - userCar.setCarNumber(carNumber); - userCar.setVendorType(carVendor.getCode()); - userCar.setCreateDate(curr); - userCar.setUpdateDate(curr); - userCar.setVendorPersonId(vendorPersonId); - wxCUserCarService.saveOrUpdate(userCar); - - // 成长值 - wxScoreRulesService.addScore(userCar,EnumScoreType.BIND_CAR, userCar); - //增加积分 - addCredit(park, cuUserId); - wxCUserTagsService.triggerAssignTags(EnumAssignTagsTrigger.ASSIGN_TAGS_TRIGGER_CAR,userCar,park,null); - } - - //-----增加积分start----- - public void addCredit(WxPark park, Long cuUserId){ - WxCreditHistory wxCreditHistory = new WxCreditHistory(); - wxCreditHistory.setCUserId(cuUserId); -// wxCreditHistory.updateTenantInfo(park); - wxCreditHistory.setTenantId(park.getFinalTenantId()); - wxCreditHistory.setFinalTenantId(park.getFinalTenantId()); -// wxCreditHistory.setCreateDate(new Date()); - wxCreditHistory.setCreditType(EnumScoreType.BIND_CAR.getCode()); - wxCreditHistory.setChangePurpose(EnumScoreType.BIND_CAR.getMessage()); - wxCreditHistory.setOperatorType(EnumUserType.CUSERBASIC.getCode()); - wxCreditHistory.setOperatorId(cuUserId); - wxCreditHistoryService.saveOrUpdate(wxCreditHistory,park.getTenantId()); - } - - public ResultData unbindCar(Map paramMap, WxPark park, Long cuUserId) { - String carNumber = paramMap.get("carNumber"); - if (StringUtils.isBlank(carNumber)) { - logger.error("carNumber为空"); - return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "carNumber为空"); - } - try { - WxCUserCar userCar = new WxCUserCar(); - userCar.updateTenantInfo(park); - userCar.setCUserId(cuUserId); - userCar.setCarNumber(carNumber); - wxCUserCarService.deleteByObj(userCar); - } catch (Exception e) { - logger.error(e.getMessage()); - return new ResultData(ErrorCode.DB_FAIL.getCode(), "解绑车牌数据库错误, e:" + e.getMessage()); - } - - return new ResultData(); - } -} diff --git a/suimangService/src/main/java/com/iformall/service/park/utils/ParkCacheUtils.java b/suimangService/src/main/java/com/iformall/service/park/utils/ParkCacheUtils.java deleted file mode 100644 index 4302f6b..0000000 --- a/suimangService/src/main/java/com/iformall/service/park/utils/ParkCacheUtils.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.iformall.service.park.utils; - -import org.springframework.data.redis.core.RedisTemplate; - -import com.iformall.utils.RedisCacheUtils; - -public class ParkCacheUtils { - - public static void removeCache(RedisTemplate template,String parkVendor,String carNumber) { - String key = "carStop:"+parkVendor+":"+carNumber; - RedisCacheUtils.removeCache(template, key); - } - - public static void setCarCouponUnUseCacheLock(RedisTemplate template,String parkVendor,String carNumber) { - String key = "carStop:"+parkVendor+":"+carNumber; - RedisCacheUtils.cache(template, key, 0, 12*3600); - } - - public static void setCarCouponUsedCacheLock(RedisTemplate template,String parkVendor,String carNumber) { - String key = "carStop:"+parkVendor+":"+carNumber; - RedisCacheUtils.cache(template, key, 1, 12*3600); - } - - public static Integer getCarCouponUseCacheLock(RedisTemplate template,String parkVendor,String carNumber) { - String key = "carStop:"+parkVendor+":"+carNumber; - return RedisCacheUtils.getCacheInteger(template, key); - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/PayServiceFactory.java b/suimangService/src/main/java/com/iformall/service/pay/PayServiceFactory.java index 01ec892..4429fa7 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/PayServiceFactory.java +++ b/suimangService/src/main/java/com/iformall/service/pay/PayServiceFactory.java @@ -5,7 +5,9 @@ import java.util.concurrent.ConcurrentHashMap; import com.iformall.enums.EnumAppPlat; import com.iformall.enums.EnumPayVersion; import com.iformall.enums.EnumProductOrderPayVendor; +import com.iformall.service.pay.service.pay.ali.page.AliPagePayAdapterService; import com.iformall.service.pay.service.pay.wx.v3.nativePay.WxNativePayV3AdapterService; +import com.iformall.service.pay.service.refund.ali.AliRefundAdapterService; import com.iformall.service.pay.service.refund.douyin.TtRefundAdapterService; import com.iformall.service.pay.service.refund.wx.v2.WxRefundAdapterService; import com.iformall.service.pay.service.refund.wx.v3.WxRefundV3AdapterService; @@ -50,6 +52,7 @@ public class PayServiceFactory { private Map payVendorServiceMap = null; private Map payVendorShareMap = null; + private Map payVendorRefundMap = null; private Map platQrcodeMap = null; private Map platMsgMap = null; @@ -63,6 +66,8 @@ public class PayServiceFactory { @Autowired WxNativePayV3AdapterService wxNativePayV3AdapterService; + @Autowired + AliPagePayAdapterService aliPagePayAdapterService; @Autowired WxMiniMaPayAdapterService wxMiniAppMaPayService; @@ -92,6 +97,8 @@ public class PayServiceFactory { @Autowired TtRefundAdapterService ttRefundService; + @Autowired + AliRefundAdapterService aliRefundService; @Autowired WxCashOutQYFKAdapterService wxCashOutService; @@ -154,7 +161,7 @@ public class PayServiceFactory { payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode()+"_", wxMiniAppPayV3AdapterService); payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_WECHAT_NATIVE.getCode()+"_", wxNativePayV3AdapterService); // payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_ALIPAY.getCode()+"_", ); -// payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_ALIPAY_WAP.getCode()+"_",); + payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_ALIPAY_WAP.getCode()+"_",aliPagePayAdapterService); payVendorServiceMap.put(EnumProductOrderPayVendor.PAY_WAY_TT.getCode()+"_",ttMiniAppPayService); } return payVendorServiceMap; @@ -235,6 +242,18 @@ public class PayServiceFactory { } return refundMap; } + + private Map getPayVendorRefundMap(){ + if (null == payVendorRefundMap ) { + payVendorRefundMap = new ConcurrentHashMap(); + payVendorRefundMap.put(EnumProductOrderPayVendor.PAY_WAY_WECHAT.getCode()+"_", wxRefundV3AdapterService); + payVendorRefundMap.put(EnumProductOrderPayVendor.PAY_WAY_WECHAT_NATIVE.getCode()+"_", wxRefundV3AdapterService); + payVendorRefundMap.put(EnumProductOrderPayVendor.PAY_WAY_ALIPAY.getCode()+"_", aliRefundService); +// payVendorRefundMap.put(EnumProductOrderPayVendor.PAY_WAY_ALIPAY_WAP.getCode()+"_",); + payVendorRefundMap.put(EnumProductOrderPayVendor.PAY_WAY_TT.getCode()+"_",ttRefundService); + } + return payVendorRefundMap; + } private Map getCashOutMap() { if (null == cashoutMap ) { @@ -334,6 +353,14 @@ public class PayServiceFactory { } return refundService; } + + public RefundPayAdapterService getRefundPayAdapterService(Integer payVendor) throws MallinkException{ + RefundPayAdapterService refundService = getPayVendorRefundMap().get(payVendor+"_"); + if (null == refundService) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"payWay["+payVendor+"] 退款service未找到"); + } + return refundService; + } public CashOutAdapterService getCashOutAdapterService(Integer type,Integer payVersion)throws MallinkException { CashOutAdapterService cashOutService = getCashOutMap().get(type+"_"+payVersion); diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/AliPayUtil.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/AliPayUtil.java deleted file mode 100644 index 527d85e..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/AliPayUtil.java +++ /dev/null @@ -1,357 +0,0 @@ -package com.iformall.service.pay.alipay; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.stereotype.Service; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.alipay.easysdk.base.image.models.AlipayOfflineMaterialImageUploadResponse; -import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse; -import com.alipay.easysdk.kernel.Config; -import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse; -import com.iformall.service.pay.alipay.api.AliPayApi; -import com.iformall.service.pay.alipay.api.enums.EnumMemberCardConfig; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelColumn; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelFieldRule; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelRequest; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelStyle; -import com.iformall.service.pay.alipay.api.result.UserAuthData; -import com.iformall.service.pay.alipay.config.AliPayConfig; - -import lombok.extern.slf4j.Slf4j; - -@Component -@Slf4j -public class AliPayUtil { - - @Autowired - AliPayConfig payConfig; - - private Config getConfig() { - //AliPayConfig payConfig = new AliPayConfig(); - //payConfig.setAppId("2021002137663024"); - //payConfig.setAppPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCUfymV5J73QQMG52PVIGUbowkloYCO4B7TQoKbrTZf2YeYsg/To/o4PiXPMNwEUfEUU8NYQ6WwNhCd2fa1ei8WFXJUf3bfgswtBk1aOmHLeY9yoXFxIKMTQ9RcobnmBzKQZlaAPMTSr7t1QtKZKPuc2gEHGRFYKO/ZuL8gIpnsVidVtmi52yd7hzao/pI3ThLA0lreg4L3rYP5ESQZRytxIPgUQ4KI11pZxFgbe+uy28AGDYIQscSIb+SWOHPYKLvOEqqepIZ8M18w/U0lZzpzepzi/V/llekvXJ6UEf1lzl7x/4UIA3WPN1B40+NzbD/OxEGTuM0UctOG6ZTd4Te9AgMBAAECggEAPYksnHbvARspu/SrRCh2fatkIPn6Ijrxyy3mnch7neCw9i/jqxpqmF/4nxFqO0gRlRDZBHyT7p+Y5zDpsW5+kLI2fJmNkzXKkmXoLBnBaOZo8WHBdtXFfjg/iltig9Y7t+cQtXd5QK2eCwuz5dA75FXa0ywqKdRdAGY0nYZ5LpwrHVU8RXheUDCJyhKNj2+W6lIaSKDxLZU3laO1oBrv1agcy7Crd5E2ndb8O3Enga+z7wSz2h7A1BasC/Yl/Ro0Y21wLCH3s/R6qA0Paq12+WEF+xdodM7SrP43CCTVFGbC1TfEOdanJfixop8QuYsIp7pHrL925+vP4eY9RfckgQKBgQDQqLdpDzzU7Ot/L9Vc/r8d4iwXXbX8+HwVFV4oBuausgFyv8eJJpfrI+IlEoB1ubJcPpJBFqfmeYTW6/v6ioFljJAlWfFvesUVt/HszBMIOsU0Bzt7ex6WlwKOagb0q0ZPA4T0OY0K0lg0loaaaR8ZTr4ivDymaGBtTBYhslpc7QKBgQC2MBznGEc5r2dhyENvdPOR20PnXQcevGnPdqSus8m0VmDcHE72RVcckcZtwczsb3NaLSqmjAcWTn51/VFmlvhB3F34FcFTPZGq6sj7fWK8HuFq7l7mu5OzYuVr73zy9ggsUuaw10IqvvwIVxszNAF0hiRnSGH3z27CoRmz3s+8EQKBgQCK3o7atBJ3X4rIJiypbL4DhIB1uJ+jUjk6yvLUTut+fufp1+tTw0S+cS5UIAEw2Lr1G4u5F/v8rwmTBJG6SC4gSLGyui6uVBYRA1BWmedcxchzfRDAeMt9y9kesUAZ3Fe5xIzbAeZ1ulKMBVZmM+pHrJlsgr0Wv0bV1xqvqITtbQKBgBIsIGXopQoa9dvqBtfyOW1eCprkS5aEQqWf9vM6Ga90QjsSU8n6xqKh48IE57TZtQ7UnIF6TCasc66/MsRh4KdpHLJnMR5lcMc0nhF/wz5ychehaTPol+X3wlyOyc7OPah2KG6ROhdbb3ZBggQMduyxiKYIsUTvmuOtAAxR+DSRAoGADtuDzGQDOJYWiO2uuP6FpA5IJaiwlSfu3xncJVfhO8SVr6VBJFg88igbIB3w6nk/sv7j9VTXqXre9HMvp1flxaaLsdxM4HcTSALS9q6t/ajaveqte6S5kAtWx0WW8C6PtgWXHbxcD7LXARSsKLoEl2JXXyUVS/m2l/RzHBQ8GJI="); - //payConfig.setAppPublicKeyCertPath("C://appCertPublicKey_2021002137663024.crt"); - //payConfig.setAlipayCertPath("C://alipayCertPublicKey_RSA2.crt"); - //payConfig.setAlipayRootCertPath("C://alipayRootCert.crt"); - return AliPayApi.getOptions(payConfig.getAppId(), payConfig.getAppPrivateKey(), payConfig.getAppPublicKeyCertPath(), - payConfig.getAlipayCertPath(), payConfig.getAlipayRootCertPath()); - } - - private String getCallBack() { - //AliPayConfig payConfig = new AliPayConfig(); - //payConfig.setCallback("https://callbacktest.malls.iformall.com/api/alipay/notify/callback"); - return payConfig.getCallback(); - } - - //第三方应用授权 - public String getAppAuthUrl(String param) { - try { - return AliPayApi.getAppAuthUrl(getConfig(), getCallBack(), param); - } catch (UnsupportedEncodingException e) { - log.error("alipay getMerchantAuthUrl error. ",e); - } - return null; - } - - //查询app_auth_token - public String getAppAuthToken(String appAuthCode) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.getAppAuthToken(getConfig(),appAuthCode); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_open_auth_token_app_response"); - if (null != result) { - JSONArray arrays = result.getJSONArray("tokens"); - if (null != arrays) { - JSONObject resutl0 =arrays.getJSONObject(0); - return resutl0.getString("app_auth_token"); - }else { - log.error("alipay getAppAuthToken error. ",response.getHttpBody()); - } - } - - } catch (Exception e) { - log.error("alipay getAppAuthToken error. ",e); - } - return null; - } - - private static JSONObject getGenericResponseWithCodes(String result,String key,String[] successCodes) { - if (StringUtils.isBlank(result)) { - log.error("alipay apiresponse ["+key+"] error. no result."+result); - return null; - } - JSONObject object = JSON.parseObject(result); - if (null != object) { - JSONObject resultObject = object.getJSONObject(key); - if (null != resultObject ) { - String code = resultObject.getString("code"); - for (String successCode : successCodes) { - if ((successCode.equals(code))) { - return resultObject; - } - } - } - } - log.error("alipay apiresponse ["+key+"] error. "+result); - return null; - } - - private static JSONObject getGenericResponse(String result,String key) { - return getGenericResponseWithCodes(result,key,new String[] {"10000"}); - } - - //门店照片上传 - public String merchantImageUpload(String appAuthToken,String imageName,byte[] file) { - String temfolder = "/alipaytempfile/"+UUID.randomUUID(); - File tempfolerFile = new File(temfolder); - if (!tempfolerFile.exists()) { - tempfolerFile.mkdirs(); - } - String temFilePath = temfolder+"/"+imageName; - File f = new File(temFilePath); - if (f.exists()) { - f.delete(); - } - try { - FileOutputStream fos = new FileOutputStream(f); - fos.write(file); - fos.close(); - AlipayOfflineMaterialImageUploadResponse response = AliPayApi.uploadMerchantImage(getConfig(),appAuthToken,imageName, temFilePath); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_offline_material_image_upload_response"); - if (f.exists()) { - f.delete(); - } - if (null != result) { - return result.getString("image_id"); - } - } catch (Exception e) { - if (f.exists()) { - f.delete(); - } - log.error("alipay merchantImageUpload error. ",e); - } - return null; - } - - //创建商圈会员卡 - public String createSmartDistrictMemberCardModel(String appAuthToken,String cardName,String logoId,String backImageId) { - AlipayMemberCardModelRequest request = new AlipayMemberCardModelRequest(); - AlipayMemberCardModelStyle style = new AlipayMemberCardModelStyle(); - style.setCard_show_name(cardName); - style.setLogo_id(logoId); - style.setBackground_id(backImageId); - request.setTemplate_style_info(style); - - List columnList = new ArrayList(); - AlipayMemberCardModelColumn column0 = new AlipayMemberCardModelColumn(); - column0.setCode("TELEPHONE"); - column0.setTitle("联系电话"); - columnList.add(column0); - AlipayMemberCardModelColumn column1 = new AlipayMemberCardModelColumn(); - column1.setCode("BENEFIT_INFO"); - column1.setTitle("会员专享"); - columnList.add(column1); - request.setColumn_info_list(columnList); - - List ruleList = new ArrayList(); - AlipayMemberCardModelFieldRule rule0 = new AlipayMemberCardModelFieldRule(); - rule0.setField_name("Balance"); - rule0.setRule_name("ASSIGN_FROM_REQUEST"); - rule0.setRule_value("Balance"); - ruleList.add(rule0); - request.setField_rule_list(ruleList); - - try { - AlipayOpenApiGenericResponse response = AliPayApi.createMemberCardModel(getConfig(),appAuthToken, request); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_marketing_card_template_create_response"); - if (null != result) { - return result.getString("template_id"); - } - } catch (Exception e) { - log.error("alipay createSmartDistrictMemberCardModel error. ",e); - } - return null; - } - - //创建商圈会员卡表单配置 - public boolean setSmartDistrictMemberCardModelConfig(String appAuthToken,String templateId) { - try { -// AlipayOpenApiGenericResponse response = AliPayApi.setMemberCardModelConfig(getConfig(),appAuthToken, templateId, -// new String[] {EnumMemberCardConfig.OPEN_FORM_FIELD_MOBILE.getCode()},new String[] {EnumMemberCardConfig.OPEN_FORM_FIELD_NAME.getCode()}); - AlipayOpenApiGenericResponse response = AliPayApi.setMemberCardModelConfig(getConfig(),appAuthToken, templateId, - new String[] {EnumMemberCardConfig.OPEN_FORM_FIELD_MOBILE.getCode()},null); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_marketing_card_formtemplate_set_response"); - if (null != result) { - return true; - } - } catch (Exception e) { - log.error("alipay setSmartDistrictMemberCardModelConfig error. ",e); - } - return false; - } - - //获取商圈会员卡领卡投放链接 - public String getSmartDistrictMemberCardUrl(String appAuthToken,String templateId,String param) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.getMemberCardUrl(getConfig(),appAuthToken, templateId, param, getCallBack()); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_marketing_card_activateurl_apply_response"); - if (null != result) { - return result.getString("apply_card_url"); - } - } catch (Exception e) { - log.error("alipay getSmartDistrictMemberCardUrl error. ",e); - } - return null; - } - - //商圈智能积分授权(算法授权)URL - public String getH5SmartDistrictMallVipPointsUrl(String param) { - try { - return "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id="+getConfig().appId+"&scope=mall_vip_points&redirect_uri="+URLEncoder.encode(getCallBack(),"utf-8")+"&state="+param; - } catch (UnsupportedEncodingException e) { - log.error("alipay getH5MallVipPointsUrl error. ",e); - } - return null; - } - - //获取用户授权令牌 - public UserAuthData queryUserAuthData(String appAuthToken,String authCode) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.queryUserAuthData(getConfig(), appAuthToken, authCode); - //JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_system_oauth_token_response"); - JSONObject responseResult = JSON.parseObject(response.getHttpBody()); - if (null != responseResult) { - JSONObject result = responseResult.getJSONObject("alipay_system_oauth_token_response"); - if (null != result) { - UserAuthData authData = new UserAuthData(); - authData.setUserId(result.getString("user_id")); - authData.setAccessToken(result.getString("access_token")); - return authData; - }else { - log.error("alipay queryUserAuthData error. "+response.getHttpBody()); - } - } - } catch (Exception e) { - log.error("alipay queryUserAuthData error. ",e); - } - return null; - } - - //查询用户表单信息 - public Map queryUserFormData(String appAuthToken,String authToken,String templateId,String requestId) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.queryUserFormData(getConfig(), appAuthToken, authToken, templateId, requestId); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_marketing_card_activateform_query_response"); - if (null != result) { - String infos = result.getString("infos"); - if (StringUtils.isBlank(infos)) { - return null; - } - - JSONArray infosArray = JSON.parseArray(infos); - if (null == infosArray) { - return null; - } - Map map = new HashMap(); - for (int i = 0 ; i < infosArray.size(); i++) { - Map jo = (Map)infosArray.get(i); - Object[] keys = jo.keySet().toArray(); - EnumMemberCardConfig config = EnumMemberCardConfig.getEnum(String.valueOf(keys[0])); - if (null != config) { - map.put(config, jo.get(keys[0])); - } - } - if (map.isEmpty()) { - return null; - } - return map; - } - } catch (Exception e) { - log.error("alipay queryUserFormData error. ",e); - } - return null; - } - - //用户开卡 - public boolean openCard(String appAuthToken,String authToken,String templateId,String userId) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.openCard(getConfig(), appAuthToken, authToken, templateId, userId); - JSONObject result = getGenericResponse(response.getHttpBody(),"alipay_marketing_card_open_response"); - if (null != result) { - return true; - } - } catch (Exception e) { - log.error("alipay openCard error. ",e); - } - return false; - } - - //商圈消息订阅 - public boolean smartDistrictTopicSubscribe(String appAuthToken,String topic) { - try { - AlipayOpenApiGenericResponse response = AliPayApi.topicSubscribe(getConfig(),appAuthToken, "app_auth", topic, "HTTP", "BIZ_TAG"); - JSONObject result = getGenericResponseWithCodes(response.getHttpBody(),"alipay_open_app_message_topic_subscribe_response",new String[] {"40004","10000"}); - if (null != result) { - return true; - } - } catch (Exception e) { - log.error("alipay smartDistrictTopicSubscribe error. ",e); - } - return false; - } - - public static byte[] File2byte(File tradeFile){ - byte[] buffer = null; - try - { - FileInputStream fis = new FileInputStream(tradeFile); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int n; - while ((n = fis.read(b)) != -1) - { - bos.write(b, 0, n); - } - fis.close(); - bos.close(); - buffer = bos.toByteArray(); - }catch (FileNotFoundException e){ - e.printStackTrace(); - }catch (IOException e){ - e.printStackTrace(); - } - return buffer; - } - - public static void main(String[] args) { - AliPayUtil util = new AliPayUtil(); -// String token = getAppAuthToken("Pfbe94a5103a0414db99ce865204ee63"); -// System.out.println(token); - //File file = new File("C://logo-img.png"); - //System.out.println(util.merchantImageUpload("202104BB054c88e950ba4513854e4275ff71cF63", "aa.jpg", File2byte(file))); - //System.out.println(util.createSmartDistrictMemberCardModel("202104BB054c88e950ba4513854e4275ff71cF63", "会员卡", "OKJx3oOPTUOaINs0AQ_qMgAAACMAAQQD", "OKJx3oOPTUOaINs0AQ_qMgAAACMAAQQD")); - //System.out.println(util.setSmartDistrictMemberCardModelConfig("202104BB054c88e950ba4513854e4275ff71cF63", "20210417000000002702655000300637")); - //System.out.println(util.getSmartDistrictMemberCardUrl("202104BB054c88e950ba4513854e4275ff71cF63", "20210417000000002702655000300637", "https://ctest.malls.iformall.com/C/api/alipay/callback", "123")); - //System.out.println(util.getH5SmartDistrictMallVipPointsUrl("2021002139648762", "https://ctest.malls.iformall.com/C/api/alipay/callback", "123")); - System.out.println(util.smartDistrictTopicSubscribe("202104BB054c88e950ba4513854e4275ff71cF63","alipay.business.mall.trade.success")); - } - -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/AliPayApi.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/AliPayApi.java deleted file mode 100644 index 7a96f7c..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/AliPayApi.java +++ /dev/null @@ -1,319 +0,0 @@ -package com.iformall.service.pay.alipay.api; - -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.lang3.StringUtils; - -import com.alibaba.fastjson.JSON; -import com.alipay.easysdk.base.image.models.AlipayOfflineMaterialImageUploadResponse; -import com.alipay.easysdk.base.oauth.models.AlipaySystemOauthTokenResponse; -import com.alipay.easysdk.factory.Factory; -import com.alipay.easysdk.kernel.Config; -import com.alipay.easysdk.util.generic.models.AlipayOpenApiGenericResponse; -import com.iformall.common.IdWorker; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelColumn; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelFieldRule; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelRequest; -import com.iformall.service.pay.alipay.api.reqEntity.AlipayMemberCardModelStyle; -import com.iformall.utils.DateUtils; - -/** - * SDK说明 https://opendocs.alipay.com/open/54/00y8k9 - * 综合体支付积分https://opendocs.alipay.com/open/01lsmc?scene=SC00001296 - * @author alascor - */ -public class AliPayApi { - - /** - * https://opendocs.alipay.com/open/291/105971 - * @param - * appId:应用ID, isv模式则为第三方应用ID, 非isv模式则为自研应用ID - * appPrivateKey: 应用私钥字符串,isv模式则为第三方应用私钥, 非isv模式则为自研应用私钥。产生地址为https://miniu.alipay.com/keytool/create - * appPublicKeyCertPath: 应用公钥文件本地地址。isv模式则为第三方应用公钥文件本地地址, 非isv模式则为自研应用公钥文件本地地址。 获取路径:https://open.alipay.com/dev/workspace/key-manage,"接口加签方式:"设置里面下载 - * alipayCertPath: 支付宝公钥证书文件路径. isv模式则为第三方应用支付宝公钥证书文件路径, 非isv模式则为自研应用支付宝公钥证书文件路径。 - * alipayRootCertPath: 支付宝根证书文件路径.isv模式则为第三方应用支付宝根证书文件路径, 非isv模式则为自研应用支付宝根证书文件路径。 - * @return - */ - public static Config getOptions(String appId,String appPrivateKey,String appPublicKeyCertPath,String alipayCertPath,String alipayRootCertPath) { - Config config = new Config(); - config.protocol = "https"; - config.gatewayHost = "openapi.alipay.com"; - config.signType = "RSA2"; - - config.appId = appId; - - // 为避免私钥随源码泄露,推荐从文件中读取私钥字符串而不是写入源码中 - config.merchantPrivateKey = appPrivateKey; - - //#注:证书文件路径支持设置为文件系统中的路径或CLASS_PATH中的路径,优先从文件系统中加载,加载失败后会继续尝试从CLASS_PATH中加载 - config.merchantCertPath = appPublicKeyCertPath; - config.alipayCertPath = alipayCertPath; - config.alipayRootCertPath = alipayRootCertPath; - - //#####注:如果采用非证书模式,则无需赋值上面的三个证书路径,改为赋值如下的支付宝公钥字符串即可 - //config.alipayPublicKey = appPublicKey; - - //可设置异步通知接收服务地址(可选) - //config.notifyUrl = "<-- 请填写您的支付类接口异步通知接收服务地址,例如:https://www.test.com/callback -->"; - - //可设置AES密钥,调用AES加解密相关接口时需要(可选) - //config.encryptKey = "<-- 请填写您的AES密钥,例如:aa4BtZ4tspm2wnXLb1ThQA== -->"; - - return config; - } - - /** - * https://opendocs.alipay.com/open/common/105193 - * 第三方应用授权 - * @throws UnsupportedEncodingException - */ - public static String getAppAuthUrl(Config config,String callback,String param) throws UnsupportedEncodingException { - String paramstr = ""; - if (!StringUtils.isBlank(param)) { - paramstr = "&state="+param; - } - return "https://openauth.alipay.com/oauth2/appToAppBatchAuth.htm?app_id="+config.appId+"&application_type=TINYAPP,WEBAPP,MOBILEAPP,PUBLICAPP&redirect_uri="+URLEncoder.encode(callback, "utf-8")+paramstr; - } - - /** - * https://opendocs.alipay.com/open/common/105193 - * https://opendocs.alipay.com/apis/api_9/alipay.open.auth.token.app - * 换取应用授权令牌(非ISV模式) - * @throws Exception - */ -// public static AlipaySystemOauthTokenResponse getAppAuthToken(Config config,String appAuthCode) throws Exception { -// Factory.setOptions(config); -// AlipaySystemOauthTokenResponse response = Factory.Base.OAuth().getToken(appAuthCode); -// return response; -// } - - /** - * https://opendocs.alipay.com/support/01ratr - * https://opendocs.alipay.com/apis/api_9/alipay.open.auth.token.app - * 换取应用授权令牌(ISV模式) - * @throws Exception - */ - public static AlipayOpenApiGenericResponse getAppAuthToken(Config config,String appAuthCode) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - //Map textParams = new HashMap(); - //textParams.put("app_auth_token", appAuthToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - bizParams.put("grant_type","authorization_code"); - bizParams.put("code",appAuthCode); - AlipayOpenApiGenericResponse response = Factory.Util.Generic() - .execute("alipay.open.auth.token.app", null, bizParams); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_3/alipay.offline.material.image.upload - * 上传门店照片和视频接口 - * @throws Exception - */ - public static AlipayOfflineMaterialImageUploadResponse uploadMerchantImage(Config config,String appAuthToken,String imageName,String localImagePath) throws Exception { - Factory.setOptions(config); - AlipayOfflineMaterialImageUploadResponse response = Factory.Base.Image().agent(appAuthToken).upload(imageName, localImagePath); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_5/alipay.marketing.card.template.create - * 会员卡模板创建 - * @throws Exception - */ - public static AlipayOpenApiGenericResponse createMemberCardModel(Config config,String appAuthToken,AlipayMemberCardModelRequest modelRequest) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - IdWorker idWorker = IdWorker.get(); - bizParams.put("request_id", String.valueOf(idWorker.nextId())); - bizParams.put("card_type", modelRequest.getCard_type()); - bizParams.put("biz_no_suffix_len",modelRequest.getBiz_no_suffix_len()); - bizParams.put("write_off_type", modelRequest.getWrite_off_type()); - - AlipayMemberCardModelStyle style = modelRequest.getTemplate_style_info(); - bizParams.put("template_style_info", style); - - List columnList = modelRequest.getColumn_info_list(); - bizParams.put("column_info_list", columnList); - - List ruleList = modelRequest.getField_rule_list(); - bizParams.put("field_rule_list", ruleList); - - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.marketing.card.template.create", textParams, bizParams); - return response; - - } - - /** - * https://opendocs.alipay.com/apis/api_5/alipay.marketing.card.formtemplate.set - * 会员卡开卡表单模板配置 - * @throws Exception - */ - public static AlipayOpenApiGenericResponse setMemberCardModelConfig(Config config,String appAuthToken,String templateId,String[] requiredFields,String[] optionalFields) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - bizParams.put("template_id", templateId); - Map extendParams = new HashMap<>(); - Map requireds = new HashMap(); - requireds.put("common_fields", requiredFields); - extendParams.put("required", JSON.toJSONString(requireds)); - if (null != optionalFields) { - Map optional = new HashMap(); - optional.put("common_fields", optionalFields); - extendParams.put("optional", JSON.toJSONString(optional)); - } - bizParams.put("fields", extendParams); - - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.marketing.card.formtemplate.set", textParams, bizParams); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_5/alipay.marketing.card.activateurl.apply - * 获取会员卡领卡投放链接 - * @param callback为子应用回调地址,非ISV应用。 必须跟子应用的后台回调弟子配置一致。 - */ - public static AlipayOpenApiGenericResponse getMemberCardUrl(Config config,String appAuthToken,String templateId,String exparam,String callback) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - bizParams.put("template_id", templateId); - bizParams.put("out_string", exparam); - bizParams.put("callback", callback); - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.marketing.card.activateurl.apply", textParams, bizParams); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_9/alipay.system.oauth.token - * 会员授权,换取授权访问令牌 - * @return - * @throws Exception - */ - public static AlipayOpenApiGenericResponse queryUserAuthData(Config config,String appAuthToken,String authCode) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - textParams.put("grant_type", "authorization_code"); - textParams.put("code", authCode); - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.system.oauth.token", textParams, null); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_5/alipay.marketing.card.activateform.query - * 查询用户提交的会员卡表单信息 - * @return - * @throws Exception - */ - public static AlipayOpenApiGenericResponse queryUserFormData(Config config,String appAuthToken,String authToken,String templateId,String requestId) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - textParams.put("auth_token", authToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - bizParams.put("biz_type", "MEMBER_CARD"); - bizParams.put("template_id", templateId); - bizParams.put("request_id", requestId); - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.marketing.card.activateform.query", textParams, bizParams); - return response; - } - - /** - * https://opendocs.alipay.com/apis/api_5/alipay.marketing.card.open - * 会员卡开卡 - * @return - * @throws Exception - */ - public static AlipayOpenApiGenericResponse openCard(Config config,String appAuthToken,String authToken,String templateId,String userId) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - Map textParams = new HashMap(); - textParams.put("app_auth_token", appAuthToken); - textParams.put("auth_token", authToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - IdWorker idWorker = IdWorker.get(); - bizParams.put("out_serial_no", String.valueOf(idWorker.nextId())); - bizParams.put("card_template_id", templateId); - - Map userInfoMap = new HashMap(); - userInfoMap.put("user_uni_id", userId); - userInfoMap.put("user_uni_id_type", "UID"); - bizParams.put("card_user_info", userInfoMap); - - Map extInfoMap = new HashMap(); - extInfoMap.put("open_date", new Date()); - extInfoMap.put("valid_date", DateUtils.stringToDate("2051-05-01 00:00:00",DateUtils.DATE_TIME_PATTERN)); - extInfoMap.put("external_card_no",String.valueOf(idWorker.nextId())); - bizParams.put("card_ext_info", extInfoMap); - - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.marketing.card.open", textParams, bizParams); - return response; - } - - - /** - * https://opendocs.alipay.com/apis/api_9/alipay.open.app.message.topic.subscribe - * 订阅消息主题 - * - * 需要联系BD 给商圈挂载“支付宝商圈交易成功信息订阅”功能包 - * https://openhome.alipay.com/svr/ability/solution/SC00001010/xxdy (对接会员卡的应用AppId用ISV的应用ID) - * - * @return - * @throws Exception - */ - public static AlipayOpenApiGenericResponse topicSubscribe(Config config,String authToken,String authType,String topic,String type,String tag) throws Exception { - Factory.setOptions(config); - //设置系统参数(OpenAPI中非biz_content里的参数) - //Map textParams = new HashMap(); - //textParams.put("app_auth_token", appAuthToken); - - //设置业务参数(OpenAPI中biz_content里的参数) - Map bizParams = new HashMap(); - bizParams.put("auth_token", authToken); - bizParams.put("auth_type", authType); - bizParams.put("topic", topic); - bizParams.put("comm_type", type); - if (!StringUtils.isBlank(tag)) { - bizParams.put("tag",tag); - } - AlipayOpenApiGenericResponse response = Factory.Util.Generic().execute( - "alipay.open.app.message.topic.subscribe", null, bizParams); - return response; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/enums/EnumMemberCardConfig.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/enums/EnumMemberCardConfig.java deleted file mode 100644 index 9231872..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/enums/EnumMemberCardConfig.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.iformall.service.pay.alipay.api.enums; - - -/** - * @author gongbiao - */ -public enum EnumMemberCardConfig { - - OPEN_FORM_FIELD_MOBILE("OPEN_FORM_FIELD_MOBILE", "手机号"), - OPEN_FORM_FIELD_GENDER("OPEN_FORM_FIELD_GENDER", "性别"), - OPEN_FORM_FIELD_NAME("OPEN_FORM_FIELD_NAME", "姓名"); - - public static EnumMemberCardConfig getEnum(String code) { - for (EnumMemberCardConfig value : values()) { - if (value.getCode().equals(code)) { - return value; - } - } - return null; - } - - private String code; - private String message; - - EnumMemberCardConfig(String code, String message) { - this.code = code; - this.message = message; - } - - public String getCode() { - return code; - } - - public String getMessage() { - return message; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelColumn.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelColumn.java deleted file mode 100644 index 16a569a..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelColumn.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.iformall.service.pay.alipay.api.reqEntity; - -import com.aliyun.tea.TeaModel; - -public class AlipayMemberCardModelColumn{ - - private String code;//标准栏位:行为由支付宝统一定,同时已经分配标准Code - private String title;//栏目的标题 - public String getCode() { - return code; - } - public void setCode(String code) { - this.code = code; - } - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelFieldRule.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelFieldRule.java deleted file mode 100644 index e1847ec..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelFieldRule.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.iformall.service.pay.alipay.api.reqEntity; - -import com.aliyun.tea.TeaModel; - -public class AlipayMemberCardModelFieldRule{ - - private String field_name;//字段名称,现在支持如下几个Key(暂不支持自定义) - private String rule_name;//规则名 - private String rule_value;//根据rule_name,采取相应取值策略 - public String getField_name() { - return field_name; - } - public void setField_name(String field_name) { - this.field_name = field_name; - } - public String getRule_name() { - return rule_name; - } - public void setRule_name(String rule_name) { - this.rule_name = rule_name; - } - public String getRule_value() { - return rule_value; - } - public void setRule_value(String rule_value) { - this.rule_value = rule_value; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelRequest.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelRequest.java deleted file mode 100644 index 86d5ffe..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelRequest.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.iformall.service.pay.alipay.api.reqEntity; - -import java.util.List; - -import com.aliyun.tea.NameInMap; -import com.aliyun.tea.Validation; - -public class AlipayMemberCardModelRequest{ - - private String card_type="OUT_MEMBER_CARD";//卡类型。可选类型如下:OUT_MEMBER_CARD:外部权益卡 - private String biz_no_suffix_len ="8";//业务卡号后缀的长度,取值范围为[8,32] - private String write_off_type = "qrcode";//卡包详情页面中展现出的卡码 - private AlipayMemberCardModelStyle template_style_info;//模板样式信息 - private List column_info_list;//栏位信息 - private List field_rule_list;//字段规则列表,会员卡开卡过程中,会员卡信息的生成规则 - public String getCard_type() { - return card_type; - } - public void setCard_type(String card_type) { - this.card_type = card_type; - } - public String getBiz_no_suffix_len() { - return biz_no_suffix_len; - } - public void setBiz_no_suffix_len(String biz_no_suffix_len) { - this.biz_no_suffix_len = biz_no_suffix_len; - } - public String getWrite_off_type() { - return write_off_type; - } - public void setWrite_off_type(String write_off_type) { - this.write_off_type = write_off_type; - } - public AlipayMemberCardModelStyle getTemplate_style_info() { - return template_style_info; - } - public void setTemplate_style_info(AlipayMemberCardModelStyle template_style_info) { - this.template_style_info = template_style_info; - } - public List getColumn_info_list() { - return column_info_list; - } - public void setColumn_info_list(List column_info_list) { - this.column_info_list = column_info_list; - } - public List getField_rule_list() { - return field_rule_list; - } - public void setField_rule_list(List field_rule_list) { - this.field_rule_list = field_rule_list; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelStyle.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelStyle.java deleted file mode 100644 index b88f1fb..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/reqEntity/AlipayMemberCardModelStyle.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.iformall.service.pay.alipay.api.reqEntity; - -import com.aliyun.tea.TeaModel; - -public class AlipayMemberCardModelStyle{ - - private String card_show_name;//钱包端显示名称(字符串长度) - private String logo_id;//logo的图片ID - private String background_id;//背景图片Id - private String bg_color="rgb(55,112,179)";//字体颜色(非背景色),只影响卡详情中部信息区域字体颜色 - public String getCard_show_name() { - return card_show_name; - } - public void setCard_show_name(String card_show_name) { - this.card_show_name = card_show_name; - } - public String getLogo_id() { - return logo_id; - } - public void setLogo_id(String logo_id) { - this.logo_id = logo_id; - } - public String getBackground_id() { - return background_id; - } - public void setBackground_id(String background_id) { - this.background_id = background_id; - } - public String getBg_color() { - return bg_color; - } - public void setBg_color(String bg_color) { - this.bg_color = bg_color; - } -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/result/UserAuthData.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/api/result/UserAuthData.java deleted file mode 100644 index a7b3b10..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/api/result/UserAuthData.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.iformall.service.pay.alipay.api.result; - -import lombok.Data; - -@Data -public class UserAuthData { - - private String userId; - private String accessToken; -} diff --git a/suimangService/src/main/java/com/iformall/service/pay/alipay/config/AliPayConfig.java b/suimangService/src/main/java/com/iformall/service/pay/alipay/config/AliPayConfig.java deleted file mode 100644 index 663fb9d..0000000 --- a/suimangService/src/main/java/com/iformall/service/pay/alipay/config/AliPayConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.iformall.service.pay.alipay.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; -import org.springframework.stereotype.Component; - -/** - * alipay 配置 - */ -@Data -@Configuration -@ConfigurationProperties(prefix = "alipay.open") -public class AliPayConfig { - - private String appId; - private String appPrivateKey; - private String appPublicKeyCertPath; - private String alipayCertPath; - private String alipayRootCertPath; - private String callback; - -} \ No newline at end of file diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/PayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/PayAdapterService.java index 029c5aa..1787b0e 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/PayAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/PayAdapterService.java @@ -32,11 +32,11 @@ public interface PayAdapterService { /** * 真正支付过程,调用对应端的API调用支付 * @param payAccount WxPayAccount - * @param order ProductOrder + * @param orderPay ProductOrderPay * @param appInfo C端app * @throws Exception */ - public PayAdapterResult createPay(ProductOrder order,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception; + public PayAdapterResult createPay(ProductOrderPay orderPay,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception; /** * 查询支付结果,调用对应端的API查询支付结果 @@ -49,7 +49,7 @@ public interface PayAdapterService { */ public PayQueryAdapterResult queryPayStatus(WxPayOrder oldRecord,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception; - public PayQueryAdapterResult queryPayStatus(ProductOrder order,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception; + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception; /** * 根据返回结果对象解析出支付状态 diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/BaseAliPayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/BaseAliPayAdapterService.java new file mode 100644 index 0000000..6d79b1a --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/BaseAliPayAdapterService.java @@ -0,0 +1,102 @@ +package com.iformall.service.pay.service.pay.ali; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.request.AlipayTradeQueryRequest; +import com.alipay.api.response.AlipayTradeQueryResponse; +import com.iformall.common.ErrorCode; +import com.iformall.domain.po.ProductOrderPay; +import com.iformall.domain.po.WxAppinfo; +import com.iformall.domain.po.WxPayAccount; +import com.iformall.domain.po.WxPayOrder; +import com.iformall.enums.EnumPayOrderStatus; +import com.iformall.exception.MallinkException; +import com.iformall.service.pay.service.pay.entity.PayAdapterResult; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; +import com.iformall.utils.MaUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +public class BaseAliPayAdapterService { + + @Autowired + protected MaUtil maUtil; + + /** + * 做为支付的扩展数据 + * @param + * @return + */ + protected String getCallbackData(WxPayOrder record) { + Map map = new HashMap<>(); + map.put("composeOrderId",record.getOrderId()); + map.put("tenantId",record.getTenantId()); + return JSON.toJSONString(map); + } + + protected PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) + throws Exception { + //AlipayClient alipayClient = maUtil.getAliPayClient(appInfo, payAccount); + AlipayClient alipayClient = maUtil.getAliPayCertClient(appInfo, payAccount); + AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); + JSONObject bizContent = new JSONObject(); + //商户订单号,商家自定义,保持唯一性 + bizContent.put("out_trade_no", orderPay.getOrderNumber()); + + request.setBizContent(bizContent.toString()); + try{ + //AlipayTradeQueryResponse response = alipayClient.execute(request); + AlipayTradeQueryResponse response = alipayClient.certificateExecute(request); + log.info("ali查询支付宝返回{}"+JSON.toJSONString(response)); + if(response.isSuccess()){ + if("10000".equals(response.getCode())){ + PayQueryAdapterResult result = new PayQueryAdapterResult(); + result.setCode(getPayStatusFrom(response.getTradeStatus())); + result.setTransactionId(response.getTradeNo()); + return result; + } + if("ACQ.TRADE_NOT_EXIST".equals(response.getSubCode())){ + PayQueryAdapterResult result = new PayQueryAdapterResult(); + result.setCode(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + result.setMsg(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getMessage()); + return result; + } + } + + }catch(AlipayApiException e){ + log.error("ali pay query error",e); + } + + throw new MallinkException(ErrorCode.PAY_ORDER_QUERY_ERROR); + } + + private int getPayStatusFrom(String trade_status){ + if("WAIT_BUYER_PAY".equals(trade_status)){ + return EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode(); + }else if("TRADE_CLOSED".equals(trade_status)){ + return EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode(); + }else if("TRADE_SUCCESS".equals(trade_status)){ + return EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode(); + }else if("TRADE_FINISHED".equals(trade_status)){ + return EnumPayOrderStatus.ORDER_STATUS_PAYMENT_SUCCESS.getCode(); + } + throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "订单查询支付宝支付状态失败"+trade_status); + } + + + protected int queryPayStatus(PayQueryAdapterResult statusObject, String orderOutNo) throws Exception { + return statusObject.getCode(); + } + + protected PayAdapterResult closeOrder(WxAppinfo appInfo, WxPayOrder record,WxPayAccount payAccount) { + return new PayAdapterResult(true, "success", null, null); + } + + +} diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/page/AliPagePayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/page/AliPagePayAdapterService.java new file mode 100644 index 0000000..8d303b1 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/ali/page/AliPagePayAdapterService.java @@ -0,0 +1,160 @@ +package com.iformall.service.pay.service.pay.ali.page; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.request.AlipayTradePagePayRequest; +import com.alipay.api.response.AlipayTradePagePayResponse; +import com.iformall.common.ErrorCode; +import com.iformall.domain.po.*; +import com.iformall.enums.*; +import com.iformall.exception.MallinkException; +import com.iformall.service.order.OrderFactory; +import com.iformall.service.order.entity.WxComposeOrder; +import com.iformall.service.pay.entity.PayExtraParam; +import com.iformall.service.pay.service.pay.CDrivingPayService; +import com.iformall.service.pay.service.pay.ali.BaseAliPayAdapterService; +import com.iformall.service.pay.service.pay.entity.PayAdapterResult; +import com.iformall.service.pay.service.pay.entity.PayQueryAdapterResult; +import com.iformall.utils.DateUtils; +import com.iformall.utils.MaUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.io.File; +import java.util.*; + +@Slf4j +@Service +public class AliPagePayAdapterService extends BaseAliPayAdapterService implements CDrivingPayService{ + + @Autowired + OrderFactory orderFactory; + + @Autowired + private MaUtil maUtil; + + @Override + public PayAdapterResult pay(WxPayAccount payAccount,WxPayOrder record,WxComposeOrder composeOrder,List childOrders, + String productName,EnumPayShare isShare,WxAppinfo appInfo,Date currentDate, PayExtraParam params) throws Exception { + + return null; + } + + //https://opendocs.alipay.com/open/270/105898 + //https://opendocs.alipay.com/open/270/01didh?ref=api + @Override + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + + //AlipayClient alipayClient = maUtil.getAliPayClient(appInfo, payAccount); + AlipayClient alipayClient = maUtil.getAliPayCertClient(appInfo, payAccount); + AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); + //异步接收地址,仅支持http/https,公网可访问 + request.setNotifyUrl(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/aliNotify"); + //同步跳转地址,仅支持http/https +// request.setReturnUrl(""); + /******必传参数******/ + JSONObject bizContent = new JSONObject(); + //商户订单号,商家自定义,保持唯一性 + bizContent.put("out_trade_no", orderPay.getOrderNumber()); + //支付金额,最小值0.01元 + bizContent.put("total_amount", orderPay.getPayAmountStr()); + //订单标题,不可使用特殊符号 + bizContent.put("subject", orderPay.getOrderDetail()); + //电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY + bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY"); + + bizContent.put("qr_pay_mode",4); + bizContent.put("qrcode_width",200); + + + String after15 = DateUtils.date2String(DateUtils.getSecondsTimeAfter(15 * 60, new Date())); + + bizContent.put("time_expire", after15); + + request.setBizContent(bizContent.toString()); + try{ + AlipayTradePagePayResponse response = alipayClient.pageExecute(request); + log.info("ali创建支付返回{}"+ JSON.toJSONString(response)); + PayAdapterResult par = new PayAdapterResult(); + if(response.isSuccess()){ + + par.setSuccess(true); + par.setTransactionId(response.getTradeNo()); + par.setData(response); + return par; + + } + par.setSuccess(false); + par.setMsg(response.getMsg()); + return par; + }catch(AlipayApiException e){ + log.error("ali pay error",e); + throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(),e.getMessage()); + } + + + } + + @Override + public PayQueryAdapterResult queryPayStatus(WxPayOrder oldRecord, WxAppinfo appInfo, + WxPayAccount payAccount) throws Exception { + return null; + } + + @Override + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + return super.queryPayStatus(orderPay,appInfo,payAccount); + } + + @Override + public int queryPayStatus(PayQueryAdapterResult statusObject, String orderOutNo) throws Exception { + return 0; + } + + @Override + public int queryPayStatusCode(WxPayOrder oldRecord, WxAppinfo appInfo, WxPayAccount payAccount) + throws Exception { + return 0; + } + + @Override + public PayAdapterResult payOrderClose(WxAppinfo appInfo, WxPayOrder record,WxPayAccount payAccount) throws Exception { + //todo + return super.closeOrder(appInfo, record, payAccount); + } + + @Override + public PayAdapterResult payOrderReverse(WxAppinfo appInfo, WxPayOrder record, WxPayAccount payAccount) + throws Exception { + return null; + } + + @Override + public PayAdapterResult payOrderPush(String openId,WxAppinfo appInfo, WxBatchOrder batchOrder,WxPayOrder payOrder) throws Exception { + return null; + } + + @Override + public File getQrcode(WxAppinfo appinfo,String pageUrl,int type,String sceneParam) throws Exception{ + return null; + } + + @Override + public String getScheme(WxAppinfo appinfo, String pageUrl, String sceneParam, Long expireTime) throws Exception { + return null; + } + + @Override + public PayAdapterResult noCreatePay(WxPayOrder record, WxComposeOrder composeOrder, List childOrders) { + return null; + } + + @Override + public void sendSubscribeMsg(WxAppinfo appinfo, WxTemplateMsg wxTemplateMsg, String openId, String toPage, Map param) throws Exception{ + + } + +} diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/douyin/v1/miniApp/TtMiniAppPayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/douyin/v1/miniApp/TtMiniAppPayAdapterService.java index a007d5c..5eb9306 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/douyin/v1/miniApp/TtMiniAppPayAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/douyin/v1/miniApp/TtMiniAppPayAdapterService.java @@ -227,18 +227,18 @@ public class TtMiniAppPayAdapterService extends BaseTtPayAdapterService implemen } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { DouYinCreatePreOrder preOrder = new DouYinCreatePreOrder(); preOrder.setAppId(appInfo.getAppId()); preOrder.setSercrect(appInfo.getSecret()); preOrder.setSalt(payAccount.getMerchantApiKey()); - preOrder.setOutOrderNo(order.getOrderNumber()); - preOrder.setTotalAmount(order.getOrderPrice()); - preOrder.setSubject(appInfo.getName()+"-"+order.getProductTitle()); - preOrder.setBody(appInfo.getName()+"-"+order.getProductTitle()); + preOrder.setOutOrderNo(orderPay.getOrderNumber()); + preOrder.setTotalAmount(orderPay.getPayAmount()); + preOrder.setSubject(appInfo.getName()+"-"+orderPay.getOrderDetail()); + preOrder.setBody(appInfo.getName()+"-"+orderPay.getOrderDetail()); preOrder.setValidTime(60*60); -// preOrder.setNotifyUrl();//回调地址 + preOrder.setNotifyUrl(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/ttNotify");//回调地址 // preOrder.setThirdpartyId();//第三方服务商ID // preOrder.setStoreId(record.getStoreId()); CreatePreOrderResult preOrderResult = DouYinPayHelper.createPreOrder(preOrder); @@ -258,12 +258,12 @@ public class TtMiniAppPayAdapterService extends BaseTtPayAdapterService implemen } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { - OrderQueryResult orderQueryResult = DouYinPayHelper.orderQuery(appInfo.getAppId(), payAccount.getMerchantApiKey(), order.getOrderNumber(), null); - int code = DouYinPayHelper.getPayStatusFromOrderQueryResult(orderQueryResult,order.getOrderNumber()); + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + OrderQueryResult orderQueryResult = DouYinPayHelper.orderQuery(appInfo.getAppId(), payAccount.getMerchantApiKey(), orderPay.getOrderNumber(), null); + int code = DouYinPayHelper.getPayStatusFromOrderQueryResult(orderQueryResult,orderPay.getOrderNumber()); PayQueryAdapterResult result = new PayQueryAdapterResult(); result.setCode(code); - result.setMsg(EnumProductOrderStatus.getEnum(code).getMessage()); + result.setMsg(EnumPayOrderStatus.getEnum(code).getMessage()); result.setTransactionId(orderQueryResult.getChannelNo()); result.setWay(orderQueryResult.getWay()); if(StringUtils.isNotBlank(orderQueryResult.getPayTime())){ diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/h5/WxH5PaySFTService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/h5/WxH5PaySFTService.java index 3bc9edb..3dbf653 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/h5/WxH5PaySFTService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/h5/WxH5PaySFTService.java @@ -30,7 +30,7 @@ public class WxH5PaySFTService extends BaseWxPaySFTAdapterService implements CDr } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } @@ -42,7 +42,7 @@ public class WxH5PaySFTService extends BaseWxPaySFTAdapterService implements CDr } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/miniApp/appPay/WxMiniAppPaySFTAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/miniApp/appPay/WxMiniAppPaySFTAdapterService.java index eb360b0..8aec258 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/miniApp/appPay/WxMiniAppPaySFTAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/sft/miniApp/appPay/WxMiniAppPaySFTAdapterService.java @@ -77,7 +77,7 @@ public class WxMiniAppPaySFTAdapterService extends BaseWxPaySFTAdapterService i } req.setAttach(getAttach(record)); req.setOut_trade_no(String.valueOf(composeOrder.getMainOrderId())); - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/pay/v3"); SFTPaySettleReq settle = new SFTPaySettleReq(); settle.setProfit_sharing(true); @@ -117,7 +117,7 @@ public class WxMiniAppPaySFTAdapterService extends BaseWxPaySFTAdapterService i payer.setOpenid(openId); req.setCombine_payer_info(payer); - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/pay/v3"); return req; } @@ -195,7 +195,7 @@ public class WxMiniAppPaySFTAdapterService extends BaseWxPaySFTAdapterService i } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } @@ -267,7 +267,7 @@ public class WxMiniAppPaySFTAdapterService extends BaseWxPaySFTAdapterService i } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/h5/WxH5PayService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/h5/WxH5PayService.java index 66162b7..bef3894 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/h5/WxH5PayService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/h5/WxH5PayService.java @@ -29,7 +29,7 @@ public class WxH5PayService extends BaseWxPayV2AdapterService implements CDrivi } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } @@ -40,7 +40,7 @@ public class WxH5PayService extends BaseWxPayV2AdapterService implements CDrivi } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/appPay/WxMiniAppPayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/appPay/WxMiniAppPayAdapterService.java index 544383b..2ab0d69 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/appPay/WxMiniAppPayAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/appPay/WxMiniAppPayAdapterService.java @@ -73,7 +73,7 @@ public class WxMiniAppPayAdapterService extends BaseWxPayV2AdapterService implem wxPayOrderP.setTotal_fee(composeOrder.getPayment()); wxPayOrderP.setSpbill_create_ip(record.getIp()); // 终端IP wxPayOrderP.setGoods_tag(productName); - wxPayOrderP.setNotify_url(payAccount.getPayNotifyUrl()); + wxPayOrderP.setNotify_url(payAccount.getNotifyUrl() +"/pay"); wxPayOrderP.setTrade_type(WxPay.TradeType.JSAPI.name()); // 终端类型 wxPayOrderP.setProduct_id(String.valueOf(composeOrder.getMainOrderId())); // 订单ID wxPayOrderP.setTime_start(Utility.getDataFormatStringYYYYMMDDHHmmss(currentDate)); @@ -149,7 +149,7 @@ public class WxMiniAppPayAdapterService extends BaseWxPayV2AdapterService implem wxPayOrderSP.setTotal_fee(composeOrder.getPayment().toString()); wxPayOrderSP.setSpbill_create_ip(record.getIp()); // 终端IP wxPayOrderSP.setGoods_tag(productName); // 券ID - wxPayOrderSP.setNotify_url(payAccount.getPayNotifyUrl()); + wxPayOrderSP.setNotify_url(payAccount.getNotifyUrl() +"/pay"); wxPayOrderSP.setTrade_type(WxPay.TradeType.JSAPI.name()); // 终端类型 wxPayOrderSP.setProduct_id(String.valueOf(composeOrder.getMainOrderId())); // wxPayOrderSP.setTime_start(Utility.getDataFormatStringYYYYMMDDHHmmss(currentDate)); @@ -249,7 +249,7 @@ public class WxMiniAppPayAdapterService extends BaseWxPayV2AdapterService implem } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } @@ -260,7 +260,7 @@ public class WxMiniAppPayAdapterService extends BaseWxPayV2AdapterService implem } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/maPay/WxMiniMaPayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/maPay/WxMiniMaPayAdapterService.java index e018ea1..bef645b 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/maPay/WxMiniMaPayAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v2/miniApp/maPay/WxMiniMaPayAdapterService.java @@ -217,7 +217,7 @@ public class WxMiniMaPayAdapterService extends BaseWxPayV2AdapterService impleme } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } @@ -256,7 +256,7 @@ public class WxMiniMaPayAdapterService extends BaseWxPayV2AdapterService impleme } @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { return null; } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/miniApp/appPay/WxMiniAppPayV3AdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/miniApp/appPay/WxMiniAppPayV3AdapterService.java index 521b488..6ae645d 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/miniApp/appPay/WxMiniAppPayV3AdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/miniApp/appPay/WxMiniAppPayV3AdapterService.java @@ -79,7 +79,7 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl } req.setOut_trade_no(record.getPayOrderNo()); req.setAttach(getAttach(record)); - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/pay/v3"); V3PaySettleReq settle = new V3PaySettleReq(); settle.setProfit_sharing(true); @@ -96,25 +96,25 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl return req; } - private V3CreatePayReq generateCreatePayRequest(ProductOrder productOrder,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception { + private V3CreatePayReq generateCreatePayRequest(ProductOrderPay productOrderPay,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception { V3CreatePayReq req = new V3CreatePayReq(); req.setAppid(appInfo.getAppId()); req.setMchid(payAccount.getSubMchId()); try { //中文必须要这样,否则会双方签名失败 - req.setDescription(WxPayV3.handleChinese(appInfo.getName()+"-"+productOrder.getProductTitle())); + req.setDescription(WxPayV3.handleChinese(appInfo.getName()+"-"+productOrderPay.getOrderDetail())); } catch (UnsupportedEncodingException e) { req.setDescription("weixin miniApp product"); } - req.setOut_trade_no(productOrder.getOrderNumber()); - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setOut_trade_no(productOrderPay.getOrderNumber()); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/refund/v3"); V3PayAmountReq amout = new V3PayAmountReq(); - amout.setTotal(productOrder.getOrderPrice()); + amout.setTotal(productOrderPay.getPayAmount()); req.setAmount(amout); V3Payer payer = new V3Payer(); - payer.setOpenid(productOrder.getOpenId()); + payer.setOpenid(productOrderPay.getOpenId()); req.setPayer(payer); return req; @@ -185,8 +185,7 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl V3CombinePayerReq payer = new V3CombinePayerReq(); payer.setSub_openid(openId); req.setCombine_payer_info(payer); - - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/pay/v3"); return req; } @@ -234,14 +233,14 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); - V3CreatePayReq payReq = generateCreatePayRequest(order,appInfo,payAccount); + V3CreatePayReq payReq = generateCreatePayRequest(orderPay,appInfo,payAccount); try { String response = WxPayV3.payCommonWithMiniApp(payService, payReq); - return getOrderPResult(response,payService,appInfo,payAccount,order.getOrderNumber()); + return getOrderPResult(response,payService,appInfo,payAccount,orderPay.getOrderNumber()); }catch(WxPayException e) { log.error("wexin pay v3 error",e); throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),e.getCustomErrorMsg()); @@ -277,7 +276,7 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl openid = payer.getString("openid"); } - EnumProductOrderStatus payStatus = WxPayOrderServiceHelper.getProductOrderStatus(tradeState); + EnumPayOrderStatus payStatus = WxPayOrderServiceHelper.getProductOrderStatus(tradeState); if (null == payStatus) { throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "订单查询微信支付状态非法["+tradeState+"]"); } @@ -354,18 +353,18 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl /** * 单商户模式 - * @param order + * @param orderPay * @param appInfo * @param payAccount * @return * @throws Exception */ @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); V3PayQuery req = new V3PayQuery(); req.setMchid(payAccount.getSubMchId()); - req.setOut_trade_no(order.getOrderNumber()); + req.setOut_trade_no(orderPay.getOrderNumber()); try { String response = WxPayV3.payQuery(payService, req); if (StringUtils.isBlank(response)){ @@ -377,13 +376,13 @@ public class WxMiniAppPayV3AdapterService extends BaseWxPayV3AdapterService impl log.error("pay common v3 query response error",e); if("ORDER_CLOSED".equals(e.getErrCode())){ PayQueryAdapterResult result = new PayQueryAdapterResult(); - result.setCode(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); - result.setMsg(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getMessage()); + result.setCode(EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); + result.setMsg(EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getMessage()); return result; }else if("ORDER_NOT_EXIST".equals(e.getErrCode()) || "ORDERNOTEXIST".equals(e.getErrCode())){ PayQueryAdapterResult result = new PayQueryAdapterResult(); - result.setCode(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - result.setMsg(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getMessage()); + result.setCode(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + result.setMsg(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getMessage()); return result; } throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),e.getCustomErrorMsg()); diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/nativePay/WxNativePayV3AdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/nativePay/WxNativePayV3AdapterService.java index 799d2df..94973f6 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/nativePay/WxNativePayV3AdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/pay/wx/v3/nativePay/WxNativePayV3AdapterService.java @@ -38,25 +38,25 @@ public class WxNativePayV3AdapterService extends BaseWxPayV3AdapterService imple @Autowired MaUtil maUtil; - private V3CreatePayReq generateCreatePayRequest(ProductOrder productOrder,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception { + private V3CreatePayReq generateCreatePayRequest(ProductOrderPay productOrderPay,WxAppinfo appInfo,WxPayAccount payAccount) throws Exception { V3CreatePayReq req = new V3CreatePayReq(); req.setAppid(appInfo.getAppId()); req.setMchid(payAccount.getSubMchId()); try { //中文必须要这样,否则会双方签名失败 - req.setDescription(WxPayV3.handleChinese(appInfo.getName()+"-"+productOrder.getProductTitle())); + req.setDescription(WxPayV3.handleChinese(appInfo.getName()+"-"+productOrderPay.getOrderDetail())); } catch (UnsupportedEncodingException e) { req.setDescription("weixin miniApp product"); } - req.setOut_trade_no(productOrder.getOrderNumber()); - req.setNotify_url(payAccount.getPayNotifyV3Url(appInfo.getProjectType())); + req.setOut_trade_no(productOrderPay.getOrderNumber()); + req.setNotify_url(payAccount.getNotifyUrl() + "/" + appInfo.getProjectType() +"/pay/v3"); V3PayAmountReq amout = new V3PayAmountReq(); - amout.setTotal(productOrder.getOrderPrice()); + amout.setTotal(productOrderPay.getPayAmount()); req.setAmount(amout); V3Payer payer = new V3Payer(); - payer.setOpenid(productOrder.getOpenId()); + payer.setOpenid(productOrderPay.getOpenId()); req.setPayer(payer); return req; @@ -97,17 +97,17 @@ public class WxNativePayV3AdapterService extends BaseWxPayV3AdapterService imple } @Override - public PayAdapterResult createPay(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayAdapterResult createPay(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); - V3CreatePayReq payReq = generateCreatePayRequest(order,appInfo,payAccount); + V3CreatePayReq payReq = generateCreatePayRequest(orderPay,appInfo,payAccount); try { String response = WxPayV3.payCommonNative(payService, payReq); - return getOrderPResult(response,payService,appInfo,payAccount,order.getOrderNumber()); + return getOrderPResult(response,payService,appInfo,payAccount,orderPay.getOrderNumber()); }catch(WxPayException e) { log.error("wexin pay v3 error",e); - throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),e.getCustomErrorMsg()); + throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(),e.getCustomErrorMsg()); } } @@ -140,7 +140,7 @@ public class WxNativePayV3AdapterService extends BaseWxPayV3AdapterService imple openid = payer.getString("openid"); } - EnumProductOrderStatus payStatus = WxPayOrderServiceHelper.getProductOrderStatus(tradeState); + EnumPayOrderStatus payStatus = WxPayOrderServiceHelper.getProductOrderStatus(tradeState); if (null == payStatus) { throw new MallinkException(ErrorCode.PAY_ORDER_ERROR.getCode(), "订单查询微信支付状态非法["+tradeState+"]"); } @@ -200,11 +200,11 @@ public class WxNativePayV3AdapterService extends BaseWxPayV3AdapterService imple * @throws Exception */ @Override - public PayQueryAdapterResult queryPayStatus(ProductOrder order, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { + public PayQueryAdapterResult queryPayStatus(ProductOrderPay orderPay, WxAppinfo appInfo, WxPayAccount payAccount) throws Exception { WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); V3PayQuery req = new V3PayQuery(); req.setMchid(payAccount.getSubMchId()); - req.setOut_trade_no(order.getOrderNumber()); + req.setOut_trade_no(orderPay.getOrderNumber()); try { String response = WxPayV3.payQuery(payService, req); if (StringUtils.isBlank(response)){ @@ -216,13 +216,13 @@ public class WxNativePayV3AdapterService extends BaseWxPayV3AdapterService imple log.error("pay common v3 query response error",e); if("ORDER_CLOSED".equals(e.getErrCode())){ PayQueryAdapterResult result = new PayQueryAdapterResult(); - result.setCode(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); - result.setMsg(EnumProductOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getMessage()); + result.setCode(EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getCode()); + result.setMsg(EnumPayOrderStatus.ORDER_STATUS_OVERTIME_CANCEL.getMessage()); return result; }else if("ORDER_NOT_EXIST".equals(e.getErrCode()) || "ORDERNOTEXIST".equals(e.getErrCode())){ PayQueryAdapterResult result = new PayQueryAdapterResult(); - result.setCode(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); - result.setMsg(EnumProductOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getMessage()); + result.setCode(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getCode()); + result.setMsg(EnumPayOrderStatus.ORDER_STATUS_PENDING_PAYMENT.getMessage()); return result; } throw new MallinkException(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(),e.getCustomErrorMsg()); diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/RefundPayAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/RefundPayAdapterService.java index 7bb406a..6960df2 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/refund/RefundPayAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/RefundPayAdapterService.java @@ -2,10 +2,7 @@ package com.iformall.service.pay.service.refund; import java.util.Map; -import com.iformall.domain.po.WxAppinfo; -import com.iformall.domain.po.WxPayAccount; -import com.iformall.domain.po.WxPayOrder; -import com.iformall.domain.po.WxRefundOrder; +import com.iformall.domain.po.*; import com.iformall.enums.EnumPayType; import com.iformall.enums.EnumPayWay; import com.iformall.service.pay.service.refund.entity.RefundAdapterResult; @@ -23,6 +20,8 @@ public interface RefundPayAdapterService { * @return */ public RefundAdapterResult refund(WxPayAccount payAccount,WxAppinfo appInfo,WxRefundOrder record,WxPayOrder payOrder,Long orderId,EnumPayType payType); + + public RefundAdapterResult refund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund); /** * API查询退款 @@ -32,11 +31,7 @@ public interface RefundPayAdapterService { * @return */ public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, WxRefundOrder record); - - /** - * 平台方 异步通知 - * @param paramMap - * @param payWay - */ - public RefundNotifyAdapterResult notify(Map paramMap, EnumPayWay payWay); + + public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, ProductOrderRefund orderRefund); + } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/ali/AliRefundAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/ali/AliRefundAdapterService.java new file mode 100644 index 0000000..8dd0d60 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/ali/AliRefundAdapterService.java @@ -0,0 +1,137 @@ +package com.iformall.service.pay.service.refund.ali; + + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest; +import com.alipay.api.request.AlipayTradeRefundRequest; +import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse; +import com.alipay.api.response.AlipayTradeRefundResponse; +import com.iformall.common.ErrorCode; +import com.iformall.domain.po.*; +import com.iformall.douyin.pay.TtPayService; +import com.iformall.douyin.pay.exception.TtPayException; +import com.iformall.douyin.payv2.request.TtPayRefundQueryV2Request; +import com.iformall.douyin.payv2.request.TtPayRefundV2Request; +import com.iformall.douyin.payv2.result.TtPayRefundQueryV2Result; +import com.iformall.douyin.payv2.result.TtPayRefundV2Result; +import com.iformall.enums.EnumPayType; +import com.iformall.enums.EnumPayWay; +import com.iformall.enums.EnumRefundOrderStatus; +import com.iformall.enums.EnumRefundStatus; +import com.iformall.exception.MallinkException; +import com.iformall.mapper.WxPayOrderMapper; +import com.iformall.mapper.WxRefundOrderMapper; +import com.iformall.service.WxAppinfoService; +import com.iformall.service.WxOrderService; +import com.iformall.service.WxPayAccountService; +import com.iformall.service.pay.service.refund.RefundPayAdapterService; +import com.iformall.service.pay.service.refund.entity.RefundAdapterResult; +import com.iformall.service.pay.service.refund.entity.RefundNotifyAdapterResult; +import com.iformall.utils.Constant; +import com.iformall.utils.MaUtil; +import com.iformall.utils.XmlUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +@Slf4j +@Service +public class AliRefundAdapterService implements RefundPayAdapterService{ + + @Autowired + MaUtil maUtil; + + /** + * 做为分账的扩展数据 + * @param + * @return + */ + protected String getCpExtra(WxRefundOrder record) { + Map map = new HashMap<>(); + map.put("tenantId",record.getTenantId()); + return JSON.toJSONString(map); + } + + @Override + public RefundAdapterResult refund(WxPayAccount payAccount,WxAppinfo appInfo,WxRefundOrder record,WxPayOrder payOrder,Long orderId,EnumPayType payType) { + return null; + } + + @Override + public RefundAdapterResult refund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + AlipayClient aliPayClient = maUtil.getAliPayClient(appInfo, payAccount); + AlipayTradeRefundRequest request = new AlipayTradeRefundRequest(); + JSONObject bizContent = new JSONObject(); + bizContent.put("out_trade_no", orderRefund.getOrderNumber()); + bizContent.put("refund_amount", orderRefund.getRefundAmountStr()); + bizContent.put("refund_reason", orderRefund.getRefundDescription()); + bizContent.put("out_request_no", orderRefund.getId().toString()); + + //// 返回参数选项,按需传入 + //JSONArray queryOptions = new JSONArray(); + //queryOptions.add("refund_detail_item_list"); + //bizContent.put("query_options", queryOptions); + + request.setBizContent(bizContent.toString()); + + try { + AlipayTradeRefundResponse response = aliPayClient.execute(request); + if(response.isSuccess()){ + if("10000".equals(response.getCode())){ + RefundAdapterResult refundAdapterResult = new RefundAdapterResult(); + refundAdapterResult.setSuccess(true); + refundAdapterResult.setCode(EnumRefundStatus.REFUND_REQ_SUCCESS.getCode()); + refundAdapterResult.setData(response); + return refundAdapterResult; + } + } + return new RefundAdapterResult(false,EnumRefundStatus.REFUND_REQ_FAIL.getCode(),response.getMsg(),response); + } catch (AlipayApiException e) { + log.error("支付宝退款失败{}"+e.getMessage()); + e.printStackTrace(); + return new RefundAdapterResult(false,EnumRefundStatus.REFUND_REQ_FAIL.getCode(),EnumRefundStatus.REFUND_REQ_FAIL.getMessage(),null); + } + } + + @Override + public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, WxRefundOrder record) { + return null; + } + + @Override + public RefundAdapterResult queryRefund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + AlipayClient aliPayClient = maUtil.getAliPayClient(appInfo, payAccount); + AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest(); + JSONObject bizContent = new JSONObject(); + bizContent.put("out_trade_no", orderRefund.getOrderNumber()); + bizContent.put("out_request_no", orderRefund.getId()); + + //// 返回参数选项,按需传入 + //JSONArray queryOptions = new JSONArray(); + //queryOptions.add("refund_detail_item_list"); + //bizContent.put("query_options", queryOptions); + + request.setBizContent(bizContent.toString()); + try { + AlipayTradeFastpayRefundQueryResponse response = aliPayClient.execute(request); + if(response.isSuccess()){ + if("REFUND_SUCCESS".equals(response.getRefundStatus())){ + return new RefundAdapterResult(true, EnumRefundOrderStatus.REFUND_SUCCESS.getCode(),"退款成功",response); + } + return new RefundAdapterResult(false,EnumRefundOrderStatus.REFUND_FAIL.getCode(),"退款失败",response); + } + } catch (AlipayApiException e) { + e.printStackTrace(); + log.error("查询支付宝退款结果失败"+e.getMessage()); + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(),e.getMessage()); + } + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR); + } + +} diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/douyin/TtRefundAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/douyin/TtRefundAdapterService.java index 58d4d06..dc95748 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/refund/douyin/TtRefundAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/douyin/TtRefundAdapterService.java @@ -16,6 +16,7 @@ import com.iformall.douyin.payv2.result.TtPayRefundQueryV2Result; import com.iformall.douyin.payv2.result.TtPayRefundV2Result; import com.iformall.enums.EnumPayType; import com.iformall.enums.EnumPayWay; +import com.iformall.enums.EnumRefundOrderStatus; import com.iformall.enums.EnumRefundStatus; import com.iformall.exception.MallinkException; import com.iformall.mapper.WxPayAccountMapper; @@ -121,7 +122,33 @@ public class TtRefundAdapterService implements RefundPayAdapterService{ // } } - @Override + @Override + public RefundAdapterResult refund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + + CreateRefund createRefund = new CreateRefund(); + createRefund.setAppId(appInfo.getAppId()); + createRefund.setSalt(payAccount.getApiKey()); + createRefund.setOutOrderNo(orderRefund.getOrderNumber()); + createRefund.setOutRefundNo(orderRefund.getId().toString()); + createRefund.setReason(orderRefund.getRefundReason()); + createRefund.setRefundAmount(orderRefund.getRefundAmount()); + + + CreateRefundResult refund = DouYinPayHelper.createRefund(createRefund); + if(refund.isSuccess()){ + RefundAdapterResult refundAdapterResult = new RefundAdapterResult(); + refundAdapterResult.setSuccess(true); + refundAdapterResult.setCode(EnumRefundStatus.REFUND_REQ_SUCCESS.getCode()); + refundAdapterResult.setRefundId(refund.getRefundNo()); + refundAdapterResult.setData(refund); + + return refundAdapterResult; + }else{ + return new RefundAdapterResult(false,EnumRefundStatus.REFUND_REQ_FAIL.getCode(),refund.getMsg(),refund); + } + } + + @Override public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, WxRefundOrder record) { try { TtPayService ttPayService = maUtil.getTtPayService(appInfo, payAccount); @@ -146,78 +173,21 @@ public class TtRefundAdapterService implements RefundPayAdapterService{ throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(),"查询状态异常"); } - -// QueryRefundResult queryRefundResult = DouYinPayHelper.refundQuery(appInfo.getAppId(), payAccount.getApiKey(), String.valueOf(record.getId()), null); -// if(queryRefundResult != null){ -// if("SUCCESS".equals(queryRefundResult.getRefundStatus())){ -// return new RefundAdapterResult(true,0,"退款",queryRefundResult); -// }else{ -// return new RefundAdapterResult(false,ErrorCode.REFUND_ORDER_ERROR.getCode(),"退款失败",queryRefundResult); -// } -// }else{ -// throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR); -// } } - @Autowired - WxAppinfoService wxAppinfoService; - @Autowired - WxPayAccountService wxPayAccountService; - @Autowired - WxPayOrderMapper wxPayOrderMapper; - @Autowired - WxRefundOrderMapper wxRefundOrderMapper; - - - private RefundNotifyAdapterResult notifyErrorResult(String msg) { - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", msg); - return new RefundNotifyAdapterResult(false,ErrorCode.REFUND_ORDER_ERROR.getCode(),msg,XmlUtil.getRequestXml(resultMap)); - } - - private RefundNotifyAdapterResult notifySuccessResult(String transactionId,String refundId,WxRefundOrder refundOrder) { - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "SUCCESS"); - resultMap.put("return_msg", "OK"); - return new RefundNotifyAdapterResult(transactionId, refundId,refundOrder,XmlUtil.getRequestXml(resultMap)); - } - - - @Override - public RefundNotifyAdapterResult notify(Map paramMap, EnumPayWay payWay) { - log.info("TtRefundAdapterService notify{}"+paramMap); - String tenantId = paramMap.get("tenantId"); - /** - * - */ - String refundno = paramMap.get("cp_refundno"); - Long refundOrderId = Long.valueOf(refundno); - WxRefundOrder refundOrder = wxRefundOrderMapper.selectById(refundOrderId); - - String appId = paramMap.get("appid"); - WxAppinfo appinfo = wxAppinfoService.getByAppIdFromRedis(appId,tenantId); - if (appinfo == null) { - log.error("未找到appid信息:" + appId); - throw new MallinkException(ErrorCode.APP_ID_NOT_FOUND); - } - WxPayAccount payAccount = wxPayAccountService.getByIdFromRedis(appinfo.getPayId()); - if (payAccount == null) { - log.error("未找到mch_id信息:" + appId); - throw new MallinkException(ErrorCode.MCH_INFO_NOT_FOUND); - } - if (!"SUCCESS".equals(paramMap.get("status"))) { - log.error("notify refund, wxpay status not success, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单状态码非SUCCESS"); + @Override + public RefundAdapterResult queryRefund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + QueryRefundResult queryRefundResult = DouYinPayHelper.refundQuery(appInfo.getAppId(), payAccount.getApiKey(), String.valueOf(orderRefund.getId()), null); + if(queryRefundResult != null){ + if("SUCCESS".equals(queryRefundResult.getRefundStatus())){ + return new RefundAdapterResult(true, EnumRefundOrderStatus.REFUND_SUCCESS.getCode(),"退款成功",queryRefundResult); + }else{ + return new RefundAdapterResult(false,EnumRefundOrderStatus.REFUND_FAIL.getCode(),"退款失败",queryRefundResult); + } + }else{ + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR); } + } - // 验证退款金额 - if (!paramMap.get("refund_amount").equals(refundOrder.getRefundFee().toString())) { - log.error("notify refund, wxpay check refund_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款总金额不一致"); - } - log.info("notify refund, wxpay checksign success, paramMap:{}, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifySuccessResult(refundOrder.getPayOrderNo(), paramMap.get("cp_refundno"), refundOrder); - } } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/entity/RefundAdapterResult.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/entity/RefundAdapterResult.java index e4e8dd4..756abb4 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/refund/entity/RefundAdapterResult.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/entity/RefundAdapterResult.java @@ -8,6 +8,7 @@ public class RefundAdapterResult implements Serializable{ private Integer code; private String msg; private Object data; + private String refundId; public RefundAdapterResult() { @@ -48,4 +49,11 @@ public class RefundAdapterResult implements Serializable{ this.code = code; } + public String getRefundId() { + return refundId; + } + public void setRefundId(String refundId) { + this.refundId = refundId; + } + } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v2/WxRefundAdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v2/WxRefundAdapterService.java index b047c3a..d20bcb7 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v2/WxRefundAdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v2/WxRefundAdapterService.java @@ -5,6 +5,7 @@ import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; +import com.iformall.domain.po.*; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -14,10 +15,6 @@ import com.alibaba.fastjson.JSONObject; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; -import com.iformall.domain.po.WxAppinfo; -import com.iformall.domain.po.WxPayAccount; -import com.iformall.domain.po.WxPayOrder; -import com.iformall.domain.po.WxRefundOrder; import com.iformall.enums.EnumPayMode; import com.iformall.enums.EnumPayType; import com.iformall.enums.EnumPayWay; @@ -227,7 +224,7 @@ public class WxRefundAdapterService implements RefundPayAdapterService{ wxRefundOrderP.setRefund_desc("用户自己退款"); } } - wxRefundOrderP.setNotify_url(payAccount.getRefundNotifyUrl()); + wxRefundOrderP.setNotify_url(payAccount.getNotifyUrl() +"/refund"); return wxRefundOrderP; } @@ -298,7 +295,7 @@ public class WxRefundAdapterService implements RefundPayAdapterService{ wxRefundOrderSP.setRefund_desc("用户自己退款"); } } - wxRefundOrderSP.setNotify_url(payAccount.getRefundNotifyUrl()); + wxRefundOrderSP.setNotify_url(payAccount.getNotifyUrl() +"/refund"); wxRefundOrderSP.setSign_type("HMAC-SHA256"); return wxRefundOrderSP; } @@ -408,7 +405,12 @@ public class WxRefundAdapterService implements RefundPayAdapterService{ } } - @Override + @Override + public RefundAdapterResult refund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + return null; + } + + @Override public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, WxRefundOrder record) { if (payAccount.getType() == EnumPayMode.MCH.getCode()) { Map paramMap = WxPayment.buildWeappRefundQueryMap( @@ -503,188 +505,9 @@ public class WxRefundAdapterService implements RefundPayAdapterService{ } } - @Autowired - WxAppinfoMapper wxAppinfoMapper; - @Autowired - WxPayAccountMapper wxPayAccountMapper; - @Autowired - WxPayOrderMapper wxPayOrderMapper; - @Autowired - WxRefundOrderMapper wxRefundOrderMapper; - - - private RefundNotifyAdapterResult notifyErrorResult(String msg) { - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "FAIL"); - resultMap.put("return_msg", msg); - return new RefundNotifyAdapterResult(false,ErrorCode.REFUND_ORDER_ERROR.getCode(),msg,XmlUtil.getRequestXml(resultMap)); - } - - private RefundNotifyAdapterResult notifySuccessResult(String transactionId,String refundId,WxRefundOrder refundOrder) { - SortedMap resultMap = new TreeMap(); - resultMap.put("return_code", "SUCCESS"); - resultMap.put("return_msg", "OK"); - return new RefundNotifyAdapterResult(transactionId, refundId,refundOrder,XmlUtil.getRequestXml(resultMap)); - } - - - @Override - public RefundNotifyAdapterResult notify(Map paramMap, EnumPayWay payWay) { - // how to get wechatAppId, wechatMchId, partnerKey - String appId = paramMap.get("appid"); - String subAppId = paramMap.get("sub_appid"); - String mchId = paramMap.get("mch_id"); - String subMchId = paramMap.get("sub_mch_id"); - if (StringUtils.isBlank(subAppId) && StringUtils.isBlank(subMchId)) { - // 普通商户号 - WxAppinfo appinfo = wxAppinfoMapper.findByAppId(appId); - if (appinfo == null) { - log.error("未找到appid信息:" + appId); - throw new MallinkException(ErrorCode.APP_ID_NOT_FOUND); - } - WxPayAccount payAccount = wxPayAccountMapper.selectById(appinfo.getPayId()); - if (payAccount == null) { - log.error("未找到mch_id信息:" + mchId); - throw new MallinkException(ErrorCode.MCH_INFO_NOT_FOUND); - } - if (!mchId.equalsIgnoreCase(payAccount.getMchId())) { - log.error("mch_id不对应:" + mchId + ",account:" + payAccount.getMchId()); - throw new MallinkException(ErrorCode.MCH_INFO_NOT_EQUAL); - } - String partnerKey = payAccount.getApiKey(); - try { - if (payWay.getType() == EnumPayWay.EnumPayWayType.WX_MINIPAY) { - if (!"SUCCESS".equals(paramMap.get("return_code"))) { - log.warn("notify refund, wxpay status not success, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单状态码非SUCCESS"); - } - - // 解密req_info - String req_info = CipherUtil.decryptReqInfo(paramMap.get("req_info"), partnerKey); - Map reqMap = WxPayment.xmlToMap(req_info); - - String refundIdStr = reqMap.get("out_refund_no"); - Long refundOrderId = Long.valueOf(refundIdStr); - WxRefundOrder refundOrder = wxRefundOrderMapper.selectById(refundOrderId); - if (refundOrder == null) { - log.warn("notify refund, wxpay check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款订单不存在"); - } - // 验证支付金额 - if (!reqMap.get("total_fee").equals(refundOrder.getTotalFee().toString())) { - log.warn("notify refund, wxpay check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单总金额不一致"); - } - // 验证退款金额 - if (!reqMap.get("refund_fee").equals(refundOrder.getRefundFee().toString())) { - log.warn("notify refund, wxpay check refund_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款总金额不一致"); - } - - - String payOrderNo = reqMap.get("out_trade_no"); - Long payOrderId = Long.valueOf(payOrderNo); - WxPayOrder payOrder = wxPayOrderMapper.selectById(payOrderId,refundOrder.getTenantId()); - if (payOrder == null) { - log.warn("notify refund, wxpay check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单不存在"); - } - // 验证支付金额 - if (!reqMap.get("total_fee").equals(payOrder.getPayAmount().toString())) { - log.warn("notify refund, wxpay check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单总金额不一致"); - } - - - // 处理支付成功 - //handleRefundSuccess(refundOrder, reqMap.get("transaction_id"), reqMap.get("refund_id")); - log.info("notify refund, wxpay checksign success, paramMap:{}, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifySuccessResult(reqMap.get("transaction_id"), reqMap.get("refund_id"), refundOrder); - } - } catch (RuntimeException e) { - log.warn("notify refund paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - log.warn("notify refund, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getMessage()); - } - } else { - // 服务号回调 - WxAppinfo appinfo = wxAppinfoMapper.findByAppId(subAppId); - if (appinfo == null) { - log.error("未找到appid信息:" + appId); - throw new MallinkException(ErrorCode.APP_ID_NOT_FOUND); - } - WxPayAccount payAccount = wxPayAccountMapper.selectById(appinfo.getPayId()); - if (payAccount == null) { - log.error("未找到mch_id信息:" + mchId); - throw new MallinkException(ErrorCode.MCH_INFO_NOT_FOUND); - } - if (!mchId.equalsIgnoreCase(payAccount.getMchId())) { - log.error("mch_id不对应:" + mchId + ",account:" + payAccount.getMchId()); - throw new MallinkException(ErrorCode.MCH_INFO_NOT_EQUAL); - } - String partnerKey = payAccount.getApiKey(); - try { - if (payWay.getType() == EnumPayWay.EnumPayWayType.WX_MINIPAY) { - if (!"SUCCESS".equals(paramMap.get("return_code"))) { - log.warn("notify order, wxpay status not success, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单状态码非SUCCESS"); - } - - // 解密req_info - String req_info = CipherUtil.decryptReqInfo(paramMap.get("req_info"), partnerKey); - log.info(req_info); - Map reqMap = WxPayment.xmlToMap(req_info); - - String refundIdStr = reqMap.get("out_refund_no"); - Long refundOrderId = Long.valueOf(refundIdStr); - WxRefundOrder refundOrder = wxRefundOrderMapper.selectById(refundOrderId); - if (refundOrder == null) { - log.warn("notify refund, wxpay check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款订单不存在"); - } - // 验证支付金额 - if (!reqMap.get("total_fee").equals(refundOrder.getTotalFee().toString())) { - log.warn("notify refund, wxpay check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单总金额不一致"); - } - // 验证退款金额 - if (!reqMap.get("refund_fee").equals(refundOrder.getRefundFee().toString())) { - log.warn("notify refund, wxpay check refund_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款总金额不一致"); - } - - String payOrderNo = reqMap.get("out_trade_no"); - if (payOrderNo == null) { - return notifySuccessResult(reqMap.get("transaction_id"), reqMap.get("refund_id"), null); - } - Long payOrderId = Long.valueOf(payOrderNo); - WxPayOrder payOrder = wxPayOrderMapper.selectById(payOrderId,refundOrder.getTenantId()); - if (payOrder == null) { - log.warn("notify refund, wxpay check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单不存在"); - } - // 验证支付金额 - if (!reqMap.get("total_fee").equals(payOrder.getPayAmount().toString())) { - log.warn("notify refund, wxpay check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单总金额不一致"); - } - - - log.info("notify refund, wxpay checksign success, paramMap:{}, paramMap: " + reqMap.toString() + ", payWay:" + payWay.toString()); - return notifySuccessResult(reqMap.get("transaction_id"), reqMap.get("refund_id"), refundOrder); - } - } catch (RuntimeException e) { - log.warn("notify refund, wepay checksign error, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR); - } catch (Exception e) { - log.warn("notify refund, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getMessage()); - } - } - - return notifyErrorResult("FAILED"); - } + @Override + public RefundAdapterResult queryRefund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + return null; + } } diff --git a/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v3/WxRefundV3AdapterService.java b/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v3/WxRefundV3AdapterService.java index 5981452..dbe06cb 100644 --- a/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v3/WxRefundV3AdapterService.java +++ b/suimangService/src/main/java/com/iformall/service/pay/service/refund/wx/v3/WxRefundV3AdapterService.java @@ -7,6 +7,8 @@ import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; +import com.iformall.domain.po.*; +import com.iformall.enums.*; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; @@ -19,16 +21,6 @@ import com.github.binarywang.wxpay.service.WxPayService; import com.iformall.common.ErrorCode; import com.iformall.common.Result; import com.iformall.common.ResultData; -import com.iformall.domain.po.WxAppinfo; -import com.iformall.domain.po.WxOrder; -import com.iformall.domain.po.WxPayAccount; -import com.iformall.domain.po.WxPayOrder; -import com.iformall.domain.po.WxRefundOrder; -import com.iformall.enums.EnumPayMchType; -import com.iformall.enums.EnumPayMode; -import com.iformall.enums.EnumPayType; -import com.iformall.enums.EnumPayWay; -import com.iformall.enums.EnumRefundStatus; import com.iformall.exception.MallinkException; import com.iformall.mapper.WxAppinfoMapper; import com.iformall.mapper.WxPayAccountMapper; @@ -59,10 +51,6 @@ import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class WxRefundV3AdapterService implements RefundPayAdapterService{ - - - @Autowired - MaUtil maUtil; @Lazy @Autowired @@ -71,6 +59,10 @@ public class WxRefundV3AdapterService implements RefundPayAdapterService{ @Lazy @Autowired WxPayAccountService wxPayAccountService; + + + @Autowired + MaUtil maUtil; private V3PayRefundReq getReq(WxPayAccount payAccount,WxAppinfo appInfo,WxRefundOrder record,WxPayOrder payOrder,Long orderId,EnumPayType payType) { V3PayRefundReq req = new V3PayRefundReq(); @@ -97,7 +89,7 @@ public class WxRefundV3AdapterService implements RefundPayAdapterService{ req.setReason("用户自己退款"); } } - req.setNotify_url(payAccount.getRefundNotifyV3Url()); + req.setNotify_url(payAccount.getNotifyUrl() +"/pay"); V3PayRefundAmountReq amount = new V3PayRefundAmountReq(); amount.setRefund(record.getRefundFee()); amount.setTotal(record.getTotalFee()); @@ -160,6 +152,42 @@ public class WxRefundV3AdapterService implements RefundPayAdapterService{ return getResultFromSp(response, record, payOrder); } + @Override + public RefundAdapterResult refund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + + WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); + + V3PayRefundReq req = new V3PayRefundReq(); + req.setOut_trade_no(orderRefund.getOrderNumber()); + req.setOut_refund_no(orderRefund.getId().toString()); + req.setReason(orderRefund.getFailReason()); + + V3PayRefundAmountReq amount = new V3PayRefundAmountReq(); + amount.setRefund(orderRefund.getRefundAmount()); + amount.setTotal(orderRefund.getPayAmount()); + req.setAmount(amount); + + String response = null; + try { + try { + response = WxPayV3.payCommonRefund(payService, req); + }catch(WxPayException e) { + log.error("weixin pay v3 refund error. " ,e); + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getCustomErrorMsg()); + } + } catch (Exception e) { + log.error("退款异常: " + e.getMessage()); + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), "退款异常"); + } + JSONObject resp = JSON.parseObject(response); + RefundAdapterResult result = new RefundAdapterResult(); + result.setSuccess(true); + result.setCode(EnumRefundStatus.REFUND_REQ_SUCCESS.getCode()); + result.setRefundId(resp.getString("refund_id")); + result.setData(resp); + return result; + } + @Override public RefundAdapterResult queryRefund(WxAppinfo appInfo,WxPayAccount payAccount, WxRefundOrder record) { // 服务商模式 @@ -192,91 +220,35 @@ public class WxRefundV3AdapterService implements RefundPayAdapterService{ } } - @Autowired - WxAppinfoMapper wxAppinfoMapper; - @Autowired - WxPayAccountMapper wxPayAccountMapper; - @Autowired - WxPayOrderMapper wxPayOrderMapper; - @Autowired - WxRefundOrderMapper wxRefundOrderMapper; - - - private RefundNotifyAdapterResult notifyErrorResult(String msg) { - SortedMap resultMap = new TreeMap(); - resultMap.put("code", "FAIL"); - resultMap.put("message", msg); - return new RefundNotifyAdapterResult(false,ErrorCode.REFUND_ORDER_ERROR.getCode(),msg,JSON.toJSONString(resultMap)); - } - - private RefundNotifyAdapterResult notifySuccessResult(String transactionId,String refundId,WxRefundOrder refundOrder) { - SortedMap resultMap = new TreeMap(); - resultMap.put("code", "SUCCESS"); - resultMap.put("message", "OK"); - return new RefundNotifyAdapterResult(transactionId, refundId,refundOrder,JSON.toJSONString(resultMap)); - } - - @Override - public RefundNotifyAdapterResult notify(Map paramMap, EnumPayWay payWay) { - String tenantId = paramMap.get("tenantId"); - String resource = paramMap.get("resource"); - JSONObject reObj = JSON.parseObject(resource); - WxPayService wxPayService = wxPayAccountService.getWxPayService(tenantId); + public RefundAdapterResult queryRefund(WxAppinfo appInfo, WxPayAccount payAccount, ProductOrderRefund orderRefund) { + WxPayService payService = maUtil.getWxPayServiceBySelfModel(appInfo, payAccount); + String response = null; try { - String decryptContent = WxPayV3.decrypt(wxPayService, reObj.getString("ciphertext"), reObj.getString("nonce"), reObj.getString("associated_data")); - log.info(decryptContent); - JSONObject decryptObj = JSON.parseObject(decryptContent); - String spMchId = decryptObj.getString("sp_mchid"); - String subMchId = decryptObj.getString("sub_mchid"); - String transactionId = decryptObj.getString("transaction_id"); - String outTradeNo = decryptObj.getString("out_trade_no"); - String refundId = decryptObj.getString("refund_id"); - String outRefundNo = decryptObj.getString("out_refund_no"); - String refundStatus = decryptObj.getString("refund_status"); - String successTime = decryptObj.getString("success_time"); - String userReceivedAccount = decryptObj.getString("user_received_account"); - JSONObject rObj = decryptObj.getJSONObject("amount"); - int total = rObj.getIntValue("total"); - int refund = rObj.getIntValue("refund"); - int payerTotal = rObj.getIntValue("payer_total"); - int payerRefund = rObj.getIntValue("payer_refund"); - - Long payOrderId = Long.valueOf(outTradeNo); - WxPayOrder payOrder = wxPayOrderMapper.selectById(payOrderId,tenantId); - if (payOrder == null) { - log.warn("notify refund, wxpay v3 check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单不存在"); - } - // 验证支付金额 - if (payerTotal != payOrder.getPayAmount().intValue()) { - log.warn("notify refund, wxpay v3 check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("支付订单总金额不一致"); - } - Long refundOrderId = Long.valueOf(outRefundNo); - WxRefundOrder refundOrder = wxRefundOrderMapper.selectById(refundOrderId); - if (refundOrder == null) { - log.warn("notify refund, wxpay v3 check pay order not exists, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款订单不存在"); - } - // 验证支付金额 - if (payerTotal != refundOrder.getTotalFee().intValue()) { - log.warn("notify refund, wxpay v3 check total_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("订单总金额不一致"); - } - // 验证退款金额 - if (payerRefund != refundOrder.getRefundFee().intValue()) { - log.warn("notify refund, wxpay v3 check refund_fee is invalid, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString()); - return notifyErrorResult("退款总金额不一致"); - } - return notifySuccessResult(transactionId, refundId, refundOrder); - } catch (RuntimeException e) { - log.warn("notify refund paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getMessage()); - } catch (Exception e) { - log.warn("notify refund, paramMap: " + paramMap.toString() + ", payWay:" + payWay.toString() + ", e:" + e.getMessage()); - throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getMessage()); - } + try { + response = WxPayV3.payCommonRefundQuery(payService, String.valueOf(orderRefund.getId())); + }catch(WxPayException e) { + log.error("weixin pay v3 query refund error " ,e); + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), e.getCustomErrorMsg()); + } + JSONObject result = JSON.parseObject(response); + String refund_status_0 = result.getString("status"); + if("SUCCESS".equals(refund_status_0)){ + return new RefundAdapterResult(true, EnumRefundOrderStatus.REFUND_SUCCESS.getCode(),"退款成功",result); + }else if("CLOSED".equals(refund_status_0)){ + return new RefundAdapterResult(false,EnumRefundOrderStatus.REFUND_FAIL.getCode(),"退款关闭,指商户发起退款失败的情况",result); + }else if("PROCESSING".equals(refund_status_0)){ + return new RefundAdapterResult(false,EnumRefundOrderStatus.REFUND_REQ_SUCCESS.getCode(),"退款中",result); + }else if("ABNORMAL".equals(refund_status_0)){ + return new RefundAdapterResult(false,EnumRefundOrderStatus.REFUND_FAIL.getCode(), + "退款异常,退款到银行发现用户的卡作废或者冻结了,导致原路退款银行卡失败。",result); + }else{ + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(),"查询状态异常 非法状态"); + } + } catch (Exception e) { + log.error("退款异常: " + e.getMessage()); + throw new MallinkException(ErrorCode.REFUND_ORDER_ERROR.getCode(), "退款异常"); + } } } diff --git a/suimangService/src/main/java/com/iformall/service/project/ProjectFactory.java b/suimangService/src/main/java/com/iformall/service/project/ProjectFactory.java new file mode 100644 index 0000000..9bfaceb --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/ProjectFactory.java @@ -0,0 +1,60 @@ +package com.iformall.service.project; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.iformall.common.ErrorCode; +import com.iformall.enums.EnumProject; +import com.iformall.exception.MallinkException; +import com.iformall.service.project.service.ProjectService; +import com.iformall.service.project.service.impl.CommonProjectService; +import com.iformall.service.project.service.impl.HBProjectService; +import com.iformall.service.project.service.impl.HKProjectService; +import com.iformall.service.project.service.impl.HYProjectService; +import com.iformall.service.project.service.impl.HYuProjectService; +import com.iformall.service.project.service.impl.ZXProjectService; + +/** + * @author Administrator + */ +@Service +public class ProjectFactory { + + private Map serviceMap = null; + + @Autowired + CommonProjectService commonPayProductService; + @Autowired + HYProjectService hYPayProductService; + @Autowired + HBProjectService hBPayProductService; + @Autowired + HYuProjectService hYuPayProductService; + @Autowired + HKProjectService hKPayProductService; + @Autowired + ZXProjectService zXPayProductService; + + + private Map getServiceMap() { + if (null == serviceMap) { + serviceMap = new ConcurrentHashMap(); + serviceMap.put(EnumProject.PROJECT_0.getCode(), commonPayProductService); + serviceMap.put(EnumProject.PROJECT_1.getCode(), hBPayProductService); + serviceMap.put(EnumProject.PROJECT_2.getCode(), hYPayProductService); + serviceMap.put(EnumProject.PROJECT_3.getCode(), hYuPayProductService); + serviceMap.put(EnumProject.PROJECT_4.getCode(), hKPayProductService); + serviceMap.put(EnumProject.PROJECT_5.getCode(), zXPayProductService); + } + return serviceMap; + } + + public ProjectService getProjectService(Integer productProject) throws MallinkException{ + ProjectService service = getServiceMap().get(productProject); + if (null == service) { + throw new MallinkException(ErrorCode.SYS_SERVER_ERROR.getCode(),"["+productProject+"] 支付套餐service未找到"); + } + return service; + } +} diff --git a/suimangService/src/main/java/com/iformall/service/project/entity/CreateBilling.java b/suimangService/src/main/java/com/iformall/service/project/entity/CreateBilling.java new file mode 100644 index 0000000..307c35f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/entity/CreateBilling.java @@ -0,0 +1,24 @@ +package com.iformall.service.project.entity; + +import lombok.Data; + +public class CreateBilling { + + //总消耗金币数 + private Integer totalCostPoins; + //详细清单 + private String detail; + + public Integer getTotalCostPoins() { + return totalCostPoins; + } + public void setTotalCostPoins(Integer totalCostPoins) { + this.totalCostPoins = totalCostPoins; + } + public String getDetail() { + return detail; + } + public void setDetail(String detail) { + this.detail = detail; + } +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/ProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/ProjectService.java new file mode 100644 index 0000000..1d9eff3 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/ProjectService.java @@ -0,0 +1,33 @@ +package com.iformall.service.project.service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; + +public interface ProjectService { + + /** + * 查询支付产品其余信息(如套餐明细等信息) + * @param product + * @return + */ + public Object getPayProductExtroInfo(Product product); + + /** + * 处理充值成功 + */ + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product); + + /** + * 处理生成视频账单 + * @return + */ + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoTimes,Long videoSize); + + /** + * 处理用户注册后事项 + */ + public void handleAfterRegeister(WxCUserBasicInfo cUser); + + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/BaseProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/BaseProjectService.java new file mode 100644 index 0000000..85dc4d1 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/BaseProjectService.java @@ -0,0 +1,11 @@ +package com.iformall.service.project.service.impl; + +import com.iformall.domain.po.Product; + +public class BaseProjectService { + + public Object noPayProductExtroInfo(Product product) { + return null; + } + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/CommonProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/CommonProjectService.java new file mode 100644 index 0000000..ad8f437 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/CommonProjectService.java @@ -0,0 +1,39 @@ +package com.iformall.service.project.service.impl; + +import org.springframework.stereotype.Service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; + +//通用项目 +@Service +public class CommonProjectService extends BaseProjectService implements ProjectService{ + + @Override + public Object getPayProductExtroInfo(Product product) { + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + // TODO Auto-generated method stub + + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoSeconds, Long videoSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/HBProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/HBProjectService.java new file mode 100644 index 0000000..2e8d440 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/HBProjectService.java @@ -0,0 +1,38 @@ +package com.iformall.service.project.service.impl; + +import org.springframework.stereotype.Service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; + +//慧播 +@Service +public class HBProjectService extends BaseProjectService implements ProjectService{ + + @Override + public Object getPayProductExtroInfo(Product product) { + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + // TODO Auto-generated method stub + + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoSeconds, Long videoSize) { + return null; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/HKProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/HKProjectService.java new file mode 100644 index 0000000..7410d61 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/HKProjectService.java @@ -0,0 +1,39 @@ +package com.iformall.service.project.service.impl; + +import org.springframework.stereotype.Service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; + +//慧侃 +@Service +public class HKProjectService extends BaseProjectService implements ProjectService{ + + @Override + public Object getPayProductExtroInfo(Product product) { + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + // TODO Auto-generated method stub + + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoSeconds, Long videoSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/HYProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/HYProjectService.java new file mode 100644 index 0000000..f91065e --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/HYProjectService.java @@ -0,0 +1,57 @@ +package com.iformall.service.project.service.impl; + +import java.math.BigDecimal; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.WxCUserBasicInfoService; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; +import com.iformall.utils.Constant; + +//慧影 +@Service +public class HYProjectService extends BaseProjectService implements ProjectService{ + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Lazy + @Autowired + WxCUserBasicInfoService wxCUserBasicInfoService; + + @Override + public Object getPayProductExtroInfo(Product product) { + //慧影套餐表project_package_detail, 现在暂时不搞那么复杂 + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + //更新用户的币 + wxCUserBasicInfoService.addPoints(cUserId, cUserFinalTenantId,product.getGlod()); + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoTimes, Long videoSize) { + //慧影视频按照时长来扣币 + CreateBilling cb = new CreateBilling(); + //每分钟扣币,不足一分钟按一分钟算 + Integer minitues = new BigDecimal(videoTimes).divide(new BigDecimal(60),BigDecimal.ROUND_CEILING).setScale(0,BigDecimal.ROUND_UP).intValue(); + Integer poinsPerMinites = Constant.hyCostPoinsPerMinites; + cb.setTotalCostPoins(new BigDecimal(minitues).multiply(new BigDecimal(poinsPerMinites)).intValue()); + cb.setDetail("每分钟扣币"+poinsPerMinites+"个,总共时长"+videoTimes+"(秒),按"+minitues+"分钟总计费。"); + //扣去当前用户的币 + wxCUserBasicInfoService.reducePoints(cUserId, cUserFinalTenantId,cb.getTotalCostPoins()); + return cb; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + wxCUserBasicInfoService.addPoints(cUser.getId(), cUser.getFinalTenantId(),Constant.hyRegeisterPoins); + } +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/HYuProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/HYuProjectService.java new file mode 100644 index 0000000..3596fe2 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/HYuProjectService.java @@ -0,0 +1,39 @@ +package com.iformall.service.project.service.impl; + +import org.springframework.stereotype.Service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; + +//慧语 +@Service +public class HYuProjectService extends BaseProjectService implements ProjectService{ + + @Override + public Object getPayProductExtroInfo(Product product) { + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + // TODO Auto-generated method stub + + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoSeconds, Long videoSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/suimangService/src/main/java/com/iformall/service/project/service/impl/ZXProjectService.java b/suimangService/src/main/java/com/iformall/service/project/service/impl/ZXProjectService.java new file mode 100644 index 0000000..495c512 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/project/service/impl/ZXProjectService.java @@ -0,0 +1,39 @@ +package com.iformall.service.project.service.impl; + +import org.springframework.stereotype.Service; + +import com.iformall.domain.po.Product; +import com.iformall.domain.po.WxCUserBasicInfo; +import com.iformall.service.project.entity.CreateBilling; +import com.iformall.service.project.service.ProjectService; + +//智象 +@Service +public class ZXProjectService extends BaseProjectService implements ProjectService{ + + @Override + public Object getPayProductExtroInfo(Product product) { + return noPayProductExtroInfo(product); + } + + @Override + public void handlePaidOrder(Long cUserId,String cUserFinalTenantId,Product product) { + // TODO Auto-generated method stub + + } + + @Override + public CreateBilling handleCreateVideoBilling(Long cUserId,String cUserFinalTenantId,String videoSeconds, Long videoSize) { + // TODO Auto-generated method stub + return null; + } + + @Override + public void handleAfterRegeister(WxCUserBasicInfo cUser) { + // TODO Auto-generated method stub + + } + + + +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/ApiDetailService.java b/suimangService/src/main/java/com/iformall/service/sm/ApiDetailService.java new file mode 100644 index 0000000..124f1e9 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/ApiDetailService.java @@ -0,0 +1,12 @@ +package com.iformall.service.sm; + +import com.iformall.domain.po.sm.ApiDetail; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + * + */ +public interface ApiDetailService extends IService { + + ApiDetail getApiDetail(Long id); +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/ApiGuideService.java b/suimangService/src/main/java/com/iformall/service/sm/ApiGuideService.java new file mode 100644 index 0000000..23396c4 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/ApiGuideService.java @@ -0,0 +1,21 @@ +package com.iformall.service.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveApiGuideDTO; +import com.iformall.domain.dto.sm.UpdateApiGuideDTO; +import com.iformall.domain.po.sm.ApiGuide; +import com.baomidou.mybatisplus.extension.service.IService; + +/** + * + */ +public interface ApiGuideService extends IService { + + PageInfo pageApiGuide(ApiGuide apiGuide, Integer pageNum, Integer pageSize); + + void saveApiGuide(SaveApiGuideDTO dto); + + void updateApiGuide(UpdateApiGuideDTO dto); + + ApiGuide getAvailableApiGuide(); +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/ApiMenuService.java b/suimangService/src/main/java/com/iformall/service/sm/ApiMenuService.java new file mode 100644 index 0000000..318c112 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/ApiMenuService.java @@ -0,0 +1,29 @@ +package com.iformall.service.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveApiMenuDTO; +import com.iformall.domain.dto.sm.UpdateApiMenuDTO; +import com.iformall.domain.po.sm.ApiMenu; +import com.baomidou.mybatisplus.extension.service.IService; +import com.iformall.domain.vo.sm.ListApiSubmenuVO; + +import java.util.List; + +/** + * + */ +public interface ApiMenuService extends IService { + + PageInfo pageApiMenu(ApiMenu apiMenu, Integer pageNum, Integer pageSize); + + void saveApiMenu(SaveApiMenuDTO dto); + + void updateApiMenu(UpdateApiMenuDTO dto); + + List listParentMenu(); + + ApiMenu getApiMenu(Long id); + + List listMenu(); + +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/PersonMouldService.java b/suimangService/src/main/java/com/iformall/service/sm/PersonMouldService.java index c48d90c..59e48f8 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/PersonMouldService.java +++ b/suimangService/src/main/java/com/iformall/service/sm/PersonMouldService.java @@ -1,5 +1,7 @@ package com.iformall.service.sm; +import java.util.List; + import com.github.pagehelper.PageInfo; import com.iformall.common.ResultData; import com.iformall.domain.po.sm.MouldPatch; @@ -42,5 +44,14 @@ public interface PersonMouldService { void deleteById(Long id); void updateOnline(PersonMould record); + + //接入商的模板编号 + List getServiceMouldIds(Long serviceId); + + List getUserMouldIds(List userIds); + List getCUserIds(Long personMouldId); + + void associatedUserMoulds(List mouldIds, Long cUserId); + } diff --git a/suimangService/src/main/java/com/iformall/service/sm/ServiceInfoService.java b/suimangService/src/main/java/com/iformall/service/sm/ServiceInfoService.java new file mode 100644 index 0000000..f4d3f97 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/ServiceInfoService.java @@ -0,0 +1,59 @@ +package com.iformall.service.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveServiceInfoDTO; +import com.iformall.domain.dto.sm.UpdateServiceInfoDTO; +import com.iformall.domain.dto.sm.UpdateServiceInfoStatusDTO; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.vo.neuver.PageServiceInfoVO; + +import java.util.List; + +/** + * 接入商service + * + * @author xmzhao71 + * @date 2023-10-19 + */ +public interface ServiceInfoService { + + /** + * 创建接入商 + * + * @param dto + */ + void saveServiceInfo(SaveServiceInfoDTO dto); + + /** + * 接入商分页查询 + * + * @param pageNum + * @param pageSize + * @return {@link PageInfo}<{@link PageServiceInfoVO}> + */ + PageInfo pageServiceInfo(ServiceInfo serviceInfo, Integer pageNum, Integer pageSize); + + /** + * 修改接入商 + * + * @param dto + */ + void updateServiceInfo(UpdateServiceInfoDTO dto); + + void updateServiceInfo(ServiceInfo serviceInfo); + + /** + * 修改接入商状态 + * + * @param dto + */ + void updateServiceInfoStatus(UpdateServiceInfoStatusDTO dto); + + ServiceInfo getServiceInfo(Long id); + ServiceInfo getServiceInfoByMallUserInfo(Long mallUserInfoId); + + void associatedMoulds(List mouldIds,Long id); + + void reduceTimes(Long serviceId,Long seconds); + +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/ServiceVideoRecordService.java b/suimangService/src/main/java/com/iformall/service/sm/ServiceVideoRecordService.java new file mode 100644 index 0000000..43bdaf1 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/ServiceVideoRecordService.java @@ -0,0 +1,23 @@ +package com.iformall.service.sm; + +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveServiceVideoRecordDTO; +import com.iformall.domain.po.sm.ServiceVideoRecord; + +/** + * @author xmzhao71 + * @date 2023-10-20 + */ +public interface ServiceVideoRecordService { + + /** + * @param dto + */ + void saveServiceVideoRecord(SaveServiceVideoRecordDTO dto); + + PageInfo listAsPage(ServiceVideoRecord record, Integer pageIndex, Integer pageSize); + + Float totalTimes(ServiceVideoRecord record); + + +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/UserMouldVideoService.java b/suimangService/src/main/java/com/iformall/service/sm/UserMouldVideoService.java index 1c22a85..a397e74 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/UserMouldVideoService.java +++ b/suimangService/src/main/java/com/iformall/service/sm/UserMouldVideoService.java @@ -59,4 +59,7 @@ public interface UserMouldVideoService { List getNotHaveUrl(); + UserMouldVideo getUserVideo(Long id); + + ResultData checkVideoStatus(Long userId, List ids); } diff --git a/suimangService/src/main/java/com/iformall/service/sm/VoiceInfoService.java b/suimangService/src/main/java/com/iformall/service/sm/VoiceInfoService.java index 27d64e3..d285b2d 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/VoiceInfoService.java +++ b/suimangService/src/main/java/com/iformall/service/sm/VoiceInfoService.java @@ -1,10 +1,8 @@ package com.iformall.service.sm; -import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; +import com.iformall.domain.vo.sm.PreviewVoiceVO; import com.iformall.domain.po.sm.VoiceInfo; -import com.iformall.domain.po.sm.VoiceLanguage; import com.iformall.sm.AiPreviewParam; import java.util.List; @@ -15,5 +13,5 @@ public interface VoiceInfoService { VoiceInfo getById(Long voiceMouldId); - ResultData voicePreview(AiPreviewParam aiPreviewParam); + PreviewVoiceVO previewVoice(AiPreviewParam aiPreviewParam); } diff --git a/suimangService/src/main/java/com/iformall/service/sm/VoiceLanguageService.java b/suimangService/src/main/java/com/iformall/service/sm/VoiceLanguageService.java index d16cfb8..296fad2 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/VoiceLanguageService.java +++ b/suimangService/src/main/java/com/iformall/service/sm/VoiceLanguageService.java @@ -1,12 +1,23 @@ package com.iformall.service.sm; +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.sm.PersonMould; import com.iformall.domain.po.sm.VoiceLanguage; import java.util.List; public interface VoiceLanguageService { + + PageInfo listAsPage(VoiceLanguage record, Integer pageIndex, Integer pageSize); - List voiceTotal(); + List voiceTotal(VoiceLanguage voiceLanguage); + VoiceLanguage getLanguage(String paperwork); + + List listVoiceLanguage(String chineseName); + + List getUserVoiceIdList(List cUserIds); + void associatedUserVoices(List voicesIds, Long cUserId); + List getCUserIds(Long voiceId); } diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/ApiDetailServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiDetailServiceImpl.java new file mode 100644 index 0000000..f1ae80a --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiDetailServiceImpl.java @@ -0,0 +1,26 @@ +package com.iformall.service.sm.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.iformall.domain.po.sm.ApiDetail; +import com.iformall.service.sm.ApiDetailService; +import com.iformall.mapper.ApiDetailMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +/** + * + */ +@Service +public class ApiDetailServiceImpl extends ServiceImpl implements ApiDetailService{ + @Autowired + private ApiDetailMapper apiDetailMapper; + + @Override + public ApiDetail getApiDetail(Long id) { + return null; + } +} + + + + diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/ApiGuideServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiGuideServiceImpl.java new file mode 100644 index 0000000..8a6f85f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiGuideServiceImpl.java @@ -0,0 +1,87 @@ +package com.iformall.service.sm.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.CommonConstants; +import com.iformall.common.ErrorCode; +import com.iformall.domain.dto.sm.SaveApiGuideDTO; +import com.iformall.domain.dto.sm.UpdateApiGuideDTO; +import com.iformall.domain.po.sm.ApiGuide; +import com.iformall.exception.BizException; +import com.iformall.service.sm.ApiGuideService; +import com.iformall.mapper.ApiGuideMapper; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +/** + * + */ +@Service +public class ApiGuideServiceImpl extends ServiceImpl implements ApiGuideService{ + + @Autowired + private ApiGuideMapper apiGuideMapper; + + @Override + public PageInfo pageApiGuide(ApiGuide apiGuide, Integer pageNum, Integer pageSize) { + return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> apiGuideMapper.listApiGuide(apiGuide)); + } + + @Override + public void saveApiGuide(SaveApiGuideDTO dto) { + ApiGuide dbApiGuide = apiGuideMapper.selectOne(new LambdaQueryWrapper().eq(ApiGuide::getName, dto.getName())); + if (dbApiGuide != null) { + throw new BizException(ErrorCode.NAME_REPEAT); + } + + // 暂时处理,存在正常的指南,则不可新增新的正常指南 + List apiGuides = apiGuideMapper.selectList(new LambdaQueryWrapper() + .eq(ApiGuide::getStatus, CommonConstants.STATUS_NORMAL) + .eq(ApiGuide::getDeleteFlag, CommonConstants.FLAG_FALSE)); + if (CommonConstants.STATUS_NORMAL.equals(dto.getStatus()) && !CollectionUtils.isEmpty(apiGuides)) { + throw new BizException(ErrorCode.EXIST_AVAILABLE_GUIDE); + } + + ApiGuide apiGuide = SaveApiGuideDTO.mapping(dto); + apiGuideMapper.insert(apiGuide); + } + + @Override + public void updateApiGuide(UpdateApiGuideDTO dto) { + ApiGuide dbApiGuide = apiGuideMapper.selectOne(new LambdaQueryWrapper() + .eq(ApiGuide::getName, dto.getName()) + .ne(ApiGuide::getId, dto.getId())); + if (dbApiGuide != null) { + throw new BizException(ErrorCode.NAME_REPEAT); + } + + // 暂时处理,存在正常的指南,则不可修改新的正常指南 + List apiGuides = apiGuideMapper.selectList(new LambdaQueryWrapper() + .eq(ApiGuide::getStatus, CommonConstants.STATUS_NORMAL) + .eq(ApiGuide::getDeleteFlag, CommonConstants.FLAG_FALSE) + .ne(ApiGuide::getId, dto.getId())); + if (CommonConstants.STATUS_NORMAL.equals(dto.getStatus()) && !CollectionUtils.isEmpty(apiGuides)) { + throw new BizException(ErrorCode.EXIST_AVAILABLE_GUIDE); + } + + ApiGuide apiGuide = UpdateApiGuideDTO.mapping(dto); + apiGuideMapper.updateById(apiGuide); + } + + @Override + public ApiGuide getAvailableApiGuide() { + ApiGuide apiGuide = new ApiGuide(); + apiGuide.setStatus(CommonConstants.STATUS_NORMAL); + List apiGuides = apiGuideMapper.listApiGuide(apiGuide); + return !CollectionUtils.isEmpty(apiGuides) ? apiGuides.get(0) : null; + } +} + + + + diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/ApiMenuServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiMenuServiceImpl.java new file mode 100644 index 0000000..89c8351 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/ApiMenuServiceImpl.java @@ -0,0 +1,89 @@ +package com.iformall.service.sm.impl; + +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.CommonConstants; +import com.iformall.domain.dto.sm.SaveApiMenuDTO; +import com.iformall.domain.dto.sm.UpdateApiMenuDTO; +import com.iformall.domain.po.sm.ApiDetail; +import com.iformall.domain.po.sm.ApiMenu; +import com.iformall.domain.vo.sm.ListApiSubmenuVO; +import com.iformall.mapper.ApiDetailMapper; +import com.iformall.service.sm.ApiMenuService; +import com.iformall.mapper.ApiMenuMapper; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * + */ +@Service +public class ApiMenuServiceImpl extends ServiceImpl implements ApiMenuService{ + + @Autowired + private ApiMenuMapper apiMenuMapper; + @Autowired + private ApiDetailMapper apiDetailMapper; + + @Override + public PageInfo pageApiMenu(ApiMenu apiMenu, Integer pageNum, Integer pageSize) { + return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> apiMenuMapper.listApiMenu(apiMenu)); + } + + @Override + public ApiMenu getApiMenu(Long id) { + ApiMenu apiMenu = new ApiMenu(); + apiMenu.setId(id); + List vos = apiMenuMapper.listApiMenu(apiMenu); + return !CollectionUtils.isEmpty(vos) ? vos.get(0) : null; + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void saveApiMenu(SaveApiMenuDTO dto) { + // 保存菜单信息 + ApiMenu apiMenu = SaveApiMenuDTO.mapping(dto); + apiMenuMapper.insert(apiMenu); + + if (CommonConstants.NUM_0 != dto.getParentId()) { + // 保存菜单详情信息 + ApiDetail apiDetail = SaveApiMenuDTO.mappingApiDetail(dto, apiMenu); + apiDetailMapper.insert(apiDetail); + } + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void updateApiMenu(UpdateApiMenuDTO dto) { + // 修改菜单信息 + ApiMenu apiMenu = UpdateApiMenuDTO.mapping(dto); + apiMenuMapper.updateById(apiMenu); + + if (CommonConstants.NUM_0 != dto.getParentId()) { + // 修改菜单详情信息 + ApiDetail apiDetail = UpdateApiMenuDTO.mappingApiDetail(dto); + apiDetailMapper.update(apiDetail, new LambdaUpdateWrapper().eq(ApiDetail::getMenuId, dto.getId())); + } + } + + @Override + public List listParentMenu() { + return apiMenuMapper.listParentMenu(); + } + + @Override + public List listMenu() { + return apiMenuMapper.listApiMenu(null); + } + +} + + + + diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/PersonMouldServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/PersonMouldServiceImpl.java index dbabecd..152cd32 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/impl/PersonMouldServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/PersonMouldServiceImpl.java @@ -7,11 +7,15 @@ import com.iformall.common.ResultData; import com.iformall.domain.po.sm.MouldPatch; import com.iformall.domain.po.sm.MouldPatchSign; import com.iformall.domain.po.sm.PersonMould; +import com.iformall.domain.po.sm.ServicePersonMould; +import com.iformall.domain.po.sm.UserPersonMould; import com.iformall.enums.EnumColour; import com.iformall.enums.EnumMouldSendType; import com.iformall.enums.EnumaMouldPatchStatus; import com.iformall.mapper.MouldPatchMapper; import com.iformall.mapper.PersonMouldMapper; +import com.iformall.mapper.ServicePersonMouldMapper; +import com.iformall.mapper.UserPersonMouldMapper; import com.iformall.service.sm.MouldPatchService; import com.iformall.service.sm.MouldPatchSignService; import com.iformall.service.sm.PersonMouldService; @@ -22,6 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -35,6 +40,12 @@ public class PersonMouldServiceImpl implements PersonMouldService { @Autowired MouldPatchSignService mouldPatchSignService; + + @Autowired + ServicePersonMouldMapper servicePersonMouldMapper; + + @Autowired + UserPersonMouldMapper userPersonMouldMapper; @Override @@ -44,6 +55,18 @@ public class PersonMouldServiceImpl implements PersonMouldService { @Override public PageInfo cListAsPage(PersonMould record, Integer pageIndex, Integer pageSize) { + if (null != record.getCuserId()) { + UserPersonMould upm = new UserPersonMould(); + upm.setUserId(record.getCuserId()); + List mouldIds = userPersonMouldMapper.findMouldIdList(upm); + if (null == mouldIds || mouldIds.size() <= 0 ) { + List pmids = new ArrayList(); + pmids.add(-1L); + record.setCustomPersonMouldIds(pmids); + }else { + record.setCustomPersonMouldIds(mouldIds); + } + } return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> personMouldMapper.findCList(record)); } @@ -116,4 +139,43 @@ public class PersonMouldServiceImpl implements PersonMouldService { personMouldMapper.updateById(personMouldUpd); } + @Override + public List getServiceMouldIds(Long serviceId) { + ServicePersonMould spm = new ServicePersonMould(); + spm.setServiceId(serviceId); + return servicePersonMouldMapper.findMouldIdList(spm); + } + + @Override + public List getUserMouldIds(List userIds) { + UserPersonMould upm = new UserPersonMould(); + upm.setCuserIds(userIds); + return userPersonMouldMapper.findMouldIdList(upm); + } + + @Override + public List getCUserIds(Long personMouldId) { + UserPersonMould upm = new UserPersonMould(); + upm.setPersonMouldId(personMouldId); + return userPersonMouldMapper.findCUserIdList(upm); + } + + @Override + public void associatedUserMoulds(List mouldIds, Long cUserId) { + userPersonMouldMapper.deleteByCuserId(cUserId); + if (null != mouldIds && mouldIds.size() > 0 ) { + List upmlist = new ArrayList(); + for (int i = 0 ; i < mouldIds.size() ; i ++) { + UserPersonMould upm = new UserPersonMould(); + upm.setId(IdWorker.get().nextId()); + upm.setUserId(cUserId); + upm.setPersonMouldId(mouldIds.get(i)); + upm.setCreateDate(new Date()); + upm.setUpdateDate(new Date()); + upmlist.add(upm); + } + userPersonMouldMapper.saveBatch(upmlist); + } + } + } diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceInfoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceInfoServiceImpl.java new file mode 100644 index 0000000..bbaaeea --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceInfoServiceImpl.java @@ -0,0 +1,132 @@ +package com.iformall.service.sm.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.common.CommonConstants; +import com.iformall.common.ErrorCode; +import com.iformall.common.IdWorker; +import com.iformall.domain.dto.sm.*; +import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServicePersonMould; +import com.iformall.exception.BizException; +import com.iformall.mapper.ServiceInfoMapper; +import com.iformall.mapper.ServicePersonMouldMapper; +import com.iformall.mapper.WxThirdPartyApiMapper; +import com.iformall.service.WxThirdPartyApiService; +import com.iformall.service.sm.ServiceInfoService; +import org.apache.commons.collections.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +@Service +public class ServiceInfoServiceImpl implements ServiceInfoService { + + @Autowired + private ServiceInfoMapper serviceInfoMapper; + @Autowired + private WxThirdPartyApiService thirdPartyApiService; + @Autowired + private WxThirdPartyApiMapper wxThirdPartyApiMapper; + @Autowired + private ServicePersonMouldMapper servicePersonMouldMapper; + + @Transactional(rollbackFor = Exception.class) + @Override + public void saveServiceInfo(SaveServiceInfoDTO dto) { + // 校验 + ServiceInfo serviceInfo = serviceInfoMapper.selectOne(new LambdaQueryWrapper() + .eq(ServiceInfo::getDelFlag, CommonConstants.FLAG_FALSE) + .eq(ServiceInfo::getCode, dto.getCode())); + if (serviceInfo != null) { + throw new BizException(ErrorCode.CODE_ALREADY_EXISTS); + } + + ServiceInfo mapping = SaveServiceInfoDTO.mapping(dto); + serviceInfoMapper.insert(mapping); + + // 生成秘钥 + SaveThirdPartyApiDTO thirdPartyApi = SaveThirdPartyApiDTO.builder() + .type(mapping.getType()) + .name(mapping.getName()) + .serviceId(mapping.getId()) + .build(); + thirdPartyApiService.saveThirdPartyApi(thirdPartyApi); + } + + @Override + public PageInfo pageServiceInfo(ServiceInfo serviceInfo, Integer pageNum, Integer pageSize) { + return PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> serviceInfoMapper.listServiceInfo(serviceInfo)); + } + + @Override + public void updateServiceInfo(UpdateServiceInfoDTO dto) { + serviceInfoMapper.updateById(UpdateServiceInfoDTO.mapping(dto)); + } + + @Override + public void updateServiceInfo(ServiceInfo serviceInfo) { + serviceInfoMapper.updateById(serviceInfo); + } + + @Transactional(rollbackFor = Exception.class) + @Override + public void updateServiceInfoStatus(UpdateServiceInfoStatusDTO dto) { + // 修改合作商状态 + serviceInfoMapper.update(null, new LambdaUpdateWrapper() + .set(ServiceInfo::getStatus, dto.getStatus()) + .eq(ServiceInfo::getId, dto.getId())); + + if (CommonConstants.STATUS_ABNORMAL.equals(dto.getStatus())) { + // 若合作商为锁定状态,则修改秘钥状态 + wxThirdPartyApiMapper.update(null, new LambdaUpdateWrapper() + .set(WxThirdPartyApi::getStatus, dto.getStatus()) + .eq(WxThirdPartyApi::getServiceId, dto.getId())); + } + } + + @Override + public ServiceInfo getServiceInfo(Long id) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setId(id); + return serviceInfoMapper.selectById(id); + } + + @Override + public ServiceInfo getServiceInfoByMallUserInfo(Long mallUserInfoId) { + ServiceInfo serviceInfo = new ServiceInfo(); + serviceInfo.setMallUserInfo(mallUserInfoId); + List serviceInfos = serviceInfoMapper.listServiceInfo(serviceInfo); + return !CollectionUtils.isEmpty(serviceInfos) ? serviceInfos.get(0) : null; + } + + @Override + public void associatedMoulds(List mouldIds, Long id) { + servicePersonMouldMapper.deleteByServiceId(id); + if (null != mouldIds && mouldIds.size() > 0 ) { + List spmlist = new ArrayList(); + for (int i = 0 ; i < mouldIds.size() ; i ++) { + ServicePersonMould spm = new ServicePersonMould(); + spm.setId(IdWorker.get().nextId()); + spm.setPersonMouldId(mouldIds.get(i)); + spm.setServiceId(id); + spm.setCreateDate(new Date()); + spm.setUpdateDate(new Date()); + spmlist.add(spm); + } + servicePersonMouldMapper.saveBatch(spmlist); + } + } + + @Override + public void reduceTimes(Long serviceId,Long seconds) { + serviceInfoMapper.reduceTimes(serviceId,seconds); + } +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceVideoRecordServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceVideoRecordServiceImpl.java new file mode 100644 index 0000000..39f27ab --- /dev/null +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/ServiceVideoRecordServiceImpl.java @@ -0,0 +1,34 @@ +package com.iformall.service.sm.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.iformall.domain.dto.sm.SaveServiceVideoRecordDTO; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import com.iformall.mapper.ServiceVideoRecordMapper; +import com.iformall.service.sm.ServiceVideoRecordService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class ServiceVideoRecordServiceImpl implements ServiceVideoRecordService { + + @Autowired + private ServiceVideoRecordMapper serviceVideoRecordMapper; + + @Override + public void saveServiceVideoRecord(SaveServiceVideoRecordDTO dto) { + serviceVideoRecordMapper.insert(SaveServiceVideoRecordDTO.mapping(dto)); + } + + @Override + public PageInfo listAsPage(ServiceVideoRecord record, Integer pageIndex, Integer pageSize) { + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> serviceVideoRecordMapper + .selectList(new LambdaQueryWrapper().eq(ServiceVideoRecord::getServiceId, record.getServiceId()).orderByDesc(ServiceVideoRecord::getCreateTime))); + } + + @Override + public Float totalTimes(ServiceVideoRecord record) { + return serviceVideoRecordMapper.totalTimes(record); + } +} diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/UserMouldVideoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/UserMouldVideoServiceImpl.java index 4806792..29b724c 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/impl/UserMouldVideoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/UserMouldVideoServiceImpl.java @@ -8,13 +8,21 @@ import com.github.pagehelper.PageInfo; import com.iformall.common.ErrorCode; import com.iformall.common.IdWorker; import com.iformall.common.ResultData; +import com.iformall.domain.po.ProductOrder; import com.iformall.domain.po.sm.*; import com.iformall.enums.*; +import com.iformall.enums.sm.EnumThirdPartyType; import com.iformall.mapper.UserMouldVideoMapper; +import com.iformall.service.ProductOrderService; +import com.iformall.service.WxCUserBasicInfoService; +import com.iformall.service.project.ProjectFactory; +import com.iformall.service.project.entity.CreateBilling; import com.iformall.service.sm.*; import com.iformall.sm.AiVideoHelper; import com.iformall.sm.AiVideoParam; import com.iformall.sm.AiVideoResult; +import com.iformall.smsdk.SmGenerateVideoDTO; +import com.iformall.smsdk.SmSdkUtils; import com.iformall.utils.Base64Util; import com.iformall.utils.Constant; import com.iformall.utils.RedisLock; @@ -30,6 +38,7 @@ import org.springframework.scheduling.annotation.AsyncResult; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.CollectionUtils; import java.net.URL; import java.util.*; @@ -63,6 +72,15 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { @Autowired RedisLock redisLock; + + @Autowired + ProjectFactory projectFactory; + + @Autowired + WxCUserBasicInfoService wxCUserBasicInfoService; + + @Autowired + ProductOrderService productOrderService; @Override public PageInfo listAsPage(UserMouldVideo record, Integer pageIndex, Integer pageSize) { @@ -71,6 +89,7 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { @Override public PageInfo cListAsPage(UserMouldVideo record, Integer pageIndex, Integer pageSize) { + record.setIsDel(EnumYesOrNo.NO.getCode()); return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> userMouldVideoMapper.findCList(record)); } @@ -83,7 +102,7 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { public UserMouldVideo getById(Long id) { return userMouldVideoMapper.selectById(id); } - + @Override public ResultData saveOrUpdate(UserMouldVideo record) { if(record.getPersonMouldId() != null){ @@ -349,11 +368,23 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { try{ AiVideoParam videoParam = new AiVideoParam(); + videoParam.setTask_id(mouldVideo.getId()); videoParam.setGen_txt(paperwork.replaceAll(Constant.text_pause, "[*]")); videoParam.setVideo_template_id(personMouldSmId); videoParam.setSubtitle(subtitleMap); videoParam.setVoice_id(voiceMouldSmId); videoParam.setVoice_style(voiceType); + videoParam.setTenancy_logo(Base64Util.imageUrlToBase64(Constant.hyLogo)); + + //查询用户是否有付费订单 + ProductOrder po = new ProductOrder(); + po.setUserId(mouldVideo.getUserId()); + Integer paidCount = productOrderService.findPaidCount(po); + if (null != paidCount && paidCount > 0 ) { + videoParam.setUser_level(1); + }else { + videoParam.setUser_level(0); + } AiVideoParam.VideoFiles videoFiles = new AiVideoParam.VideoFiles(); AiVideoParam.BackGround backGround = new AiVideoParam.BackGround(); backGround.setType(EnumVideoType.getEnum(mouldVideo.getVideoType()).getType()); @@ -391,10 +422,17 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { } videoParam.setVideo_files(videoFiles); - AiVideoResult video = AiVideoHelper.createVideo(videoParam,mouldVideo.getId()); + + AiVideoResult video = null; + if (!AiVideoHelper.localDeploy) { + video = AiVideoHelper.createVideo(videoParam); + }else { +// AiVideoResult video = AiVideoHelper.createVideo(videoParam,mouldVideo.getId()); + video = SmSdkUtils.generateVideo(videoParam); + } if(video.isSuccess()){ videoUpd.setVideoPath(video.getUrl()); -// videoUpd.setVideoTime(video.getDuration()+""); + videoUpd.setVideoTime(video.getDuration()+""); videoUpd.setVideoStatus(EnumVideoStatus.success.getCode()); videoUpd.setVideoMsg("success"); videoUpd.setCreateVideoDate(new Date()); @@ -435,6 +473,7 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { || EnumVideoStatus.upload_fail.getCode().equals(userMouldVideo.getVideoStatus())){ String url = AiVideoHelper.oral_broadcasting + mouldVideo.getVideoPath(); VideUploadResult result = videoFactory.getExcutor(videoType).uploadVideoPath(mouldVideo.getTitle(), url); + if(result.isSuccess()){ UserMouldVideo videoUpd = new UserMouldVideo(); videoUpd.setId(userMouldVideo.getId()); @@ -443,28 +482,47 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { this.saveOrUpdate(videoUpd); //实时判断上传状态 - for (int i = 0;i <= 30; i++){ + for (int i = 0;i <= 300; i++){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } String progress = videoFactory.getExcutor(videoType).getVedioUploadProgress(result.getVideoId()); - if (progress.equals("complete")) { - VideUploadResult videoDetail = videoFactory.getExcutor(videoType).getVideoDetailWithCache(result.getVideoId(),true); - if (videoDetail.isSuccess()){ - videoUpd = new UserMouldVideo(); - videoUpd.setId(userMouldVideo.getId()); - videoUpd.setCoverImg(videoDetail.getCoverURL()); - videoUpd.setVideoPlayUrl(videoDetail.getVideoUrl()); - videoUpd.setVideoTime(videoDetail.getDuration()); - videoUpd.setVideoSize(videoDetail.getSize()); - videoUpd.setVideoStatus(EnumVideoStatus.upload_success.getCode()); - videoUpd.setVideoMsg("视频上传成功"); - videoUpd.setUpdateDate(new Date()); - this.updateById(videoUpd); - break; - } + if (progress.equals("complete")) { + VideUploadResult videoDetail = videoFactory.getExcutor(videoType).getVideoDetailWithCache(result.getVideoId(),true); + + if (videoDetail.isSuccess()){ + videoUpd = new UserMouldVideo(); + videoUpd.setId(userMouldVideo.getId()); + videoUpd.setCoverImg(videoDetail.getCoverURL()); + videoUpd.setVideoPlayUrl(videoDetail.getVideoUrl()); + Double _vt = Double.valueOf(videoDetail.getDuration()); + if (null != _vt && _vt > 0) { + videoUpd.setVideoTime(videoDetail.getDuration()); + }else { + logger.info(" video no times:"+mouldVideo.getVideoTime()); + if (null != StringUtils.trimToNull(mouldVideo.getVideoTime())) { + videoUpd.setVideoTime(mouldVideo.getVideoTime()); + } + } + videoUpd.setVideoSize(videoDetail.getSize()); + videoUpd.setVideoStatus(EnumVideoStatus.upload_success.getCode()); + videoUpd.setVideoMsg("视频上传成功"); + videoUpd.setUpdateDate(new Date()); + //设置扣费,当前方法是慧影项目专用的 + if (StringUtils.isBlank(videoUpd.getVideoTime())) { + break; + } + CreateBilling cb = projectFactory.getProjectService(EnumProject.PROJECT_2.getCode()) + .handleCreateVideoBilling(userMouldVideo.getUserId(), userMouldVideo.getFinalTenantId(), videoUpd.getVideoTime(), videoUpd.getVideoSize()); + if (null != cb) { + videoUpd.setCostPoints(cb.getTotalCostPoins()); + videoUpd.setCostPointsDetail(cb.getDetail()); + } + this.updateById(videoUpd); + break; + } } } } @@ -489,6 +547,7 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { videoStatuss.add(EnumVideoStatus.success.getCode()); videoStatuss.add(EnumVideoStatus.upload_fail.getCode()); umVideoQ.setVideoStatuss(videoStatuss); + umVideoQ.setIsDel(EnumYesOrNo.NO.getCode()); return userMouldVideoMapper.getSortList(umVideoQ); } @@ -496,6 +555,7 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { public List getUpLoadIngList() { UserMouldVideo umVideoQ = new UserMouldVideo(); umVideoQ.setVideoStatus(EnumVideoStatus.upload_ing.getCode()); + umVideoQ.setIsDel(EnumYesOrNo.NO.getCode()); return userMouldVideoMapper.getSortList(umVideoQ); } @@ -511,4 +571,21 @@ public class UserMouldVideoServiceImpl implements UserMouldVideoService { return userMouldVideoMapper.getNotHaveUrl(umVideoQ); } + @Override + public UserMouldVideo getUserVideo(Long id) { + return userMouldVideoMapper.selectById(id); + } + + @Override + public ResultData checkVideoStatus(Long userId, List ids) { + if (CollectionUtils.isEmpty(ids)){ + return new ResultData(ErrorCode.VIDEO_CREATING.getCode(),""); + } + Integer integer = userMouldVideoMapper.checkVideoStatus(userId,ids); + if (integer > 0){ + return new ResultData("生成视频成功"); + } + return new ResultData(ErrorCode.VIDEO_CREATING.getCode(),"视频生成中"); + } + } diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceInfoServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceInfoServiceImpl.java index 402df0c..cadda70 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceInfoServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceInfoServiceImpl.java @@ -2,27 +2,28 @@ package com.iformall.service.sm.impl; import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.google.common.collect.Lists; import com.iformall.common.ErrorCode; -import com.iformall.common.ResultData; +import com.iformall.domain.vo.sm.PreviewVoiceVO; import com.iformall.domain.po.sm.VoiceInfo; import com.iformall.domain.vo.VoiceInfoVo; -import com.iformall.enums.EnumSex; import com.iformall.enums.EnumSpeakType; +import com.iformall.exception.BizException; import com.iformall.file.aliyun.bean.AliyunOSSConfig; import com.iformall.mapper.VoiceMapper; import com.iformall.service.sm.VoiceInfoService; import com.iformall.sm.*; +import com.iformall.smsdk.SmPreviewVideoDTO; +import com.iformall.smsdk.SmSdkUtils; import com.iformall.utils.Constant; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.util.ObjectUtils; import java.util.ArrayList; import java.util.List; +import java.util.Optional; @Service public class VoiceInfoServiceImpl implements VoiceInfoService { @@ -77,21 +78,31 @@ public class VoiceInfoServiceImpl implements VoiceInfoService { } @Override - public ResultData voicePreview(AiPreviewParam aiPreviewParam) { - VoiceInfo voiceInfo = voiceMapper.selectOne(new LambdaQueryWrapper().eq(VoiceInfo::getIsDel, 0).eq(VoiceInfo::getId, aiPreviewParam.getVoice_id())); - if (ObjectUtils.isEmpty(voiceInfo)){ - return new ResultData(ErrorCode.SYS_SERVER_ERROR.getCode(), "声音信息不存在"); - } + public PreviewVoiceVO previewVoice(AiPreviewParam aiPreviewParam) { + VoiceInfo voiceInfo = voiceMapper.selectOne(new LambdaQueryWrapper() + .eq(VoiceInfo::getIsDel, 0) + .eq(VoiceInfo::getId, aiPreviewParam.getVoice_id())); + voiceInfo = Optional.ofNullable(voiceInfo).orElseThrow(() -> new BizException(ErrorCode.SYS_SERVER_ERROR.getCode(), "声音信息不存在")); + AiPreviewParam param = new AiPreviewParam(); param.setGen_txt(aiPreviewParam.getGen_txt().replaceAll(Constant.text_pause,"[*]")); param.setVoice_id(voiceInfo.getMouldSmId()); param.setVoice_style(StringUtils.isBlank(aiPreviewParam.getVoice_style()) ? EnumSpeakType.default_0.getMessage() : aiPreviewParam.getVoice_style()); param.setGender(voiceInfo.getSex() == 1 ? "male" : "female"); - AiPreviewResult result = AiVideoHelper.voicePreview(param); + AiPreviewResult result = null; + if (!AiVideoHelper.localDeploy) { + result = AiVideoHelper.voicePreview(param); + }else { +// AiPreviewResult result = AiVideoHelper.voicePreview(param); + result = SmSdkUtils.preview(SmPreviewVideoDTO.mapping(param)); + } if (result.isSuccess()){ - return new ResultData(result.getTime()); + PreviewVoiceVO vo = new PreviewVoiceVO(); + vo.setTime(result.getTime()); + vo.setUrl(result.getUrl()); + return vo; } - return new ResultData(result.getCode(), result.getMsgInfo(result.getCode(),result.getMsg())); + throw new BizException(result.getCode(), result.getMsg()); } } diff --git a/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceLanguageServiceImpl.java b/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceLanguageServiceImpl.java index e52501e..af6f334 100644 --- a/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceLanguageServiceImpl.java +++ b/suimangService/src/main/java/com/iformall/service/sm/impl/VoiceLanguageServiceImpl.java @@ -2,25 +2,126 @@ package com.iformall.service.sm.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; import com.google.common.collect.Lists; +import com.iformall.common.IdWorker; +import com.iformall.constant.LanguageEnums; +import com.iformall.domain.po.sm.UserPersonMould; +import com.iformall.domain.po.sm.UserVoiceLanguage; import com.iformall.domain.po.sm.VoiceLanguage; +import com.iformall.language.LanguageDetect; +import com.iformall.mapper.UserVoiceLanguageMapper; import com.iformall.mapper.VoiceLanguageMapper; import com.iformall.service.sm.VoiceLanguageService; +import com.iformall.util.DetectUtils; import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; import java.util.List; +import java.util.Optional; @Service public class VoiceLanguageServiceImpl implements VoiceLanguageService { @Autowired private VoiceLanguageMapper voiceLanguageMapper; + + @Autowired + private UserVoiceLanguageMapper userVoiceLanguageMapper; + + @Override + public PageInfo listAsPage(VoiceLanguage record, Integer pageIndex, Integer pageSize) { + return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> voiceLanguageMapper.findList(record)); + } @Override - public List voiceTotal() { - List languages = voiceLanguageMapper.selectList(new LambdaQueryWrapper().eq(VoiceLanguage::getIsDel, 0).orderByAsc(VoiceLanguage::getLocal)); + public List voiceTotal(VoiceLanguage voiceLanguage) { + voiceLanguage.setIsDel(0); + voiceLanguage.setSortColumns("local asc"); + if (null != voiceLanguage.getCUserId()) { + UserVoiceLanguage uvl = new UserVoiceLanguage(); + uvl.setUserId(voiceLanguage.getCUserId()); + List vids = userVoiceLanguageMapper.findVoiceIdList(uvl); + if (null == vids || vids.size() <= 0) { + List vvids = new ArrayList(); + vvids.add(-1L); + voiceLanguage.setCustomizedVocideIds(vvids); + }else { + voiceLanguage.setCustomizedVocideIds(vids); + } + } + + List languages = voiceLanguageMapper.findList(voiceLanguage); return CollectionUtils.isEmpty(languages) ? Lists.newArrayList() : languages; } + + @Override + public VoiceLanguage getLanguage(String paperwork) { + // 文案中若包含指定语种,则规定为该语种 + String detectLanguage = DetectUtils.detectLanguage(paperwork); + detectLanguage = Optional.ofNullable(detectLanguage).orElseGet(() -> LanguageDetect.detect(paperwork)); + detectLanguage = DetectUtils.getLocalLanguage(detectLanguage); + + List voiceLanguages; + // 判断语种是否包含- + String split = ".*-.*"; + if (detectLanguage == null) { + voiceLanguages = voiceLanguageMapper.listByLocal(LanguageEnums.en_US.getLocal()); + } else if (detectLanguage.matches(split)) { + voiceLanguages = voiceLanguageMapper.listByLocal(detectLanguage); + } else { + voiceLanguages = voiceLanguageMapper.listByLanguage(detectLanguage); + } + + return voiceLanguages.get(0); + } + + @Override + public List listVoiceLanguage(String chineseName) { + List languages = voiceLanguageMapper.selectList(new LambdaQueryWrapper() + .eq(VoiceLanguage::getIsDel, 0) + .like(StringUtils.isNotBlank(chineseName), VoiceLanguage::getChineseName, chineseName) + .orderByAsc(VoiceLanguage::getLocal)); + return CollectionUtils.isEmpty(languages) ? Collections.emptyList() : languages; + } + + @Override + public List getUserVoiceIdList(List cUserIds) { + UserVoiceLanguage vl = new UserVoiceLanguage(); + vl.setCuserIds(cUserIds); + return userVoiceLanguageMapper.findVoiceIdList(vl); + } + + @Override + public void associatedUserVoices(List voicesIds, Long cUserId) { + userVoiceLanguageMapper.deleteByCuserId(cUserId); + if (null != voicesIds && voicesIds.size() > 0 ) { + List upmlist = new ArrayList(); + for (int i = 0 ; i < voicesIds.size() ; i ++) { + UserVoiceLanguage upm = new UserVoiceLanguage(); + upm.setId(IdWorker.get().nextId()); + upm.setUserId(cUserId); + upm.setVoiceLanguageId(voicesIds.get(i)); + upm.setCreateDate(new Date()); + upm.setUpdateDate(new Date()); + upmlist.add(upm); + } + userVoiceLanguageMapper.saveBatch(upmlist); + } + + } + + @Override + public List getCUserIds(Long voiceId) { + UserVoiceLanguage vl = new UserVoiceLanguage(); + vl.setVoiceLanguageId(voiceId); + return userVoiceLanguageMapper.findCUserIdList(vl); + } + } diff --git a/suimangService/src/main/java/com/iformall/sm/AiCheckPhotoParam.java b/suimangService/src/main/java/com/iformall/sm/AiCheckPhotoParam.java index ac52220..1028dd2 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiCheckPhotoParam.java +++ b/suimangService/src/main/java/com/iformall/sm/AiCheckPhotoParam.java @@ -6,5 +6,7 @@ import lombok.Data; public class AiCheckPhotoParam { private String img; + + private String token; } diff --git a/suimangService/src/main/java/com/iformall/sm/AiDigitalAvatarHelper.java b/suimangService/src/main/java/com/iformall/sm/AiDigitalAvatarHelper.java index af88e03..035ff79 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiDigitalAvatarHelper.java +++ b/suimangService/src/main/java/com/iformall/sm/AiDigitalAvatarHelper.java @@ -37,7 +37,7 @@ public class AiDigitalAvatarHelper { this.callbackUrl = callbackUrl; } - + //智象小程序人脸检测 public static AiCheckPhotoResult checkPhoto(AiCheckPhotoParam param) { // String response = HttpUtil.doAiVideoPost("http://nas.pucao.cn:2005/dec_face", JSONObject.toJSONString(param)); String response = HttpUtil.doAiVideoPost(digital_avatar + "/dec_face", JSONObject.toJSONString(param)); @@ -70,6 +70,7 @@ public class AiDigitalAvatarHelper { return result; } + //智象小程序生成 public static DigitalAvatarResult digitalAvatarPhoto(DigitalAvatarParam param,Long taskId) { param.setTask_id(taskId); @@ -154,6 +155,7 @@ public class AiDigitalAvatarHelper { } + //智象小程序生成logo public static ShareImgResult createShareImg(ShareImgParam param) { // log.info("生成照片start request:" + param.getBg_img()); diff --git a/suimangService/src/main/java/com/iformall/sm/AiPhotoSpeakResult.java b/suimangService/src/main/java/com/iformall/sm/AiPhotoSpeakResult.java index fce9184..aece0fd 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiPhotoSpeakResult.java +++ b/suimangService/src/main/java/com/iformall/sm/AiPhotoSpeakResult.java @@ -12,19 +12,4 @@ public class AiPhotoSpeakResult { private String saveDir; private String audioPath; - public String getMsgInfo(Integer code, String msg) { - if (code == 4000) { - return "成功"; - } else if (code == 3006 && msg.equals("miss parameter")) { - return "(MetaService)却少参数"; - } else if (code == 3007 && msg.equals("miss gen_txt")) { - return "(MetaService)没有检测到文本"; - } else if (code == 3008 && msg.equals("check languages")) { - return "(MetaService)文字和语种不对应"; - } else if (code == 4001 && msg.equals("long audio")) { - return "(MetaService)视频时长大于一分钟"; - } else { - return "(MetaService:" + msg + ")服务被Avatar攻击..."; - } - } } diff --git a/suimangService/src/main/java/com/iformall/sm/AiPreviewParam.java b/suimangService/src/main/java/com/iformall/sm/AiPreviewParam.java index dbaf272..a27b5d1 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiPreviewParam.java +++ b/suimangService/src/main/java/com/iformall/sm/AiPreviewParam.java @@ -9,5 +9,5 @@ public class AiPreviewParam { private String voice_style; private String gender; private int speed; - + private String token; } diff --git a/suimangService/src/main/java/com/iformall/sm/AiPreviewResult.java b/suimangService/src/main/java/com/iformall/sm/AiPreviewResult.java index 1f80c6a..fb87e24 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiPreviewResult.java +++ b/suimangService/src/main/java/com/iformall/sm/AiPreviewResult.java @@ -1,6 +1,5 @@ package com.iformall.sm; -import io.swagger.models.auth.In; import lombok.Data; @Data @@ -12,17 +11,4 @@ public class AiPreviewResult { private String url; private Double time; - public String getMsgInfo(Integer code, String msg) { - if (code == 3000) { - return "成功"; - } else if (code == 3006 && msg.equals("miss parameter")) { - return "(MetaService)缺少参数"; - } else if (code == 3007 && msg.equals("miss gen_txt")) { - return "(MetaService)没有检测到文本"; - } else if (code == 3008 && msg.equals("check languages")) { - return "(MetaService)文字和语种不对应"; - } else { - return "(MetaService)预览失败,请重试"; - } - } } diff --git a/suimangService/src/main/java/com/iformall/sm/AiTtsHelper.java b/suimangService/src/main/java/com/iformall/sm/AiTtsHelper.java new file mode 100644 index 0000000..f1e0d52 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/sm/AiTtsHelper.java @@ -0,0 +1,73 @@ +package com.iformall.sm; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.iformall.utils.Base64Util; +import com.iformall.utils.HttpUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +public class AiTtsHelper { + + public static String huibo_tts_wav; + @Value("${suimang.huibo_tts_wav}") + public void setHuiboTtsWav(String huibo_tts_wav) { + this.huibo_tts_wav = huibo_tts_wav; + } + + + public static String doPost(String url, String params) { + return HttpUtil.doAiVideoPost(url,params); + } + + //慧播预览 + public static AiPreviewResult voicePreview(AiPreviewParam param) { + String response = doPost(huibo_tts_wav + "/tts_wav", JSONObject.toJSONString(param)); + log.info("TTS音色预览 end response:" + response); + AiPreviewResult result = new AiPreviewResult(); + + if (StringUtils.isBlank(response)) { + result.setSuccess(false); + result.setMsg("(MetaService) no result"); + return result; + } + JSONObject jsonObject = JSON.parseObject(response); + JSONObject status = jsonObject.getJSONObject("status"); + + Integer code = status.getInteger("code"); + String msg = status.getString("msg"); + if (code == null) { + result.setSuccess(false); + result.setMsg("(MetaService) error."+msg); + return result; + } + if (code.intValue() == 3000) { + JSONObject data = jsonObject.getJSONObject("data"); + String strURL = data.getString("url"); + String time = data.getString("time"); + + result.setCode(200); + result.setSuccess(true); + result.setUrl(huibo_tts_wav + strURL); + result.setTime(Double.valueOf(time)); + result.setMsg("(MetaService) error."+msg); + } else { + result.setCode(code); + result.setSuccess(false); + result.setMsg("(MetaService) error."+msg); + } + return result; + } + + + + public static void main(String[] args) { + + } + + +} diff --git a/suimangService/src/main/java/com/iformall/sm/AiVideoHelper.java b/suimangService/src/main/java/com/iformall/sm/AiVideoHelper.java index 1e622ec..1521447 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiVideoHelper.java +++ b/suimangService/src/main/java/com/iformall/sm/AiVideoHelper.java @@ -37,13 +37,20 @@ public class AiVideoHelper { this.oral_broadcasting = oral_broadcasting; } + public static String video_tts; + @Value("${suimang.video_tts}") + public void setVideoTts(String video_tts) { + this.video_tts = video_tts; + } + public static String photo_speak; @Value("${suimang.photo_speak}") public void setPhotoSpeak(String photo_speak){ this.photo_speak = photo_speak; } - + public static String photo_speak_hy; + @Value("${suimang.photo_speak_hy}") public void setPhotoSpeakHy(String photo_speak_hy){ this.photo_speak_hy = photo_speak_hy; @@ -54,19 +61,35 @@ public class AiVideoHelper { public void setCallbackUrl(String callbackUrl){ this.callbackUrl = callbackUrl; } - + + public static boolean localDeploy;//是否是私有化部署 + @Value("${suimang.local_deploy}") + public void setLocalDeploy(boolean localDeploy) { + this.localDeploy = localDeploy; + } + + public static String token;//跟遂芒唯一验证 + @Value("${suimang.token}") + public void setToken(String token) { + this.token = token; + } public static String doPost(String url, String params) { return HttpUtil.doAiVideoPost(url,params); } - - public static AiVideoResult createVideo(AiVideoParam videoParam,Long taskId) { + //慧影生成视频 + public static AiVideoResult createVideo(AiVideoParam videoParam) { - videoParam.setTask_id(taskId); - videoParam.setCallback_url(callbackUrl + "/callback/oral/broadcasting"); +// videoParam.setTask_id(taskId); + if (StringUtils.isNotBlank(videoParam.getCallback_url())) { + videoParam.setCallback_url(videoParam.getCallback_url()); + } else { + videoParam.setCallback_url(callbackUrl + "/callback/oral/broadcasting"); + } - log.info("生成视频start request:" + videoParam.neglectImgString()); + videoParam.setToken(token); + log.info("生成视频start request:" + videoParam.toSimpelJson()); String response = doPost(oral_broadcasting+"/gen_dh_video", JSONObject.toJSONString(videoParam)); log.info("生成视频end response:"+response); @@ -124,8 +147,10 @@ public class AiVideoHelper { // } } + //慧语(照片说话)图片质量检查 public static AiCheckPhotoResult checkPhoto(AiCheckPhotoParam param) { // String response = doPost("http://111.198.0.15:22299" + "/image_qualit", JSONObject.toJSONString(param)); + param.setToken(token); String response = doPost(photo_speak + "/image_qualit", JSONObject.toJSONString(param)); log.info("图片质量审核 end response:" + response); AiCheckPhotoResult result = new AiCheckPhotoResult(); @@ -158,14 +183,17 @@ public class AiVideoHelper { return result; } + //慧语(照片说话)+慧影 预览 public static AiPreviewResult voicePreview(AiPreviewParam param) { - String response = doPost(photo_speak + "/tts_wav", JSONObject.toJSONString(param)); + param.setToken(token); + log.info("TTS音色预览 start request:" + JSONObject.toJSONString(param)); + String response = doPost(video_tts + "/tts_wav", JSONObject.toJSONString(param)); log.info("TTS音色预览 end response:" + response); AiPreviewResult result = new AiPreviewResult(); if (StringUtils.isBlank(response)) { result.setSuccess(false); - result.setMsg("(MetaService)TTS音色预览失败,请稍后重试"); + result.setMsg("(MetaService) no result"); return result; } JSONObject jsonObject = JSON.parseObject(response); @@ -182,25 +210,24 @@ public class AiVideoHelper { String msg = status.getString("msg"); if (code == null) { result.setSuccess(false); - result.setMsg("(MetaService)TTS音色预览异常,请稍后重试"); + result.setMsg("(MetaService) error,"+msg); return result; } if (code.intValue() == 3000) { result.setCode(200); result.setSuccess(true); - result.setUrl(photo_speak + strURL); + result.setUrl(video_tts + strURL); result.setTime(Double.valueOf(time)); - String resultMsg = result.getMsgInfo(code, msg); - result.setMsg(resultMsg); + result.setMsg("(MetaService) error,"+msg); } else { result.setCode(code); result.setSuccess(false); - String resultMsg = result.getMsgInfo(code, msg); - result.setMsg(resultMsg); + result.setMsg("(MetaService) error,"+msg); } return result; } - + + //慧语(照片说话)生成 public static AiPhotoSpeakResult createPhotoSpeakVideo(AiPhotoSpeakParam videoParam,Long taskId) { videoParam.setTask_id(taskId); @@ -212,7 +239,7 @@ public class AiVideoHelper { AiPhotoSpeakResult result = new AiPhotoSpeakResult(); if (StringUtils.isBlank(response)) { result.setSuccess(false); - result.setMsg("(MetaService empty)服务被Avatar攻击..."); + result.setMsg("(MetaService) not result"); return result; } @@ -222,7 +249,7 @@ public class AiVideoHelper { String msg = status.getString("msg"); if (code == null) { result.setSuccess(false); - result.setMsg("(MetaService code empty)服务被Avatar攻击..."); + result.setMsg("(MetaService) error."+msg); return result; } @@ -236,17 +263,16 @@ public class AiVideoHelper { result.setSaveDir(saveDir); result.setCode(code); result.setAudioPath(audioPath); - String resultMsg = result.getMsgInfo(code, msg); - result.setMsg(resultMsg); + result.setMsg("(MetaService) error."+msg); } else { result.setSuccess(false); result.setCode(code); - String resultMsg = result.getMsgInfo(code, msg); - result.setMsg(resultMsg); + result.setMsg("(MetaService) error."+msg); } return result; } + //慧语(照片说话)超分生成 public static AiVideoHqResult videoHq(AiVideoHqParam param,Long taskId) { param.setTask_id(taskId); diff --git a/suimangService/src/main/java/com/iformall/sm/AiVideoParam.java b/suimangService/src/main/java/com/iformall/sm/AiVideoParam.java index cf1b461..546cc46 100644 --- a/suimangService/src/main/java/com/iformall/sm/AiVideoParam.java +++ b/suimangService/src/main/java/com/iformall/sm/AiVideoParam.java @@ -1,12 +1,20 @@ package com.iformall.sm; import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.aliyun.openservices.shade.org.apache.commons.lang3.StringUtils; + import lombok.Data; import java.util.List; import java.util.Map; +/** + * https://note.youdao.com/s/7OZ5UfES + * @author Administrator + * + */ @Data public class AiVideoParam { /** @@ -41,55 +49,36 @@ public class AiVideoParam { private String voice_style; private String url = "None";//预留音频url private VideoFiles video_files; + private String token; + private String tenancy_logo; + private Integer user_level; private Map subtitle; - public String neglectImgString(){ - StringBuffer str = new StringBuffer(); - str.append("{"); - str.append("\"gen_txt\":").append("\"").append(gen_txt).append("\","); - str.append("\"video_template_id\":").append("\"").append(video_template_id).append("\","); - str.append("\"voice_id\":").append("\"").append(voice_id).append("\","); - str.append("\"voice_style\":").append("\"").append(voice_style).append("\","); - if(video_files != null){ - str.append("\"video_files\":").append("{"); - if(video_files.getBack_ground() != null){ - str.append("\"back_ground\":").append("{") - .append("\"image\":").append("\"").append("\",") - .append("\"type\":").append("\"").append(video_files.getBack_ground().getType()).append("\"") - .append("},"); + public String toSimpelJson() { + String json = JSON.toJSONString(this); + JSONObject obj = JSON.parseObject(json); + JSONObject vf = obj.getJSONObject("video_files"); + if (null != vf ) { + JSONObject bg = vf.getJSONObject("back_ground"); + if ( null != bg) { + bg.remove("image"); } - if(video_files.getDigital_human() != null){ - str.append("\"digital_human\":").append("{") - .append("\"coord\":").append(JSONObject.toJSONString(video_files.getDigital_human().getCoord())).append(",") - .append("\"level\":").append(video_files.getDigital_human().getLevel()).append(",") - .append("\"ratio\":").append(video_files.getDigital_human().getRatio()) - .append("},"); + JSONObject dh = vf.getJSONObject("digital_human"); + if ( null != dh) { + dh.remove("image"); } - if(video_files.getMaterial() != null && video_files.getMaterial().size() > 0){ - str.append("\"material\":").append("["); - for (Material material:video_files.getMaterial()) { - if(material != null){ - str.append("{"); - str.append("\"coord\":").append(JSONObject.toJSONString(material.getCoord())).append(",") - .append("\"image\":").append("\"").append("\",") - .append("\"level\":").append(material.getLevel()).append(",") - .append("\"ratio\":").append(material.getRatio()); - str.append("},"); - } + JSONArray ms = vf.getJSONArray("material"); + if (null != ms && ms.size() > 0 ) { + for (int i = 0 ; i < ms.size(); i++) { + JSONObject jo = ms.getJSONObject(i); + jo.remove("image"); } - str.deleteCharAt(str.length()-1); - str.append("]"); } - str.append("},"); } - str.deleteCharAt(str.length()-1); - str.append("\"subtitle\":").append(JSON.toJSONString(subtitle)); - str.append("}"); - - return str.toString(); + return JSON.toJSONString(obj); } - + @Data public static class VideoFiles { private BackGround back_ground; diff --git a/suimangService/src/main/java/com/iformall/smsdk/HttpComponentsClientRestfulHttpRequestFactory.java b/suimangService/src/main/java/com/iformall/smsdk/HttpComponentsClientRestfulHttpRequestFactory.java new file mode 100644 index 0000000..21e067f --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/HttpComponentsClientRestfulHttpRequestFactory.java @@ -0,0 +1,31 @@ +package com.iformall.smsdk; + +import java.net.URI; + +import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; +import org.apache.http.client.methods.HttpUriRequest; +import org.springframework.http.HttpMethod; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; + +public class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory{ + + + @Override + protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) { + if (httpMethod == HttpMethod.GET) { + return new HttpGetRequestWithEntity(uri); + } + return super.createHttpUriRequest(httpMethod, uri); + } + //核心代码 + private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase { + public HttpGetRequestWithEntity(final URI uri) { + super.setURI(uri); + } + + @Override + public String getMethod() { + return HttpMethod.GET.name(); + } + } +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmGenerateVideoDTO.java b/suimangService/src/main/java/com/iformall/smsdk/SmGenerateVideoDTO.java new file mode 100644 index 0000000..da463e8 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmGenerateVideoDTO.java @@ -0,0 +1,23 @@ +package com.iformall.smsdk; + +import com.iformall.domain.po.sm.UserMouldVideo; +import com.iformall.sm.AiVideoParam; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "生成视频请求参数") +@Data +public class SmGenerateVideoDTO { + @ApiModelProperty(value = "类型") + private Integer type; + @ApiModelProperty(value = "生成视频参数") + private AiVideoParam aiVideoParam; + + public static SmGenerateVideoDTO build(AiVideoParam aiVideoParam, Integer type) { + SmGenerateVideoDTO dto = new SmGenerateVideoDTO(); + dto.setType(type); + dto.setAiVideoParam(aiVideoParam); + return dto; + } +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmPreviewVideoDTO.java b/suimangService/src/main/java/com/iformall/smsdk/SmPreviewVideoDTO.java new file mode 100644 index 0000000..ef73c06 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmPreviewVideoDTO.java @@ -0,0 +1,28 @@ +package com.iformall.smsdk; + +import com.iformall.sm.AiPreviewParam; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +@ApiModel(value = "预览视频请求参数") +@Data +public class SmPreviewVideoDTO { + @ApiModelProperty("文案") + private String paperwork; + @ApiModelProperty("声音id") + private String voiceId; + @ApiModelProperty("声音风格名称") + private String voiceStyle; + @ApiModelProperty("性别") + private String gender; + + public static SmPreviewVideoDTO mapping(AiPreviewParam aiPreviewParam) { + SmPreviewVideoDTO dto = new SmPreviewVideoDTO(); + dto.setPaperwork(aiPreviewParam.getGen_txt()); + dto.setVoiceId(aiPreviewParam.getVoice_id()); + dto.setVoiceStyle(aiPreviewParam.getVoice_style()); + dto.setGender(aiPreviewParam.getGender()); + return dto; + } +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmSdkConstant.java b/suimangService/src/main/java/com/iformall/smsdk/SmSdkConstant.java new file mode 100644 index 0000000..8cbb650 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmSdkConstant.java @@ -0,0 +1,47 @@ +package com.iformall.smsdk; + +/** + * 遂芒sdk常量 + * + * @author xmzhao71 + * @date 2023-10-19 + */ +public interface SmSdkConstant { + + /** + * 请求头参数 + */ + String APP_KEY = "appKey"; + String SIGN = "sign"; + + /** + * 请求参数,必填 + */ + String TIMESTAMP = "timeStamp"; + + + /** + * 预览视频 + */ + String PREVIEW_VIDEO = "/api/video/previewVideo"; + + /** + * 生成视频 + */ + String GENERATE_VIDEO = "/api/video/generateVideo"; + + /** + * 当前接入方 + */ + String CURRENT_SERVICE_INFO = "/api/serviceInfo/current"; + + /** + * 当前接入方生成视频记录 + */ + String CURRENT_SERVICE_VIDEO_RECORDS = "/api/serviceInfo/currentVideoRecords"; + + /** + * 当前接入方生成视频记录 + */ + String CURRENT_SERVICE_VIDEO_TOTALS = "/api/serviceInfo/currentVideoTotals"; +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmSdkProperties.java b/suimangService/src/main/java/com/iformall/smsdk/SmSdkProperties.java new file mode 100644 index 0000000..4b3e210 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmSdkProperties.java @@ -0,0 +1,21 @@ +package com.iformall.smsdk; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * 遂芒sdk调用凭证 + * + * @author xmzhao71 + * @date 2023-10-20 + */ +@Data +@Component +@ConfigurationProperties(prefix = "sdk.sm") +public class SmSdkProperties { + /** + * 域名 + */ + private String baseUrl; +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmSdkUtils.java b/suimangService/src/main/java/com/iformall/smsdk/SmSdkUtils.java new file mode 100644 index 0000000..b7e83e7 --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmSdkUtils.java @@ -0,0 +1,109 @@ +package com.iformall.smsdk; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import com.iformall.domain.po.sm.ServiceInfo; +import com.iformall.domain.po.sm.ServiceVideoRecord; +import com.iformall.sm.AiPreviewResult; +import com.iformall.sm.AiVideoParam; +import com.iformall.sm.AiVideoResult; +import com.iformall.utils.JsonUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Component; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestTemplate; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; + +import java.util.HashMap; +import java.util.Map; + +@Slf4j +@Component +public class SmSdkUtils { + private static SmSdkUtils smSdkUtils; + + @Resource(name = "restTemplate") + private RestTemplate restTemplate; + + @Autowired + private SmSdkProperties smSdkProperties; + + @PostConstruct + public void init() { + smSdkUtils = this; + initRestTemplate(); + } + + private void initRestTemplate() { + //修改restTemplate的RequestFactory使其支持Get携带body参数 + restTemplate.setRequestFactory(new HttpComponentsClientRestfulHttpRequestFactory()); + } + + //POST + public static AiPreviewResult preview(SmPreviewVideoDTO dto) { + String url = smSdkUtils.smSdkProperties.getBaseUrl() + SmSdkConstant.PREVIEW_VIDEO; + log.info("(遂芒api)【预览视频】接口的请求参数:{}", JSON.toJSON(dto)); + ResponseEntity response = smSdkUtils.restTemplate.exchange(url, HttpMethod.POST, SmUtils.getHttpEntity(JSON.parseObject(JSON.toJSONString(dto), Map.class)), String.class); + log.info("(遂芒api)【预览视频】接口的响应数据:{}", JSON.toJSON(response.getBody())); + JSONObject resultObject = JSON.parseObject(response.getBody()); + String data = resultObject.getString("data"); + return StringUtils.isNotBlank(data) ? JSON.parseObject(data, AiPreviewResult.class) : new AiPreviewResult(); + } + + //POST + public static AiVideoResult generateVideo(AiVideoParam aiVideoParam) { + String url = smSdkUtils.smSdkProperties.getBaseUrl() + SmSdkConstant.GENERATE_VIDEO; +// log.info("(遂芒api)【生成视频】接口的请求参数:{}", JSON.toJSONString(dto)); + log.info("(遂芒api)【生成视频】接口的请求参数:{}", JSON.toJSON(aiVideoParam.getTask_id())); + ResponseEntity response = smSdkUtils.restTemplate.exchange(url, HttpMethod.POST, SmUtils.getHttpEntity(JSON.parseObject(JSON.toJSONString(aiVideoParam), Map.class)), String.class); + log.info("(遂芒api)【生成视频】接口的响应数据:{}", JSON.toJSON(response.getBody())); + JSONObject resultObject = JSON.parseObject(response.getBody()); + String data = resultObject.getString("data"); + return StringUtils.isNotBlank(data) ? JSON.parseObject(data, AiVideoResult.class) : new AiVideoResult(); + } + + //GET + public static ServiceInfo getCurrentServiceInfo() { + String url = smSdkUtils.smSdkProperties.getBaseUrl() + SmSdkConstant.CURRENT_SERVICE_INFO; + Map param = new HashMap(); + HttpEntity> httEntity = SmUtils.getHttpEntity(param); + ResponseEntity response = smSdkUtils.restTemplate.exchange(url, HttpMethod.GET,httEntity , String.class); + log.info("(遂芒api)【查询当前接入方】接口的响应数据:{}", JSON.toJSON(response.getBody())); + JSONObject resultObject = JSON.parseObject(response.getBody()); + String data = resultObject.getString("data"); + return StringUtils.isNotBlank(data) ? JSON.parseObject(data, ServiceInfo.class) : new ServiceInfo(); + } + + //GET + public static PageInfo currentVideoRecords(int pageNum,int pageSize) { + Map parm = new HashMap(); + parm.put("pageNum", pageNum); + parm.put("pageSize", pageSize); + HttpEntity> httEntity = SmUtils.getHttpEntity(parm); + String url = smSdkUtils.smSdkProperties.getBaseUrl() + SmSdkConstant.CURRENT_SERVICE_VIDEO_RECORDS+"?pageNum="+pageNum+"&pageSize="+pageSize; + ResponseEntity response = smSdkUtils.restTemplate.exchange(url, HttpMethod.GET, httEntity, String.class); + log.info("(遂芒api)【查询当前接入方】接口的响应数据:{}", JSON.toJSON(response.getBody())); + JSONObject resultObject = JSON.parseObject(response.getBody()); + String data = resultObject.getString("data"); + return StringUtils.isNotBlank(data) ? JSON.parseObject(data, PageInfo.class) : new PageInfo(); + } + + public static Float currentVideoTotals() { + Map parm = new HashMap(); + HttpEntity> httEntity = SmUtils.getHttpEntity(parm); + String url = smSdkUtils.smSdkProperties.getBaseUrl() + SmSdkConstant.CURRENT_SERVICE_VIDEO_TOTALS; + ResponseEntity response = smSdkUtils.restTemplate.exchange(url, HttpMethod.GET, httEntity, String.class); + log.info("(遂芒api)【查询当前接入方】接口的响应数据:{}", JSON.toJSON(response.getBody())); + JSONObject resultObject = JSON.parseObject(response.getBody()); + String data = resultObject.getString("data"); + return StringUtils.isNotBlank(data) ? Float.parseFloat(data) : 0; + } +} diff --git a/suimangService/src/main/java/com/iformall/smsdk/SmUtils.java b/suimangService/src/main/java/com/iformall/smsdk/SmUtils.java new file mode 100644 index 0000000..3aa899e --- /dev/null +++ b/suimangService/src/main/java/com/iformall/smsdk/SmUtils.java @@ -0,0 +1,53 @@ +package com.iformall.smsdk; + +import com.alibaba.fastjson.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.iformall.common.CommonConstants; +import com.iformall.domain.po.WxThirdPartyApi; +import com.iformall.enums.sm.EnumThirdPartyType; +import com.iformall.mapper.WxThirdPartyApiMapper; +import com.iformall.utils.sign.SignUtils; +import org.apache.http.protocol.HTTP; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.MultiValueMap; + +import javax.annotation.PostConstruct; +import java.util.List; +import java.util.Map; + +@Component +public class SmUtils { + public static SmUtils smUtils; + @Autowired + private SmSdkProperties smSdkProperties; + @Autowired + private WxThirdPartyApiMapper wxThirdPartyApiMapper; + + @PostConstruct + public void init() { + smUtils = this; + } + + public static HttpEntity> getHttpEntity(Map paramMap) { + paramMap.put(SmSdkConstant.TIMESTAMP, System.currentTimeMillis()); + WxThirdPartyApi apiConfig = getApiConfig(); + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + httpHeaders.set(SmSdkConstant.APP_KEY, apiConfig.getAppId() + "&" + apiConfig.getAppKey()); + String sign = SignUtils.getSign(apiConfig.getSignKey(), paramMap, "MD5"); + httpHeaders.set(SmSdkConstant.SIGN, sign); + return new HttpEntity<>(paramMap, httpHeaders); + } + + //私有化统一用系统的来调用 + public static WxThirdPartyApi getApiConfig() { + List wxThirdPartyApis = smUtils.wxThirdPartyApiMapper.selectList(new LambdaQueryWrapper() + .eq(WxThirdPartyApi::getStatus, CommonConstants.STATUS_NORMAL).eq(WxThirdPartyApi::getType, EnumThirdPartyType.PRIVATE_JOIN.getCode())); + return wxThirdPartyApis.get(0); + } +} diff --git a/suimangService/src/main/java/com/iformall/utils/Constant.java b/suimangService/src/main/java/com/iformall/utils/Constant.java index a5236ed..7a3efae 100644 --- a/suimangService/src/main/java/com/iformall/utils/Constant.java +++ b/suimangService/src/main/java/com/iformall/utils/Constant.java @@ -69,7 +69,8 @@ public class Constant { public static final String APP_Id = "APP_Id"; public static final String APP_NAME = "APP_NAME"; public static final String APP_INFO = "APPINFO"; - + public static final String SERVICE_ID = "SERVICE_ID"; + public static final String LOGIN_B_USER_KEY = "LOGIN_B_USER_KEY"; @@ -119,5 +120,13 @@ public class Constant { public static final Integer wiwideNewPlat = 1;//新平台 public static final String text_pause = "\uD83D\uDD57"; + + //慧影每分钟消耗金币数 + public static final Integer hyCostPoinsPerMinites = 1; + //慧影注册送金币数 + public static final Integer hyRegeisterPoins = 5; + //慧影项目生成视频logo + public static final String hyLogo=""; + } diff --git a/suimangService/src/main/java/com/iformall/utils/MaUtil.java b/suimangService/src/main/java/com/iformall/utils/MaUtil.java index 1a3092e..ec6e06f 100644 --- a/suimangService/src/main/java/com/iformall/utils/MaUtil.java +++ b/suimangService/src/main/java/com/iformall/utils/MaUtil.java @@ -3,9 +3,18 @@ package com.iformall.utils; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; +import com.alibaba.fastjson.JSONObject; +import com.alipay.api.AlipayApiException; +import com.alipay.api.AlipayClient; +import com.alipay.api.AlipayConfig; +import com.alipay.api.CertAlipayRequest; +import com.alipay.api.DefaultAlipayClient; +import com.alipay.api.request.AlipayTradePagePayRequest; +import com.alipay.api.response.AlipayTradePagePayResponse; import com.github.binarywang.wxpay.config.WxPayConfig; import com.github.binarywang.wxpay.service.WxPayService; import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl; +import com.iformall.common.ErrorCode; import com.iformall.common.FmHttpClientBuilder; import com.iformall.domain.po.WxAppinfo; import com.iformall.domain.po.WxPayAccount; @@ -23,8 +32,10 @@ import com.iformall.douyin.web.api.TtWebService; import com.iformall.douyin.web.api.impl.TtWebServiceImpl; import com.iformall.douyin.web.config.TtWebDefaultConfigImpl; import com.iformall.douyin.web.enums.TtWebApiBeginEnum; +import com.iformall.exception.MallinkException; import com.iformall.mapper.WxAppinfoMapper; import com.iformall.service.WxAppinfoService; +import com.iformall.service.pay.service.pay.entity.PayAdapterResult; import lombok.extern.flogger.Flogger; import me.chanjar.weixin.common.error.WxErrorException; import org.apache.commons.lang3.StringUtils; @@ -56,6 +67,9 @@ public class MaUtil { private static Map webServiceMap = new ConcurrentHashMap(); private static Map webServiceKeyMap = new ConcurrentHashMap(); + + private static Map alipayClientMap = new ConcurrentHashMap(); + private static Map alipayClientKeyMap = new ConcurrentHashMap(); public WxMaService getWeappService(WxAppinfo appinfo) { WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); @@ -290,4 +304,73 @@ public class MaUtil { } return service; } + + public AlipayClient getAliPayClient(WxAppinfo appinfo, WxPayAccount payAccount) { + AlipayConfig alipayConfig = new AlipayConfig(); + + alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do"); + alipayConfig.setAppId(appinfo.getAppId()); + alipayConfig.setPrivateKey(appinfo.getSecret()); + alipayConfig.setFormat("json"); + alipayConfig.setCharset("UTF-8"); + alipayConfig.setAlipayPublicKey(payAccount.getMerchantApiKey()); + alipayConfig.setSignType("RSA2"); + + String key = appinfo.getAppId()+"_byPublicKey"; + AlipayClient alipayClient = alipayClientMap.get(key); + if(alipayClient == null){ + synchronized("getAliPayClientBlock"+appinfo.getAppId()) { + alipayClient = alipayClientMap.get(key); + if (null == alipayClient) { + try { + alipayClient = new DefaultAlipayClient(alipayConfig); + alipayClientMap.put(key, alipayClient); + } catch (AlipayApiException e) { + e.printStackTrace(); + } + } + } + } + if(alipayClient == null){ + throw new MallinkException(ErrorCode.APP_PLAT_ERROR.getCode(),"获取支付配置失败"); + } + return alipayClient; + } + + public AlipayClient getAliPayCertClient(WxAppinfo appinfo, WxPayAccount payAccount) { + + CertAlipayRequest certAlipayRequest = new CertAlipayRequest(); + certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do"); + certAlipayRequest.setAppId(appinfo.getAppId()); + certAlipayRequest.setPrivateKey(appinfo.getSecret()); + certAlipayRequest.setFormat("json"); + certAlipayRequest.setCharset("UTF-8"); + certAlipayRequest.setSignType("RSA2"); + certAlipayRequest.setCertPath(payAccount.getMerchantCertPath()); + certAlipayRequest.setAlipayPublicCertPath(payAccount.getMerchantKeyPath()); + certAlipayRequest.setRootCertPath(payAccount.getMerchantCertPemPath()); + + String key = appinfo.getAppId()+"_byCert"; + AlipayClient alipayClient = alipayClientMap.get(key); + if(alipayClient == null){ + synchronized("getAliPayClientBlock"+appinfo.getAppId()) { + alipayClient = alipayClientMap.get(key); + if (null == alipayClient) { + try { + alipayClient = new DefaultAlipayClient(certAlipayRequest); + alipayClientMap.put(key, alipayClient); + } catch (AlipayApiException e) { + e.printStackTrace(); + logger.error("AlipayClient error.",e); + } + } + } + } + if(alipayClient == null){ + throw new MallinkException(ErrorCode.APP_PLAT_ERROR.getCode(),"获取支付配置失败"); + } + + return alipayClient; + } + } diff --git a/suimangService/src/main/resources/mapper/ApiDetailMapper.xml b/suimangService/src/main/resources/mapper/ApiDetailMapper.xml new file mode 100644 index 0000000..0640ff1 --- /dev/null +++ b/suimangService/src/main/resources/mapper/ApiDetailMapper.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + + id,create_time,update_time, + menu_id,menu_name,charge_flag, + auth_flag,description,platform_url, + public_param,request_param,response_param, + request_sample,response_sample,exception_sample + + diff --git a/suimangService/src/main/resources/mapper/ApiGuideMapper.xml b/suimangService/src/main/resources/mapper/ApiGuideMapper.xml new file mode 100644 index 0000000..dda42cf --- /dev/null +++ b/suimangService/src/main/resources/mapper/ApiGuideMapper.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + id,create_time,update_time, + release_time,name,content, + status,delete_flag + + + + WHERE 1 = 1 + + and `id` = #{id} + + + and `name` = #{name} + + + and `status` = #{status} + + + + + diff --git a/suimangService/src/main/resources/mapper/ApiMenuMapper.xml b/suimangService/src/main/resources/mapper/ApiMenuMapper.xml new file mode 100644 index 0000000..f5765dd --- /dev/null +++ b/suimangService/src/main/resources/mapper/ApiMenuMapper.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + m.id,m.create_time,m.update_time, + m.name,m.parent_id,m.status, + m.leaf_flag,m.delete_flag,m.content + + + + WHERE m.delete_flag = 0 + + AND m.`id` = #{id} + + + AND m.`parent_id` = #{parentId} + + + AND m.`name` = #{name} + + + AND m.`status = #{status} + + + + + + diff --git a/suimangService/src/main/resources/mapper/MallUserInfoMapper.xml b/suimangService/src/main/resources/mapper/MallUserInfoMapper.xml index 75fd3bb..267ba7b 100644 --- a/suimangService/src/main/resources/mapper/MallUserInfoMapper.xml +++ b/suimangService/src/main/resources/mapper/MallUserInfoMapper.xml @@ -18,14 +18,15 @@ + - `id`,`tenant_id`,`parent_tenant_id`,`username`,`name`,`password`,`create_time`,`last_login_time`,`status`,`is_admin`,`invest_rule`,`nick_name`,`phone`,`web_open_id`,email + `id`,`tenant_id`,`parent_tenant_id`,`username`,`name`,`password`,`create_time`,`last_login_time`,`status`,`is_admin`,`invest_rule`,`nick_name`,`phone`,`web_open_id`,email,`project_type` - `id`,`tenant_id`,`parent_tenant_id`,`username`,`name`,`password`,`create_time`,`last_login_time`,`status`,`is_admin`,`invest_rule`,`nick_name`,`phone`, + `id`,`tenant_id`,`parent_tenant_id`,`username`,`name`,`password`,`create_time`,`last_login_time`,`status`,`is_admin`,`invest_rule`,`nick_name`,`phone`,`project_type` `bopen_id`,`web_open_id`,email @@ -89,6 +90,9 @@ and `email` = #{email} + + and `project_type` = #{projectType} + and `web_open_id` is not null @@ -122,6 +126,9 @@ and username=#{username} + + and project_type=#{projectType} + @@ -284,6 +294,7 @@ + @@ -293,13 +304,13 @@ u.`id`,u.`tenant_id`,u.`parent_tenant_id`,u.`username`,u.`name`,u.`password`,u.`create_time`,u.`last_login_time`,u.`status`,u.`is_admin`,u.`invest_rule`,u.`nick_name`,u.`phone`, - m.`name` as mall_name, m.`group` as mall_group, m.`img_url`, m.`img_url_h`,email + m.`name` as mall_name, m.`group` as mall_group, m.`img_url`, m.`img_url_h`,u.email,u.`project_type` u.`id`,u.`tenant_id`,u.`parent_tenant_id`,u.`username`,u.`name`,u.`password`,u.`create_time`,u.`last_login_time`,u.`status`,u.`is_admin`,u.`invest_rule`,u.`nick_name`,u.`phone`, u.`bopen_id`,u.`web_open_id`, - m.`name` as mall_name, m.`group` as mall_group, m.`img_url`, m.`img_url_h`,email + m.`name` as mall_name, m.`group` as mall_group, m.`img_url`, m.`img_url_h`,u.email,u.`project_type` @@ -312,6 +323,9 @@ and u.`phone` = #{phone} + + and u.project_type=#{projectType} + @@ -128,7 +150,7 @@ `id`, `video_type`, `cover_img`, `cover_picture`, `title`, `sub_title`, `sex`, `age`, `colour`, `scene_sign`, `sale_price`, `price`, `send_type`, `mould_sm_id`,`material`,`background_id`,`background_material`, - `status`, `create_date`, `update_date` + `status`, `create_date`, `update_date`,`customized` from person_mould diff --git a/suimangService/src/main/resources/mapper/ProductMapper.xml b/suimangService/src/main/resources/mapper/ProductMapper.xml index 553cc64..c3339ae 100644 --- a/suimangService/src/main/resources/mapper/ProductMapper.xml +++ b/suimangService/src/main/resources/mapper/ProductMapper.xml @@ -7,6 +7,7 @@ + @@ -21,7 +22,7 @@ - `id`,`tenant_id`,`parent_tenant_id`,`project_type`,`type`, + `id`,`tenant_id`,`parent_tenant_id`,`project_type`,`type`,`extra_id`, `cover_img`,`title`,`en_title`,`glod`,`detail`, `price_dollar`,`sell_price_dollar`,`price_rmb`,`sell_price_rmb`, `create_date`,`update_date` diff --git a/suimangService/src/main/resources/mapper/ProductOrderMapper.xml b/suimangService/src/main/resources/mapper/ProductOrderMapper.xml index 900f264..14b88a4 100644 --- a/suimangService/src/main/resources/mapper/ProductOrderMapper.xml +++ b/suimangService/src/main/resources/mapper/ProductOrderMapper.xml @@ -17,7 +17,6 @@ - @@ -30,7 +29,7 @@ `id`,`order_number`,`tenant_id`,`parent_tenant_id`,`user_id`,`product_id`,`product_title`,`product_en_title`,`order_status`, `project_type`,`pay_vendor`,`order_price`,`create_date`,`update_date`, - `remark`,`order_id`,`open_id`,`profit_sharing`,`transaction_id`,`payment`,`payment_time`,`pay_way` + `remark`,`open_id`,`profit_sharing`,`transaction_id`,`payment`,`payment_time`,`pay_way` @@ -67,10 +66,6 @@ and `project_type` = #{projectType} and `pay_vendor` = #{payVendor} - - - and `order_id` = #{orderId} - and `profit_sharing` = #{profitSharing} @@ -101,6 +96,13 @@ #{sItem} + + + and user_id in + + #{uidItem} + + and id in @@ -117,6 +119,12 @@ from product_order + + @@ -126,9 +134,15 @@ ,`open_id` = #{openId} + + ,`pay_vendor` = #{payVendor} + ,`transaction_id` = #{transactionId} + + ,`payment` = #{payment} + ,`payment_time` = #{paymentTime} diff --git a/suimangService/src/main/resources/mapper/ProductOrderPayMapper.xml b/suimangService/src/main/resources/mapper/ProductOrderPayMapper.xml new file mode 100644 index 0000000..a3077f7 --- /dev/null +++ b/suimangService/src/main/resources/mapper/ProductOrderPayMapper.xml @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `id`,`tenant_id`,`parent_tenant_id`,`order_id`,`order_number`,`pay_amount`,`user_id`,`order_detail`,`open_id`, + `project_type`,`pay_vendor`,`ip`,`transaction_id`,`pay_order_status`,`pay_time`,`fail_reason` + `pay_way`,`profit_sharing`,`create_date`,`update_date` + + + + where 1 = 1 + + + and `id` = #{id} + + + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + + + and `order_id` = #{orderId} + + + and `order_number` = #{orderNumber} + + + + and `user_id` = #{userId} + + + and `project_type` = #{projectType} + and `pay_vendor` = #{payVendor} + + + and `transaction_id` = #{transactionId} + + + + and `profit_sharing` = #{profitSharing} + + + + and `pay_order_status` = #{payOrderStatus} + + + and `create_date` >= #{startDate} + + + and `create_date` <= #{endDate} + + + and `pay_time` >= #{payStartDate} + + + and `pay_time` <= #{payEndDate} + + + + and id in + + #{idItem} + + + order by ${sortColumns} + + + + + + + update product_order_pay + set `pay_order_status` = #{payOrderStatus} + ,`update_date` = #{updateDate} + + ,`open_id` = #{openId} + + + ,`transaction_id` = #{transactionId} + + + ,`pay_time` = #{payTime} + + + ,`pay_way` = #{payWay} + + where id = #{id} + and `pay_order_status` != #{payOrderStatus} + + and `pay_order_status` = #{isOrderStatus} + + + + + + + + + update product_order_pay + set `pay_order_status` = #{payOrderStatus} + ,`update_date` = now() + where `order_id` = #{orderId} + + + diff --git a/suimangService/src/main/resources/mapper/ProductOrderRefundMapper.xml b/suimangService/src/main/resources/mapper/ProductOrderRefundMapper.xml new file mode 100644 index 0000000..8156253 --- /dev/null +++ b/suimangService/src/main/resources/mapper/ProductOrderRefundMapper.xml @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `id`,`tenant_id`,`parent_tenant_id`,`order_id`,`order_number`,`project_type`,`pay_vendor`, + `user_id`,`pay_id`,`transaction_id`,`pay_amount`, + `refund_amount`,`refund_order_status`,`fail_reason`,`refund_id`,`refund_reason`,`refund_description` + `create_date`,`update_date` + + + + where 1 = 1 + + + and `id` = #{id} + + + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + + + and `order_id` = #{orderId} + + + and `order_number` = #{orderNumber} + + and `project_type` = #{projectType} + and `pay_vendor` = #{payVendor} + + + and `user_id` = #{userId} + + + and `pay_id` = #{payId} + + + + and `transaction_id` = #{transactionId} + + + + and `refund_order_status` = #{refundOrderStatus} + + + and `create_date` >= #{startDate} + + + and `create_date` <= #{endDate} + + + + and id in + + #{idItem} + + + order by ${sortColumns} + + + + + + + update product_order_pay + set `pay_order_status` = #{payOrderStatus} + ,`update_date` = #{updateDate} + + ,`open_id` = #{openId} + + + ,`transaction_id` = #{transactionId} + + + ,`pay_time` = #{payTime} + + + ,`pay_way` = #{payWay} + + where id = #{id} + and `pay_order_status` != #{payOrderStatus} + + and `pay_order_status` = #{isOrderStatus} + + + + + + + + + update product_order_pay + set `pay_order_status` = #{payOrderStatus} + ,`update_date` = now() + where `order_id` = #{orderId} + + + diff --git a/suimangService/src/main/resources/mapper/ProjectPackageDetailMapper.xml b/suimangService/src/main/resources/mapper/ProjectPackageDetailMapper.xml new file mode 100644 index 0000000..3730e0c --- /dev/null +++ b/suimangService/src/main/resources/mapper/ProjectPackageDetailMapper.xml @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + `id`,`tenant_id`,`parent_tenant_id`,`project_type`,`package_id`, + `invite_user_credit`,`ai_photo_price`,`ai_script_price`,`video_price`, + `is_video_watermark`,`language`,`sound`, + `video_time`,`ai_photo`,`is_sing`,`ai_script`,`video_format`,`template`, + `create_date`,`update_date` + + + + where is_del = 0 + and `id` = #{id} + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + and `project_type` = #{projectType} + + and `package_id` = #{packageId} + + + + and `create_date` >= #{startDate} + + + and `create_date` <= #{endDate} + + + + and id in + + #{idItem} + + + order by ${sortColumns} + + + + + + + + diff --git a/suimangService/src/main/resources/mapper/ServiceInfoMapper.xml b/suimangService/src/main/resources/mapper/ServiceInfoMapper.xml new file mode 100644 index 0000000..f4e0dc8 --- /dev/null +++ b/suimangService/src/main/resources/mapper/ServiceInfoMapper.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + `id`, `create_time`, `update_time`, `name`, `address`, `code`, `type`, `status`, `del_flag`, `mall_user_info`,`remaining_times` + + + + where 1 = 1 + + and `id` = #{id} + + + and `name` LIKE CONCAT('%', #{name},'%') + + + and `code` = #{code} + + + and `type` = #{type} + + + and `status` = #{status} + + + and `del_flag` = #{delFlag} + + + and `mall_user_info` = #{mallUserInfo} + + + + + + + update service_info set remaining_times = remaining_times - #{seconds} where id = #{id} + + + + \ No newline at end of file diff --git a/suimangService/src/main/resources/mapper/ServicePersonMouldMapper.xml b/suimangService/src/main/resources/mapper/ServicePersonMouldMapper.xml new file mode 100644 index 0000000..ca5279e --- /dev/null +++ b/suimangService/src/main/resources/mapper/ServicePersonMouldMapper.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + `id`, `person_mould_id`, `service_id`, `create_date`, `update_date` + + + + where 1 = 1 + + + and `id` = #{id} + + + + and id in + + #{idItem} + + + + order by customized desc,${sortColumns} + + + + + + delete from service_person_mould where service_id = #{serviceId} + + + + INSERT INTO service_person_mould (`id`, `person_mould_id`, `service_id`,`create_date`, `update_date`) + VALUES + + ( + #{item.id}, + #{item.personMouldId}, + #{item.serviceId}, + #{item.createDate}, + #{item.updateDate} + ) + + + + diff --git a/suimangService/src/main/resources/mapper/ServiceVideoRecordMapper.xml b/suimangService/src/main/resources/mapper/ServiceVideoRecordMapper.xml new file mode 100644 index 0000000..6df0b10 --- /dev/null +++ b/suimangService/src/main/resources/mapper/ServiceVideoRecordMapper.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/suimangService/src/main/resources/mapper/UserLevelCreditLogMapper.xml b/suimangService/src/main/resources/mapper/UserLevelCreditLogMapper.xml new file mode 100644 index 0000000..03a243d --- /dev/null +++ b/suimangService/src/main/resources/mapper/UserLevelCreditLogMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + `id`,`tenant_id`,`parent_tenant_id`,`user_id`, + `project_type`,`type`,`befour_credit`,`credit_num`,`after_credit`, + `extra_id`,`remark`,`detail`,`create_date` + + + + where 1 = 1 + and `id` = #{id} + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + and `user_id` = #{userId} + and `project_type` = #{projectType} + and `type` = #{type} + + and `extra_id` = #{extraId} + + + + and `create_date` >= #{startDate} + + + and `create_date` <= #{endDate} + + + + and id in + + #{idItem} + + + + + and extra_id in + + #{extIdItem} + + + order by ${sortColumns} + + + + + diff --git a/suimangService/src/main/resources/mapper/UserLevelPackageMapper.xml b/suimangService/src/main/resources/mapper/UserLevelPackageMapper.xml new file mode 100644 index 0000000..0ba9174 --- /dev/null +++ b/suimangService/src/main/resources/mapper/UserLevelPackageMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + `id`,`tenant_id`,`parent_tenant_id`, + `package_id`,`package_level`,`package_color`, + `user_credits`,`residue_credits`, + `expires_date`, `create_date`, `update_date` + + + + where 1 = 1 + and `id` = #{id} + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + + and `package_id` = #{packageId} + and `package_level` = #{packageLevel} + + + and id in + + #{idItem} + + + order by ${sortColumns} + + + + + + update user_level_package + set `update_date` = #{updateDate} + + ,`user_credits` = user_credits+#{addSumCredits} + + ,`residue_credits` = residue_credits+#{addCredits} + where id = #{id} + + + + update user_level_package + set `update_date` = #{updateDate} + ,`residue_credits` = residue_credits+#{reduceCredits} + where id = #{id} + and residue_credits+#{reduceCredits} >= 0 + + + diff --git a/suimangService/src/main/resources/mapper/UserMouldVideoMapper.xml b/suimangService/src/main/resources/mapper/UserMouldVideoMapper.xml index f312790..c5cf283 100644 --- a/suimangService/src/main/resources/mapper/UserMouldVideoMapper.xml +++ b/suimangService/src/main/resources/mapper/UserMouldVideoMapper.xml @@ -35,21 +35,31 @@ + + + + `id`, `tenant_id`, `parent_tenant_id`, `user_id`, `video_type`, - `person_mould_id`, `person_mould_sm`,`person_json`, `subtitle_enabled`, `subtitle_params`, `voice_mould_id`, `voice_mould_sm`, `languages`, `paperwork`, `background_id`, `background_sm`,`material_ids`,`material_all_json`, - `title`, `cover_img`, `remark`, `video_id`, `video_path`, `video_play_url`, `video_time`, `video_size`, `video_status`, `video_msg`, `create_video_date`, `create_date`, `update_date` + `person_mould_id`, `person_mould_sm`,`person_json`, `subtitle_enabled`, `subtitle_params`, `voice_mould_id`, `voice_mould_sm`, `languages`, + `paperwork`, `background_id`, `background_sm`,`material_ids`,`material_all_json`,`title`, `cover_img`, `remark`, `video_id`, `video_path`, + `video_play_url`, `video_time`, `video_size`, `video_status`, `video_msg`, `create_video_date`, `create_date`, `update_date`,`cost_points`, + `cost_points_detail`,`is_del` - where `is_del` = 0 + where 1 = 1 and `id` = #{id} + + and `is_del` = #{isDel} + + and `tenant_id` = #{tenantId} @@ -80,6 +90,10 @@ and `title` like concat('%', #{title},'%') + + + and `paperwork` like concat('%', #{paperwork},'%') + and `video_status` = #{videoStatus} @@ -105,6 +119,13 @@ #{videoStatusItem} + + + and user_id in + + #{cidItem} + + and id in @@ -132,7 +153,7 @@ `id`, `video_type`, `paperwork`, `title`, `cover_img`, `remark`, `video_id`, `video_path`, `video_play_url`, `video_time`, `video_size`, `video_status`, `video_msg`, - `create_video_date`, `create_date`, `update_date` + `create_video_date`, `create_date`, `update_date`,`cost_points`,`cost_points_detail`,`is_del` from user_mould_video @@ -152,7 +173,7 @@ + + diff --git a/suimangService/src/main/resources/mapper/UserPersonMouldMapper.xml b/suimangService/src/main/resources/mapper/UserPersonMouldMapper.xml new file mode 100644 index 0000000..4579b69 --- /dev/null +++ b/suimangService/src/main/resources/mapper/UserPersonMouldMapper.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + `id`, `person_mould_id`, `c_user_id`, `create_date`, `update_date` + + + + where 1 = 1 + + + and `id` = #{id} + + + + and id in + + #{idItem} + + + + order by customized desc,${sortColumns} + + + + + + + + delete from user_person_mould where c_user_id = #{cUserId} + + + + INSERT INTO user_person_mould (`id`, `person_mould_id`, `c_user_id`,`create_date`, `update_date`) + VALUES + + ( + #{item.id}, + #{item.personMouldId}, + #{item.userId}, + #{item.createDate}, + #{item.updateDate} + ) + + + + diff --git a/suimangService/src/main/resources/mapper/UserVoiceLanguageMapper.xml b/suimangService/src/main/resources/mapper/UserVoiceLanguageMapper.xml new file mode 100644 index 0000000..34f9086 --- /dev/null +++ b/suimangService/src/main/resources/mapper/UserVoiceLanguageMapper.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + + + `id`, `voice_language_id`, `c_user_id`, `create_date`, `update_date` + + + + where 1 = 1 + + + and `id` = #{id} + + + + and id in + + #{idItem} + + + + order by customized desc,${sortColumns} + + + + + + + + delete from user_voice_language where c_user_id = #{cUserId} + + + + INSERT INTO user_voice_language (`id`, `voice_language_id`, `c_user_id`,`create_date`, `update_date`) + VALUES + + ( + #{item.id}, + #{item.voiceLanguageId}, + #{item.userId}, + #{item.createDate}, + #{item.updateDate} + ) + + + + diff --git a/suimangService/src/main/resources/mapper/VoiceLanguageMapper.xml b/suimangService/src/main/resources/mapper/VoiceLanguageMapper.xml index 039a587..828144c 100644 --- a/suimangService/src/main/resources/mapper/VoiceLanguageMapper.xml +++ b/suimangService/src/main/resources/mapper/VoiceLanguageMapper.xml @@ -1,6 +1,78 @@ + + + + + + + + + + + + + + + + + + + `id`, `tenant_id`, `parent_tenant_id`, `language`, `country`, `local`, `name`, `chinese_name`, `img`, `create_date`, + `update_date`, `is_del`,`customized` + + + + where 1 = 1 + + + and `id` = #{id} + + + and `tenant_id` = #{tenantId} + + + and `parent_tenant_id` = #{parentTenantId} + + + and `is_del` = #{isDel} + + + + and ( customized = 0 or (customized = 1 + and id in + + #{cIdItem} + + )) + + + + and customized = 0 + + + + and customized = 1 + + + + and id in + + #{idItem} + + + + order by customized desc,${sortColumns} + + + + INSERT INTO voice_language (`id`, `country`, `language`, `local`, `name`, `img`, `is_del`,`chinese_name`) @@ -18,4 +90,22 @@ ) + + diff --git a/suimangService/src/main/resources/mapper/WxCUserBasicInfoMapper.xml b/suimangService/src/main/resources/mapper/WxCUserBasicInfoMapper.xml index 4feab76..58b5c77 100644 --- a/suimangService/src/main/resources/mapper/WxCUserBasicInfoMapper.xml +++ b/suimangService/src/main/resources/mapper/WxCUserBasicInfoMapper.xml @@ -580,5 +580,13 @@ {call cuser_old_to_new(#{oldCuserId},#{newCuserId},#{tableIndex},#{finalTableIndex})} + + + UPDATE wx_c_user_basic_info set poins = poins - #{reductPoints} where id = #{id} + + + + UPDATE wx_c_user_basic_info set poins = poins + #{addPoints} where id = #{id} + \ No newline at end of file diff --git a/suimangService/src/main/resources/mapper/WxCVideoMapper.xml b/suimangService/src/main/resources/mapper/WxCVideoMapper.xml index 0dc0e45..753b489 100644 --- a/suimangService/src/main/resources/mapper/WxCVideoMapper.xml +++ b/suimangService/src/main/resources/mapper/WxCVideoMapper.xml @@ -14,6 +14,7 @@ + @@ -27,16 +28,16 @@ --> select wca.user_name,wca.resource_id,wca.expire_time,vi.id,vi.language_id,vi.sex,vi.display_name,vi.local_name,vi.mould_sm_id,vi.style_list, -vl.name,vl.chinese_name +vl.name,vl.chinese_name,vl.trial_text FROM wx_c_author wca join voice_info vi on wca.resource_id = vi.id join voice_language vl on vi.language_id =vl.id diff --git a/suimangService/src/main/resources/mapper/WxMsgValidationcodeMapper.xml b/suimangService/src/main/resources/mapper/WxMsgValidationcodeMapper.xml index 7d83260..3961c4d 100644 --- a/suimangService/src/main/resources/mapper/WxMsgValidationcodeMapper.xml +++ b/suimangService/src/main/resources/mapper/WxMsgValidationcodeMapper.xml @@ -12,10 +12,11 @@ + - `id`,`tenant_id`,`parent_tenant_id`,`phone`,`expiretime`,`createtime`,`type`,`msg`,`signature`,`code` + `id`,`tenant_id`,`parent_tenant_id`,`phone`,`expiretime`,`createtime`,`type`,`msg`,`signature`,`code`,`project_type` @@ -35,6 +36,7 @@ and `signature` = #{signature} and `code` = #{code} and date_format(`createtime`,'%Y-%m-%d') = #{createtimeStr} + and `project_type` = #{projectType} and id in diff --git a/suimangService/src/main/resources/mapper/WxThirdPartyApiMapper.xml b/suimangService/src/main/resources/mapper/WxThirdPartyApiMapper.xml index 85a0e4b..411a0c7 100644 --- a/suimangService/src/main/resources/mapper/WxThirdPartyApiMapper.xml +++ b/suimangService/src/main/resources/mapper/WxThirdPartyApiMapper.xml @@ -10,19 +10,41 @@ - - - - `id`,`tenant_id`,`parent_tenant_id`,`type`,`name`,`app_id`,`app_key`,`sign_key`,`api_url`, `token`,`token_expired_time`,`user_name`,`password`,`version`,`remark`,`tp_id` + `id`, `tenant_id`, `parent_tenant_id`, `type`, `name`, `service_id`, `app_id`, `app_key`, `sign_key`, `token`, `token_expired_time`, `version`, `tp_id`, `remark`, `status` + + + WHERE 1 = 1 + + AND `id` = #{id} + + + AND `type` = #{type} + + + AND `name` = #{name} + + + AND `service_id` = #{serviceId} + + + AND `app_id` = #{appId} + + + AND `app_key` = #{appKey} + + + AND `status` = #{status} + + where 1 = 1 @@ -62,6 +84,10 @@ - - + diff --git a/suimangVideo/.gitignore b/suimangVideo/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/suimangVideo/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/suimangVideo/src/main/java/com/iformall/constant/LanguageEnums.java b/suimangVideo/src/main/java/com/iformall/constant/LanguageEnums.java new file mode 100644 index 0000000..b4320a2 --- /dev/null +++ b/suimangVideo/src/main/java/com/iformall/constant/LanguageEnums.java @@ -0,0 +1,52 @@ +package com.iformall.constant; + + +/** + * 地区语言列表(具体到地区语言) + * 主要用来做默认语言常量 + * + * @author xmzhao71 + * @date 2023-10-13 + */ +public enum LanguageEnums { + en_US("en", "US", "en-US", "英语(美国)"), + zh_CN("zh", "CN", "zh-CN", "中文(普通话,简体)"), + ; + + LanguageEnums(String language, String country, String local, String desc) { + this.language = language; + this.country = country; + this.local = local; + this.desc = desc; + } + + private String language; + private String country; + private String local; + private String desc; + + public String getLanguage() { + return language; + } + + public String getCountry() { + return country; + } + + public String getLocal() { + return local; + } + + public String getDesc() { + return desc; + } + + public static LanguageEnums getEnum(String language) { + for (LanguageEnums value : values()) { + if (value.getLanguage().equals(language)) { + return value; + } + } + return null; + } +} diff --git a/suimangVideo/src/main/java/com/iformall/language/LanguageDetect.java b/suimangVideo/src/main/java/com/iformall/language/LanguageDetect.java index c9f75a2..7304977 100644 --- a/suimangVideo/src/main/java/com/iformall/language/LanguageDetect.java +++ b/suimangVideo/src/main/java/com/iformall/language/LanguageDetect.java @@ -1,105 +1,114 @@ package com.iformall.language; -import com.alibaba.fastjson.JSONObject; import com.cybozu.labs.langdetect.Detector; import com.cybozu.labs.langdetect.DetectorFactory; import com.cybozu.labs.langdetect.LangDetectException; -import com.google.common.io.ByteStreams; import lombok.extern.slf4j.Slf4j; -import lombok.var; +import org.apache.commons.io.IOUtils; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; -import org.springframework.util.StreamUtils; -import sun.misc.IOUtils; import java.io.IOException; import java.io.InputStream; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; @Slf4j public class LanguageDetect { - private static Detector initDetector(){ + private static Detector initDetector() { try { -// DetectorFactory.loadProfile(Thread.currentThread().getContextClassLoader().getResource("profiles").getPath()); -// return DetectorFactory.create(); List profile = new ArrayList<>(); - try { PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("classpath:profiles/*"); - for (Resource resource:resources) { - InputStream inputStream = resource.getInputStream(); -// String str = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8); - String str = new String(ByteStreams.toByteArray(inputStream)); - profile.add(str); -// InputStream inputStream = resource.getInputStream(); -// byte[] bytes = new byte[(int) resource.contentLength()]; -// inputStream.read(bytes); -// profile.add(new String(bytes)); + for (Resource resource : resources) { + InputStream inputStream = resource.getInputStream(); + String str = new String(IOUtils.toByteArray(inputStream)); + profile.add(str); } } catch (IOException e) { e.printStackTrace(); } - if(!profile.isEmpty()){ + if (!profile.isEmpty()) { DetectorFactory.clear(); DetectorFactory.loadProfile(profile); return DetectorFactory.create(); } } catch (LangDetectException e) { e.printStackTrace(); - log.error("语言检测初始化错误。"+e.getMessage()); + log.error("语言检测初始化错误。" + e.getMessage()); } return null; } - public static String detect(String str){ + public static String detect(String str) { Detector detector = initDetector(); - if(detector == null){ + if (detector == null) { return null; } detector.append(str); -// try { -// detect.getProbabilities(); -// } catch (LangDetectException e) { -// e.printStackTrace(); -// } - try { String language = detector.detect(); log.info("语种识别(" + str + ")-----" + language); return language; } catch (LangDetectException e) { - e.printStackTrace(); - log.error("语言检测错误。"); + log.error("语言检测错误", e); } return null; } - public static void main(String[] args) { -// var resolver = new PathMatchingResourcePatternResolver(); -// Resource[] resources = new Resource[0]; -// try { -// resources = resolver.getResources("classpath:profiles/*"); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// for (var resource:resources) { -// System.out.println(resource.getFilename()); -// try { -// byte[] bytes = new byte[0]; -// bytes = new byte[resource.getInputStream().available()]; -// resource.getInputStream().read(bytes); -// String str = new String(bytes); -// System.out.println(str); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// -// } + private static void test() { + // 测试用方法 + PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); + Resource[] resources = new Resource[0]; + try { + resources = resolver.getResources("classpath:profiles/*"); + } catch (IOException e) { + e.printStackTrace(); + } + for (Resource resource : resources) { + System.out.println(resource.getFilename()); + try { + byte[] bytes = new byte[0]; + bytes = new byte[resource.getInputStream().available()]; + resource.getInputStream().read(bytes); + String str = new String(bytes); + System.out.println(str); + } catch (IOException e) { + e.printStackTrace(); + } + + } System.out.println(detect("科技公司")); + System.out.println(detect("科技公司有哪几家做的还不错呢,其中就有我们这一家")); + System.out.println(detect("中国科技还行吧")); + System.out.println(detect("中国")); + System.out.println(detect("梦想")); + System.out.println(detect("I am a teacher")); + System.out.println(detect("I am a 老师")); + System.out.println(detect("行人從非機動車道變換車道到機動車道,激動的叫起來了")); + System.out.println(detect("おはよう")); + + System.out.println("======================================="); + String regex = ".*[\u4e00-\u9fa5]+.*"; +// String regex2 = "\b.*[a-zA-Z]+.*\b"; + + String regex3 = ".*-.*"; + System.out.println("I am a 老师".matches(regex)); + System.out.println("I am a teacher".matches(regex)); + System.out.println("I am a 我們".matches(regex)); + System.out.println("行人從非機動車道變換車道到機動車道,激動的叫起來了".matches(regex)); + + System.out.println("======================================="); +// System.out.println("I am a 老师".matches(regex2)); +// System.out.println("I am a teacher".matches(regex2)); +// System.out.println("abcdefg".matches(regex2)); +// System.out.println("abc d e fg".matches(regex2)); + + System.out.println("======================================="); + System.out.println("abc".matches(regex3)); + System.out.println("a-bc".matches(regex3)); } } diff --git a/suimangVideo/src/main/java/com/iformall/util/DetectUtils.java b/suimangVideo/src/main/java/com/iformall/util/DetectUtils.java new file mode 100644 index 0000000..e3a11e6 --- /dev/null +++ b/suimangVideo/src/main/java/com/iformall/util/DetectUtils.java @@ -0,0 +1,45 @@ +package com.iformall.util; + +import com.iformall.constant.LanguageEnums; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 语种检测类 + * + * @author xmzhao71 + * @date 2023-10-13 + */ +public class DetectUtils { + + /** + * 检测语言是否包含指定语种 + * + * @param text 文案 + * @return {@link String} 指定地区语种 + */ + public static String detectLanguage(String text) { + String zhCNRegex = ".*[\u4e00-\u9fa5]+.*"; + if (text.matches(zhCNRegex)) { + return LanguageEnums.zh_CN.getLocal(); + } + return null; + } + + /** + * 获取地区语言 + * + * @param detectLanguage 检测语言 + * @return {@link String} 指定地区语言 + */ + public static String getLocalLanguage(String detectLanguage) { + if (detectLanguage == null) { + return null; + } + if (detectLanguage.equalsIgnoreCase(LanguageEnums.en_US.getLanguage())) { + return LanguageEnums.en_US.getLocal(); + } + return detectLanguage; + } +} \ No newline at end of file diff --git a/suimangVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java b/suimangVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java index c565cb0..939067e 100644 --- a/suimangVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java +++ b/suimangVideo/src/main/java/com/iformall/video/aliyun/AliyunVideoExcutor.java @@ -151,9 +151,12 @@ public class AliyunVideoExcutor implements VideoExcutor { }else{ VideUploadResult result = getVideoDetailFromApi(videoId); if(this.videoStatus.equals(result.getStatus())){ - if(StringUtils.isNotBlank(result.getDuration()) && !"0.0".equals(result.getDuration())){ + if(StringUtils.isNotBlank(result.getVideoUrl())){ UploadCacheHelper.cacheVideoDetail(redisTemplate, videoId,result); } +// if(StringUtils.isNotBlank(result.getDuration()) && !"0.0".equals(result.getDuration())){ +// UploadCacheHelper.cacheVideoDetail(redisTemplate, videoId,result); +// } }else{ //还不能播放 result.setSuccess(false);