Commit 465f130c authored by jiaorz's avatar jiaorz

Merge branch 'master' into master-count-vehicle

parents be343ca5 5468d332
package com.github.wxiaoqi.security.common.util;
import javax.servlet.http.HttpServletRequest;
public class UserAgentUtil {
/**
* 关键字: 微信浏览器
*/
public static final String KEY_WEIXIN_BROWSER = "micromessenger";
/**
* 判断是否微信浏览器
*
* @param user_agent
* @return
*/
public static boolean isWexinBrowser(HttpServletRequest request) {
// 可能会出现npe
String user_agent = "";
user_agent = request.getHeader("user-agent");
// 修改如下
return user_agent != null && user_agent.toLowerCase().indexOf(KEY_WEIXIN_BROWSER) > 0;
}
}
package com.github.wxiaoqi.security.admin.rest; package com.github.wxiaoqi.security.admin.rest;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.biz.*; import com.github.wxiaoqi.security.admin.biz.*;
import com.github.wxiaoqi.security.admin.entity.*; import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO; import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
...@@ -40,6 +41,10 @@ public class PublicController { ...@@ -40,6 +41,10 @@ public class PublicController {
@Autowired @Autowired
private AppUserDetailBiz detailBiz; private AppUserDetailBiz detailBiz;
@Autowired
private AppUserLoginBiz appUserLoginBiz;
@Autowired @Autowired
private BaseUserMemberBiz userMemberBiz; private BaseUserMemberBiz userMemberBiz;
...@@ -85,6 +90,23 @@ public class PublicController { ...@@ -85,6 +90,23 @@ public class PublicController {
return ObjectRestResponse.succ(getAppUserInfoById(id)); return ObjectRestResponse.succ(getAppUserInfoById(id));
} }
@RequestMapping(value = "/app/userinfo-by-username", method = RequestMethod.GET)
public @ResponseBody
ObjectRestResponse<AppUserDTO> userDetailByUsername(String name) throws Exception {
AppUserLogin appUserLogin;
if (StrUtil.isBlank(name)) {
throw new BaseException(ResultCode.NOTEXIST_CODE
, new HashSet<String>() {{add("用户名不存在!");}});
}else {
appUserLogin = appUserLoginBiz.selectOne(new AppUserLogin(){{setUsername(name);}});
if(null == appUserLogin) {
throw new BaseException(ResultCode.NOTEXIST_CODE
, new HashSet<String>() {{add("用户名不存在!");}});
}
}
return ObjectRestResponse.succ(getAppUserInfoById(appUserLogin.getId()));
}
private AppUserDTO getAppUserInfoById(Integer userid) throws IllegalAccessException, InvocationTargetException { private AppUserDTO getAppUserInfoById(Integer userid) throws IllegalAccessException, InvocationTargetException {
AppUserDTO userDTO=new AppUserDTO(); AppUserDTO userDTO=new AppUserDTO();
//获取用户基础信息 //获取用户基础信息
......
...@@ -239,7 +239,7 @@ public class AppPermissionService { ...@@ -239,7 +239,7 @@ public class AppPermissionService {
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED) @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public JSONObject register(String username, String password, String headimgurl, public JSONObject register(String username, String password, String headimgurl,
String nickname, String mobilecode, String openId, String unionid, Integer type,String code) { String nickname, String mobilecode, String openId, String unionid, Integer type,String code) {
log.info("register------code====="+code); log.info("register------code====="+code+"----开始进入方法---time===="+System.currentTimeMillis()/1000L);
String activityCode = null; String activityCode = null;
// 判断参数和验证码 // 判断参数和验证码
if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(mobilecode)) { if (StringUtils.isBlank(username) || StringUtils.isBlank(password) || StringUtils.isBlank(mobilecode)) {
...@@ -247,7 +247,7 @@ public class AppPermissionService { ...@@ -247,7 +247,7 @@ public class AppPermissionService {
} }
String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode; String redisLockKey = RedisKey.CONSTANT_CODE_PREFIX + username + mobilecode;
String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString(); String mobilecodeRedis = userRedisTemplate.opsForValue().get(redisLockKey) == null ? "" : userRedisTemplate.opsForValue().get(redisLockKey).toString();
log.error("注册接口,获取redis中的验证码:" + mobilecodeRedis); log.info("注册接口,获取redis中的验证码:" + mobilecodeRedis+"---time===="+System.currentTimeMillis()/1000L);
// 获取到缓存的验证码后要先清空缓存对应键的值 // 获取到缓存的验证码后要先清空缓存对应键的值
userRedisTemplate.delete(redisLockKey); userRedisTemplate.delete(redisLockKey);
if (StringUtils.isBlank(mobilecodeRedis)) { if (StringUtils.isBlank(mobilecodeRedis)) {
...@@ -282,7 +282,7 @@ public class AppPermissionService { ...@@ -282,7 +282,7 @@ public class AppPermissionService {
appUserLogin.setUpdatetime(now); appUserLogin.setUpdatetime(now);
appUserLoginBiz.insertSelective(appUserLogin); appUserLoginBiz.insertSelective(appUserLogin);
Integer userid = appUserLogin.getId(); Integer userid = appUserLogin.getId();
log.error("注册:新增登陆用户信息: " + userid); log.info("注册:新增登陆用户信息: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 新增用户详情 // 新增用户详情
AppUserDetail rsUserDetail = new AppUserDetail(); AppUserDetail rsUserDetail = new AppUserDetail();
rsUserDetail.setUserid(userid); rsUserDetail.setUserid(userid);
...@@ -292,7 +292,9 @@ public class AppPermissionService { ...@@ -292,7 +292,9 @@ public class AppPermissionService {
rsUserDetail.setUpdatetime(now); rsUserDetail.setUpdatetime(now);
rsUserDetail.setIsdel(0); rsUserDetail.setIsdel(0);
rsUserDetail.setCrtHost(getIp()); rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail);
//setCreateIPInfo(rsUserDetail);
log.info("注册:解析地址后: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//邀请人id关系绑定 //邀请人id关系绑定
Integer parentId=0; Integer parentId=0;
if (StringUtils.isNotBlank(code)){ if (StringUtils.isNotBlank(code)){
...@@ -314,21 +316,27 @@ public class AppPermissionService { ...@@ -314,21 +316,27 @@ public class AppPermissionService {
//生成邀请码 长度改为8 不然重复率太高 //生成邀请码 长度改为8 不然重复率太高
rsUserDetail.setCode(ReferralCodeUtil.encode(userid)); rsUserDetail.setCode(ReferralCodeUtil.encode(userid));
appUserDetailBiz.insertSelective(rsUserDetail); appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid); log.info("注册:新增用户详情: " + userid+"---time===="+System.currentTimeMillis()/1000L);
/* //绑定上下线关系 /* //绑定上下线关系
if(parentId!=null&&parentId>0){ if(parentId!=null&&parentId>0){
relationBiz.bindRelation(userid,parentId,1); relationBiz.bindRelation(userid,parentId,1);
}*/ }*/
//临时会员绑定 //临时会员绑定
insertUserMemberByUserIdAndPhone(userid, username); insertUserMemberByUserIdAndPhone(userid, username);
log.info("注册:临时会员绑定: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//参加新人活动 //参加新人活动
jionActivity(userid); jionActivity(userid);
log.info("注册:参加新人活动: " + userid+"---time===="+System.currentTimeMillis()/1000L);
//创建钱包 //创建钱包
walletBiz.createWalletByUserId(appUserLogin.getId()); walletBiz.createWalletByUserId(appUserLogin.getId());
log.info("注册:创建钱包: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 登录结果要做做统一处理 // 登录结果要做做统一处理
JSONObject data = autoLogin(userid, username, headimgurl, nickname,code,activityCode,1); JSONObject data = autoLogin(userid, username, headimgurl, nickname,code,activityCode,1);
log.info("注册:登录结果要做做统一处理: " + userid+"---time===="+System.currentTimeMillis()/1000L);
// 到im注册,获取返回结果 // 到im注册,获取返回结果
Map<String, Object> map = registerIm(username, appUserLogin.getPassword(), nickname); Map<String, Object> map = registerIm(username, appUserLogin.getPassword(), nickname);
log.info("注册:到im注册: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (map != null) { if (map != null) {
Integer imUserId = Integer.parseInt(map.get("userId").toString()); Integer imUserId = Integer.parseInt(map.get("userId").toString());
//String access_token=map.get("access_token").toString(); //String access_token=map.get("access_token").toString();
...@@ -345,6 +353,7 @@ public class AppPermissionService { ...@@ -345,6 +353,7 @@ public class AppPermissionService {
//data.put("imToken",access_token); //data.put("imToken",access_token);
data.put("imUserId", imUserId); data.put("imUserId", imUserId);
} }
log.info("注册:处理im账号: " + userid+"---time===="+System.currentTimeMillis()/1000L);
if (data != null) { if (data != null) {
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userid); jsonObject.put("userId", userid);
...@@ -352,6 +361,7 @@ public class AppPermissionService { ...@@ -352,6 +361,7 @@ public class AppPermissionService {
log.info("注册成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString()); log.info("注册成功获取积分:发送消息 exchange = {}, routingKey = {}, json = {}", RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
mqSenderFeign.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString()); mqSenderFeign.sendMessage(RabbitConstant.INTEGRAL_TOPIC, RabbitConstant.INTEGRAL_ROUTING_KEY, jsonObject.toJSONString());
sendQueue(username, password, headimgurl, nickname, mobilecode, openId, unionid, type, code, activityCode, userid,RegisterQueueDTO.SIGN_NEW); sendQueue(username, password, headimgurl, nickname, mobilecode, openId, unionid, type, code, activityCode, userid,RegisterQueueDTO.SIGN_NEW);
log.info("注册:发消息队列: " + userid+"---time===="+System.currentTimeMillis()/1000L);
return JsonResultUtil.createSuccessResultWithObj(data); return JsonResultUtil.createSuccessResultWithObj(data);
} else { } else {
return JsonResultUtil.createDefaultFail(); return JsonResultUtil.createDefaultFail();
...@@ -535,7 +545,7 @@ public class AppPermissionService { ...@@ -535,7 +545,7 @@ public class AppPermissionService {
userDetail.setUpdatetime(now); userDetail.setUpdatetime(now);
userDetail.setIsdel(0); userDetail.setIsdel(0);
userDetail.setCrtHost(getIp()); userDetail.setCrtHost(getIp());
setCreateIPInfo(userDetail); //setCreateIPInfo(userDetail);
appUserDetailBiz.insertSelective(userDetail); appUserDetailBiz.insertSelective(userDetail);
} /*else { } /*else {
...@@ -949,7 +959,7 @@ public class AppPermissionService { ...@@ -949,7 +959,7 @@ public class AppPermissionService {
//设置来源 //设置来源
rsUserDetail.setChannel(UserSourceEnum.APPLET.getCode()); rsUserDetail.setChannel(UserSourceEnum.APPLET.getCode());
rsUserDetail.setCrtHost(getIp()); rsUserDetail.setCrtHost(getIp());
setCreateIPInfo(rsUserDetail); //setCreateIPInfo(rsUserDetail);
rsUserDetail.setState(1); rsUserDetail.setState(1);
appUserDetailBiz.insertSelective(rsUserDetail); appUserDetailBiz.insertSelective(rsUserDetail);
log.error("注册:新增用户详情: " + userid); log.error("注册:新增用户详情: " + userid);
...@@ -1083,7 +1093,7 @@ public class AppPermissionService { ...@@ -1083,7 +1093,7 @@ public class AppPermissionService {
public void setCreateIPInfo(AppUserDetail appUserDetail) { public void setCreateIPInfo(AppUserDetail appUserDetail) {
String crtHost = appUserDetail.getCrtHost(); String crtHost = appUserDetail.getCrtHost();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("解析的地址:【{}】", crtHost); log.debug("解析的地址:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
} }
try { try {
analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL2, crtHost, appUserDetail); analyticalIPByWebSiteAndIPAddress(IPAddress.BASE_IP_PARSING_URL2, crtHost, appUserDetail);
...@@ -1100,10 +1110,12 @@ public class AppPermissionService { ...@@ -1100,10 +1110,12 @@ public class AppPermissionService {
private void analyticalIPByWebSiteAndIPAddress(String url, String crtHost, AppUserDetail appUserDetail) { private void analyticalIPByWebSiteAndIPAddress(String url, String crtHost, AppUserDetail appUserDetail) {
String ipAddress = restTemplate.getForObject(String.format("%s%s", url, crtHost), String.class); String ipAddress = restTemplate.getForObject(String.format("%s%s", url, crtHost), String.class);
log.debug("解析的调用网站后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA); String data = JSONObject.parseObject(ipAddress).getString(IPAddress.BASE_DATA);
JSONObject ipJsonObject = JSONObject.parseObject(data); JSONObject ipJsonObject = JSONObject.parseObject(data);
String cityName = ipJsonObject.getString(IPAddress.CITY_NAME); String cityName = ipJsonObject.getString(IPAddress.CITY_NAME);
RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName); RegionDTO regionDTO = regionFeign.getRegionByCityName(StringUtils.isEmpty(cityName) ? "东莞" : cityName);
log.debug("解析的调用服务后:【{}】", crtHost+"---time==="+System.currentTimeMillis()/1000L);
if (null != regionDTO) { if (null != regionDTO) {
appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId()))); appUserDetail.setProvinceCode(Integer.valueOf(String.valueOf(regionDTO.getParentId())));
appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId()))); appUserDetail.setCityCode(Integer.valueOf(String.valueOf(regionDTO.getId())));
......
package com.xxfc.platform.order.entity.inter; package com.xxfc.platform.order.entity.inter;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum; import com.xxfc.platform.order.contant.enumerate.ItemTypeEnum;
import com.xxfc.platform.order.entity.BaseOrder; import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderItem; import com.xxfc.platform.order.entity.OrderItem;
...@@ -28,4 +29,8 @@ public interface OrderDetail extends OrderItemInter { ...@@ -28,4 +29,8 @@ public interface OrderDetail extends OrderItemInter {
void setTickerNo(List<String> tickerNo); void setTickerNo(List<String> tickerNo);
public AppUserDTO getAppUserDTO();
public void setAppUserDTO(AppUserDTO appUserDTO);
} }
...@@ -7,4 +7,7 @@ import lombok.Data; ...@@ -7,4 +7,7 @@ import lombok.Data;
public class CancelOrderDTO { public class CancelOrderDTO {
@ApiModelProperty(value = "取消原因") @ApiModelProperty(value = "取消原因")
private String cancelReason; private String cancelReason;
@ApiModelProperty(value = "app用户id")
private String appUserId;
} }
\ No newline at end of file
...@@ -19,6 +19,7 @@ import java.util.List; ...@@ -19,6 +19,7 @@ import java.util.List;
public class MemberBO extends OrderMemberDetail implements OrderDetail { public class MemberBO extends OrderMemberDetail implements OrderDetail {
private BaseOrder order; private BaseOrder order;
private BaseUserMemberLevel baseUserMemberLevel; private BaseUserMemberLevel baseUserMemberLevel;
AppUserDTO appUserDTO;
/** /**
* 下单来源,1--app;2--小程序 * 下单来源,1--app;2--小程序
*/ */
......
...@@ -42,4 +42,9 @@ public class RentVehicleBO extends OrderRentVehicleDetail implements OrderDetail ...@@ -42,4 +42,9 @@ public class RentVehicleBO extends OrderRentVehicleDetail implements OrderDetail
@ApiModelProperty(value = "随车物品", hidden = true) @ApiModelProperty(value = "随车物品", hidden = true)
private List<OrderAccompanyDTO> accompanyItems; private List<OrderAccompanyDTO> accompanyItems;
/**
* 创建用户 -1+后台用户id 后台系统
*/
String crtUser;
} }
package com.xxfc.platform.order.pojo; package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@Data @Data
......
package com.xxfc.platform.order.pojo; package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
...@@ -8,7 +8,7 @@ public class AddOrderCommonDTO { ...@@ -8,7 +8,7 @@ public class AddOrderCommonDTO {
/** /**
* *
*/ */
@ApiModelProperty(value = "下单来源,1--app;2--小程序") @ApiModelProperty(value = "下单来源,1--app;2--小程序;3--后台")
private Integer orderOrigin; private Integer orderOrigin;
......
package com.xxfc.platform.order.pojo; package com.xxfc.platform.order.pojo.order.add;
import com.xxfc.platform.activity.entity.ActivityPopularizeItem; import com.xxfc.platform.order.pojo.OrderAccompanyDTO;
import com.xxfc.platform.vehicle.constant.AccompanyingItemType;
import com.xxfc.platform.vehicle.entity.AccompanyingItem;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
......
package com.xxfc.platform.order.pojo; package com.xxfc.platform.order.pojo.order.add;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import lombok.Data; import lombok.Data;
import javax.persistence.Column; import javax.persistence.Column;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@Data @Data
......
package com.xxfc.platform.order.pojo.order.add;
import lombok.Data;
@Data
public class BgAddRentDTO extends AddRentVehicleDTO {
/**
* 用户订单
*/
Integer appUserId;
}
...@@ -632,7 +632,8 @@ public class BaseOrderBiz extends BaseBiz<BaseOrderMapper, BaseOrder> { ...@@ -632,7 +632,8 @@ public class BaseOrderBiz extends BaseBiz<BaseOrderMapper, BaseOrder> {
public Query initQuery(String no) { public Query initQuery(String no) {
QueryOrderDetailDTO qodd = new QueryOrderDetailDTO(); QueryOrderDetailDTO qodd = new QueryOrderDetailDTO();
qodd.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID())); //qodd.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
qodd.setUserId(Integer.valueOf(BaseContextHandler.getUserID()));
qodd.setNo(no); qodd.setNo(no);
qodd.setLimit(1); qodd.setLimit(1);
qodd.setPage(1); qodd.setPage(1);
......
...@@ -443,12 +443,14 @@ public class OrderAccountBiz extends BaseBiz<OrderAccountMapper,OrderAccount> { ...@@ -443,12 +443,14 @@ public class OrderAccountBiz extends BaseBiz<OrderAccountMapper,OrderAccount> {
csv.initParamJson(); csv.initParamJson();
//设置明细 //设置明细
orderRentVehicleBiz.updateSelectiveById(new OrderRentVehicleDetail(){{ orderRentVehicleBiz.updateSelectiveByIdRe(new OrderRentVehicleDetail(){{
setId(orderMQDTO.getDetailId()); setId(orderMQDTO.getDetailId());
handelCostDetailExtend(csv); handelCostDetailExtend(csv);
setBackFreeDays(inProgressVO.getBackFreeDays()); setBackFreeDays(inProgressVO.getBackFreeDays());
}}); }});
orderMQDTO.setOrderRentVehicleDetail(orderRentVehicleBiz.selectById(orderMQDTO.getDetailId()));
//捕捉异常 //捕捉异常
try { try {
orderMsgBiz.handelMsgDeposit(orderMQDTO.getOrderRentVehicleDetail(), orderMQDTO, userFeign.userDetailById(orderMQDTO.getUserId()).getData()); orderMsgBiz.handelMsgDeposit(orderMQDTO.getOrderRentVehicleDetail(), orderMQDTO, userFeign.userDetailById(orderMQDTO.getUserId()).getData());
......
...@@ -37,7 +37,6 @@ import com.xxfc.platform.vehicle.entity.VehicleUserLicense; ...@@ -37,7 +37,6 @@ import com.xxfc.platform.vehicle.entity.VehicleUserLicense;
import com.xxfc.platform.vehicle.feign.VehicleFeign; import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.BookVehicleVO; import com.xxfc.platform.vehicle.pojo.BookVehicleVO;
import com.xxfc.platform.vehicle.pojo.CompanyDetail; import com.xxfc.platform.vehicle.pojo.CompanyDetail;
import com.xxfc.platform.vehicle.pojo.QueryMultiDTO;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import lombok.Data; import lombok.Data;
...@@ -49,14 +48,13 @@ import org.springframework.stereotype.Controller; ...@@ -49,14 +48,13 @@ import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.lang.reflect.Array;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static com.xxfc.platform.order.pojo.AddRentVehicleDTO.DEFAULT_DATE_TIME_FORMATTER; import static com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO.DEFAULT_DATE_TIME_FORMATTER;
@Controller @Controller
@RequestMapping("baseOrder") @RequestMapping("baseOrder")
......
...@@ -149,7 +149,8 @@ public class BaseOrderController extends CommonBaseController implements UserRes ...@@ -149,7 +149,8 @@ public class BaseOrderController extends CommonBaseController implements UserRes
if (StringUtils.isBlank(BaseContextHandler.getUserID())) { if (StringUtils.isBlank(BaseContextHandler.getUserID())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE); throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
} }
dto.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID())); //dto.setCrtUser(Integer.valueOf(BaseContextHandler.getUserID()));
dto.setUserId(Integer.valueOf(BaseContextHandler.getUserID()));
Query query = new Query(dto); Query query = new Query(dto);
PageDataVO<OrderPageVO> pages = PageDataVO.pageInfo(query, () -> baseOrderBiz.pageByParm(query.getSuper())); PageDataVO<OrderPageVO> pages = PageDataVO.pageInfo(query, () -> baseOrderBiz.pageByParm(query.getSuper()));
pages.getData().parallelStream().forEach(data -> data.setQrcodeStr(qrcodePrefix)); pages.getData().parallelStream().forEach(data -> data.setQrcodeStr(qrcodePrefix));
...@@ -248,16 +249,33 @@ public class BaseOrderController extends CommonBaseController implements UserRes ...@@ -248,16 +249,33 @@ public class BaseOrderController extends CommonBaseController implements UserRes
if (StringUtils.isBlank(BaseContextHandler.getUserID())) { if (StringUtils.isBlank(BaseContextHandler.getUserID())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE); throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
} }
cancelCommon(no, cancelOrderDto, BaseContextHandler.getUserID());
return ObjectRestResponse.succ();
}
@RequestMapping(value = "/back-stage/cancel/{no}", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "取消订单")
@IgnoreClientToken
public ObjectRestResponse bgCancel(@PathVariable String no, @RequestBody CancelOrderDTO cancelOrderDto) {
//查询列表数据
if (StringUtils.isBlank(cancelOrderDto.getAppUserId())) {
throw new BaseException(ResultCode.AJAX_WECHAT_NOTEXIST_CODE);
}
cancelCommon(no, cancelOrderDto, cancelOrderDto.getAppUserId());
return ObjectRestResponse.succ();
}
private void cancelCommon(String no, CancelOrderDTO cancelOrderDto, String userId) {
BaseOrder dbBaseOrder = baseOrderBiz.selectOne(new BaseOrder() {{ BaseOrder dbBaseOrder = baseOrderBiz.selectOne(new BaseOrder() {{
setNo(no); setNo(no);
}}); }});
if (null == dbBaseOrder || !BaseContextHandler.getUserID().equals(dbBaseOrder.getUserId().toString())) { if (null == dbBaseOrder || !userId.equals(dbBaseOrder.getUserId().toString())) {
throw new BaseException(ResultCode.NOTEXIST_CODE); throw new BaseException(ResultCode.NOTEXIST_CODE);
} }
dbBaseOrder.setCancelReason(cancelOrderDto.getCancelReason()); dbBaseOrder.setCancelReason(cancelOrderDto.getCancelReason());
orderCancelBiz.cancel(dbBaseOrder); orderCancelBiz.cancel(dbBaseOrder);
return ObjectRestResponse.succ();
} }
@RequestMapping(value = "/app/unauth/notifyUrl", method = RequestMethod.GET) @RequestMapping(value = "/app/unauth/notifyUrl", method = RequestMethod.GET)
......
package com.xxfc.platform.order.rest; package com.xxfc.platform.order.rest;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.entity.BaseUserMemberLevel;
import com.github.wxiaoqi.security.admin.feign.UserFeign; import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken; import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse; import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController; import com.github.wxiaoqi.security.common.rest.BaseController;
import com.xxfc.platform.order.biz.OrderMemberDetailBiz; import com.xxfc.platform.order.biz.OrderMemberDetailBiz;
import com.xxfc.platform.order.entity.BaseOrder; import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderMemberDetail; import com.xxfc.platform.order.entity.OrderMemberDetail;
import com.xxfc.platform.order.pojo.AddMemberDTO; import com.xxfc.platform.order.pojo.order.add.AddMemberDTO;
import com.xxfc.platform.order.pojo.AddTourDTO;
import com.xxfc.platform.order.pojo.order.MemberBO; import com.xxfc.platform.order.pojo.order.MemberBO;
import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.service.OrderMemberService; import com.xxfc.platform.order.service.OrderMemberService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -49,6 +46,7 @@ public class OrderMemberController extends BaseController<OrderMemberDetailBiz,O ...@@ -49,6 +46,7 @@ public class OrderMemberController extends BaseController<OrderMemberDetailBiz,O
// bo.setMemberLevelId(bo.getBaseUserMemberLevel().getId()); // bo.setMemberLevelId(bo.getBaseUserMemberLevel().getId());
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
//查询优惠券 //查询优惠券
orderMemberService.createOrder(bo); orderMemberService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder()); return ObjectRestResponse.succ(bo.getOrder());
......
...@@ -13,8 +13,9 @@ import com.xxfc.platform.order.biz.BaseOrderBiz; ...@@ -13,8 +13,9 @@ import com.xxfc.platform.order.biz.BaseOrderBiz;
import com.xxfc.platform.order.biz.OrderRentVehicleBiz; import com.xxfc.platform.order.biz.OrderRentVehicleBiz;
import com.xxfc.platform.order.entity.BaseOrder; import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail; import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.pojo.AddRentVehicleDTO; import com.xxfc.platform.order.pojo.order.add.AddRentVehicleDTO;
import com.xxfc.platform.order.pojo.order.RentVehicleBO; import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.add.BgAddRentDTO;
import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO; import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO;
import com.xxfc.platform.order.service.OrderRentVehicleService; import com.xxfc.platform.order.service.OrderRentVehicleService;
import com.xxfc.platform.vehicle.entity.BranchCompany; import com.xxfc.platform.vehicle.entity.BranchCompany;
...@@ -59,6 +60,25 @@ public class OrderRentVehicleController extends CommonBaseController { ...@@ -59,6 +60,25 @@ public class OrderRentVehicleController extends CommonBaseController {
@ResponseBody @ResponseBody
@ApiOperation(value = "确认租车订单") @ApiOperation(value = "确认租车订单")
public ObjectRestResponse<BaseOrder> add(@RequestBody AddRentVehicleDTO vo){ public ObjectRestResponse<BaseOrder> add(@RequestBody AddRentVehicleDTO vo){
RentVehicleBO bo = initRentVehicleBO(vo);
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
orderRentVehicleService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
}
@RequestMapping(value = "back-stage/add",method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "后台人员为客户下租车订单")
public ObjectRestResponse<BaseOrder> backStagedd(@RequestBody BgAddRentDTO dto){
RentVehicleBO bo = initRentVehicleBO(dto);
bo.setAppUserDTO(userFeign.userDetailById(dto.getAppUserId()).getData());
bo.setCrtUser("-1"+ BaseContextHandler.getUserID());
orderRentVehicleService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder());
}
private RentVehicleBO initRentVehicleBO(@RequestBody AddRentVehicleDTO vo) {
if(null == vo.getEndCompanyId() || vo.getEndCompanyId().equals(0)) { if(null == vo.getEndCompanyId() || vo.getEndCompanyId().equals(0)) {
if(StrUtil.isBlank(vo.getEndAddr())) { if(StrUtil.isBlank(vo.getEndAddr())) {
throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确")); throw new BaseException(ResultCode.PARAM_ILLEGAL_CODE, Sets.newSet("公司参数不正确"));
...@@ -92,12 +112,10 @@ public class OrderRentVehicleController extends CommonBaseController { ...@@ -92,12 +112,10 @@ public class OrderRentVehicleController extends CommonBaseController {
setBookStartDate(vo.getBookStartDate()); setBookStartDate(vo.getBookStartDate());
setBookEndDate(vo.getBookEndDate()); setBookEndDate(vo.getBookEndDate());
}}); }});
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())? bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())?
StrUtil.splitTrim(vo.getTickerNos(), ","):null); StrUtil.splitTrim(vo.getTickerNos(), ","):null);
bo.setAccompanyItems(vo.getAccompanyItems()); bo.setAccompanyItems(vo.getAccompanyItems());
orderRentVehicleService.createOrder(bo); return bo;
return ObjectRestResponse.succ(bo.getOrder());
} }
@RequestMapping(value = "list-by-order/{orderId}",method = RequestMethod.GET) @RequestMapping(value = "list-by-order/{orderId}",method = RequestMethod.GET)
......
...@@ -7,12 +7,13 @@ import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO; ...@@ -7,12 +7,13 @@ import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken; import com.github.wxiaoqi.security.auth.client.annotation.IgnoreClientToken;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken; import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig; import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.context.BaseContextHandler;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse; import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController; import com.github.wxiaoqi.security.common.rest.BaseController;
import com.xxfc.platform.order.biz.OrderTourDetailBiz; import com.xxfc.platform.order.biz.OrderTourDetailBiz;
import com.xxfc.platform.order.entity.BaseOrder; import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.entity.OrderTourDetail; import com.xxfc.platform.order.entity.OrderTourDetail;
import com.xxfc.platform.order.pojo.AddTourDTO; import com.xxfc.platform.order.pojo.order.add.AddTourDTO;
import com.xxfc.platform.order.pojo.order.TourBO; import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.pojo.price.TourPriceVO; import com.xxfc.platform.order.pojo.price.TourPriceVO;
import com.xxfc.platform.order.service.OrderTourService; import com.xxfc.platform.order.service.OrderTourService;
...@@ -58,6 +59,7 @@ public class OrderTourController extends BaseController<OrderTourDetailBiz,Order ...@@ -58,6 +59,7 @@ public class OrderTourController extends BaseController<OrderTourDetailBiz,Order
@ApiOperation(value = "确认旅游订单") @ApiOperation(value = "确认旅游订单")
public ObjectRestResponse<BaseOrder> add(@RequestBody AddTourDTO vo){ public ObjectRestResponse<BaseOrder> add(@RequestBody AddTourDTO vo){
TourBO bo = BeanUtil.toBean(vo, TourBO.class); TourBO bo = BeanUtil.toBean(vo, TourBO.class);
bo.setAppUserDTO(userFeign.userDetailByToken(BaseContextHandler.getToken()).getData());
bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())? Arrays.asList(vo.getTickerNos().split(",")):null); bo.setTickerNo(StrUtil.isNotBlank(vo.getTickerNos())? Arrays.asList(vo.getTickerNos().split(",")):null);
orderTourService.createOrder(bo); orderTourService.createOrder(bo);
return ObjectRestResponse.succ(bo.getOrder()); return ObjectRestResponse.succ(bo.getOrder());
......
package com.xxfc.platform.order.service; package com.xxfc.platform.order.service;
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign; import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface; import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.common.biz.BaseBiz; import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.context.BaseContextHandler; import com.github.wxiaoqi.security.common.context.BaseContextHandler;
...@@ -64,7 +66,7 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or ...@@ -64,7 +66,7 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
* 创建基础订单 * 创建基础订单
* @return * @return
*/ */
public BaseOrder createBaseOrder(Integer orderOrigin) { public BaseOrder createBaseOrder(Integer orderOrigin, AppUserDTO appUserDTO) {
BaseOrder baseOrder = new BaseOrder(); BaseOrder baseOrder = new BaseOrder();
//设置下单来源 //设置下单来源
...@@ -85,13 +87,14 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or ...@@ -85,13 +87,14 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
baseOrder.setVersion(VERSION_INITIAL); baseOrder.setVersion(VERSION_INITIAL);
//设置用户id //设置用户id
baseOrder.setUserId(Integer.valueOf(BaseContextHandler.getUserID())); baseOrder.setUserId(appUserDTO.getUserid());
baseOrder.setMemberLevel(getAppUser().getMemberLevel()); baseOrder.setMemberLevel(appUserDTO.getMemberLevel());
return baseOrder; return baseOrder;
} }
public void initDetail(Detail detail) { public void initDetail(Detail detail) {
BaseOrder order = createBaseOrder(detail.getOrderOrigin()); // Integer appUserId = (null == detail.getAppUserDTO())? Integer.valueOf(BaseContextHandler.getUserID()): detail.getAppUserDTO().getUserid();
BaseOrder order = createBaseOrder(detail.getOrderOrigin(), detail.getAppUserDTO());
detail.setOrder(order); detail.setOrder(order);
} }
...@@ -118,10 +121,11 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or ...@@ -118,10 +121,11 @@ public abstract class AbstractOrderHandle<Biz extends BaseBiz, Detail extends Or
detail.setOrderId(detail.getOrder().getId()); detail.setOrderId(detail.getOrder().getId());
detailBiz.insertSelective(detail); detailBiz.insertSelective(detail);
detail.getOrder().setDetailId(detail.getId()); detail.getOrder().setDetailId(detail.getId());
int updateResult =baseOrderBiz.updateSelectiveByIdRe(detail.getOrder()); // int updateResult =baseOrderBiz.updateSelectiveByIdRe(detail.getOrder());
if(updateResult > 0) { // if(updateResult > 0) {
detail.getOrder().setVersion(detail.getOrder().getVersion() + 1); // detail.getOrder().setVersion(detail.getOrder().getVersion() + 1);
} // }
detail.setOrder(baseOrderBiz.updateSelectiveByIdReT(detail.getOrder()));
//插入item //插入item
if(null != detail.getItems() && detail.getItems().size() > 0) { if(null != detail.getItems() && detail.getItems().size() > 0) {
......
...@@ -196,6 +196,11 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl ...@@ -196,6 +196,11 @@ public class OrderRentVehicleService extends AbstractOrderHandle<OrderRentVehicl
accompanyItem.setOrderId(bo.getOrder().getId()); accompanyItem.setOrderId(bo.getOrder().getId());
orderItemBiz.insertSelective(accompanyItem); orderItemBiz.insertSelective(accompanyItem);
//设置后台系统创建人
if(StrUtil.isNotBlank(bo.getCrtUser())) {
bo.getOrder().setCrtUser(bo.getCrtUser());
}
super.handleDetail(bo); super.handleDetail(bo);
//发送定时取消订单(数据字典设置--5分钟) //发送定时取消订单(数据字典设置--5分钟)
......
...@@ -75,6 +75,9 @@ ...@@ -75,6 +75,9 @@
<if test="crtUser != null"> <if test="crtUser != null">
and crt_user = #{crtUser} and crt_user = #{crtUser}
</if> </if>
<if test="userId != null">
and user_id = #{userId}
</if>
<if test="crtCompanyId != null"> <if test="crtCompanyId != null">
and crt_company_id = #{crtCompanyId} and crt_company_id = #{crtCompanyId}
</if> </if>
...@@ -205,10 +208,16 @@ ...@@ -205,10 +208,16 @@
and r.end_time between #{startTime} and #{endTime} and r.end_time between #{startTime} and #{endTime}
</if> </if>
<if test="companyIds != null and companyIds.size > 0"> <if test="companyIds != null and companyIds.size > 0">
and r.start_company_id in and (r.start_company_id in
<foreach collection="companyIds" item="id" open="(" separator="," close=")"> <foreach collection="companyIds" item="id" open="(" separator="," close=")">
#{id} #{id}
</foreach> </foreach>
or
r.end_company_id in
<foreach collection="companyIds" item="id" open="(" separator="," close=")">
#{id}
</foreach>
)
</if> </if>
<if test="status == 4"> <if test="status == 4">
order by r.start_time order by r.start_time
......
...@@ -113,6 +113,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -113,6 +113,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
public void publishSummitActivityById(Integer id, Integer state) { public void publishSummitActivityById(Integer id, Integer state) {
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsPublish(state); summitActivity.setIsPublish(state);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
summitActivity.setId(id); summitActivity.setId(id);
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
...@@ -121,6 +122,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -121,6 +122,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsShow(state); summitActivity.setIsShow(state);
summitActivity.setId(id); summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
...@@ -128,6 +130,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -128,6 +130,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsHomePage(state); summitActivity.setIsHomePage(state);
summitActivity.setId(id); summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
...@@ -135,6 +138,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -135,6 +138,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsOpenReg(state); summitActivity.setIsOpenReg(state);
summitActivity.setId(id); summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
...@@ -142,6 +146,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -142,6 +146,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setIsDel(1); summitActivity.setIsDel(1);
summitActivity.setId(id); summitActivity.setId(id);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
...@@ -162,6 +167,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv ...@@ -162,6 +167,7 @@ public class SummitActivityBiz extends BaseBiz<SummitActivityMapper, SummitActiv
SummitActivity summitActivity = new SummitActivity(); SummitActivity summitActivity = new SummitActivity();
summitActivity.setId(id); summitActivity.setId(id);
summitActivity.setRank(rank); summitActivity.setRank(rank);
summitActivity.setUpdTime(Instant.now().toEpochMilli());
mapper.updateByPrimaryKeySelective(summitActivity); mapper.updateByPrimaryKeySelective(summitActivity);
} }
......
...@@ -83,6 +83,12 @@ ...@@ -83,6 +83,12 @@
<artifactId>jiguang-common</artifactId> <artifactId>jiguang-common</artifactId>
<version>1.1.1</version> <version>1.1.1</version>
</dependency> </dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>compile</scope>
</dependency>
</dependencies> </dependencies>
......
package com.xxfc.platform.universal.api;
import com.xxfc.platform.universal.api.pojo.Authentication;
import com.xxfc.platform.universal.entity.IdInformation;
/**
* 调用外部接口实现类。调用不同的外部接口,需要编写不同了类实现该类
*/
public interface BaseAuthentication {
Authentication getAuthentication(IdInformation idInformation);
}
package com.xxfc.platform.universal.api.impl;
import com.xxfc.platform.universal.api.BaseAuthentication;
import com.xxfc.platform.universal.api.pojo.Authentication;
import com.xxfc.platform.universal.entity.IdInformation;
public class FQAuthentication implements BaseAuthentication {
@Override
public Authentication getAuthentication(IdInformation idInformation) {
return null;
}
}
package com.xxfc.platform.universal.api.pojo;
public class Authentication {
}
...@@ -7,7 +7,7 @@ public class RedisKey { ...@@ -7,7 +7,7 @@ public class RedisKey {
/** /**
* 常量缓存key前缀 * 常量缓存key前缀
*/ */
public static final String CONSTANT_CACHE_PREFIX ="cache:constant:"; public static final String TOKEN_CACHE_PREFIX ="cache:token:";
/** /**
* 地区常量缓存key前缀(子读取列表) * 地区常量缓存key前缀(子读取列表)
......
package com.xxfc.platform.universal.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.KeyStore;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.github.wxiaoqi.security.common.util.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
/**
* @Author vitoHuang
* @Time 2015年8月14日
* @Mark HTTPS请求工具
*/
@Slf4j
public class HTTPSUtils{
/**
* HTTPS json 请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式 POST/GET
* @param msg json方式的请求参数
* @return 返回相应的字符串 异常会输出null
*/
public static String httpRequest(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequest()httpRequest="+requestUrl);
OutputStream outputStream = null;
InputStream inputStream = null;
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
log.error("httpUrlConn="+httpUrlConn);
if (null != msg) {
outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(msg.getBytes("UTF-8"));
}
// 将返回的输入流转换成字符串
inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
log.error("inputStreamReader="+inputStreamReader);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
httpUrlConn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:"+e.getMessage());
}finally{
if(outputStream != null)try{outputStream.close();}catch (Exception e) {}
if(inputStream != null)try{inputStream.close();;}catch (Exception e) {}
}
return null;
}
/**
* HTTPS json 请求
* @param requestUrl
* @param requestMethod
* @param msg
* @return 对字符串进行封装成JSON
*/
public static JSONObject httpRequestToJSON(String requestUrl, String requestMethod, String msg){
log.error("进入方法httpRequestToJSON-----");
String json = httpRequest(requestUrl, requestMethod, msg);
log.error("json-----"+json);
JSONObject jsonObject = null;
if(StringUtils.isNotBlank(json)) jsonObject = JSON.parseObject(json);
return jsonObject;
}
}
package com.xxfc.platform.universal.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
@Slf4j
public class HttpRequestUtil {
/**
* post请求
* @param url url地址
* @return
*/
public static String httpPost(String url){
//post请求返回结果
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
String str = "";
try {
HttpResponse result = httpClient.execute(method);
url = URLDecoder.decode(url, "UTF-8");
/**请求发送成功,并得到响应**/
if (result.getStatusLine().getStatusCode() == 200) {
try {
/**读取服务器返回过来的json字符串数据**/
str = EntityUtils.toString(result.getEntity(),"UTF-8");
} catch (Exception e) {
log.error("post请求提交失败:" + url, e);
}
}
} catch (IOException e) {
log.error("post请求提交失败:" + url, e);
}
return str;
}
/**
* 发送get请求
* @param url 路径
* @return
*/
public static String httpGet(String url){
//get请求返回结果
String strResult = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
//发送get请求
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
/**请求发送成功,并得到响应**/
if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
/**读取服务器返回过来的json字符串数据**/
strResult = EntityUtils.toString(response.getEntity(),"UTF-8");
} else {
log.error("get请求提交失败:" + url);
}
} catch (IOException e) {
log.error("get请求提交失败:" + url, e);
}
return strResult;
}
}
package com.xxfc.platform.universal.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
request.setEntity(new StringEntity(body, "utf-8"));
}
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
if (!StringUtils.isBlank(path)) {
sbUrl.append(path);
}
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
sbQuery.append(query.getValue());
}
if (!StringUtils.isBlank(query.getKey())) {
sbQuery.append(query.getKey());
if (!StringUtils.isBlank(query.getValue())) {
sbQuery.append("=");
sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
}
}
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
throw new RuntimeException(ex);
} catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex);
}
}
}
\ No newline at end of file
package com.xxfc.platform.universal.utils;
import com.github.wxiaoqi.security.common.util.MD5Util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/*
'微信支付服务器签名支付请求请求类
'============================================================================
'api说明:
'init(app_id, app_secret, partner_key, app_key);
'初始化函数,默认给一些参数赋值,如cmdno,date等。
'setKey(key_)'设置商户密钥
'getLasterrCode(),获取最后错误号
'GetToken();获取Token
'getTokenReal();Token过期后实时获取Token
'createMd5Sign(signParams);生成Md5签名
'genPackage(packageParams);获取package包
'createSHA1Sign(signParams);创建签名SHA1
'sendPrepay(packageParams);提交预支付
'getDebugInfo(),获取debug信息
'============================================================================
'*/
public class RequestHandler {
/** Token获取网关地址地址 */
private String tokenUrl;
/** 预支付网关url地址 */
private String gateUrl;
/** 查询支付通知网关URL */
private String notifyUrl;
/** 商户参数 */
private String appid;
private String appkey;
private String partnerkey;
private String appsecret;
private String key;
/** 请求的参数 */
private SortedMap parameters;
/** Token */
private String Token;
private String charset;
/** debug信息 */
private String debugInfo;
private String last_errcode;
private HttpServletRequest request;
private HttpServletResponse response;
/**
* 初始构造函数。
*
* @return
*/
public RequestHandler(HttpServletRequest request,
HttpServletResponse response) {
this.last_errcode = "0";
this.request = request;
this.response = response;
//this.charset = "GBK";
this.charset = "UTF-8";
this.parameters = new TreeMap();
// 验证notify支付订单网关
notifyUrl = "https://gw.tenpay.com/gateway/simpleverifynotifyid.xml";
}
/**
* 初始化函数。
*/
public void init(String app_id, String app_secret, String partner_key) {
this.last_errcode = "0";
this.Token = "token_";
this.debugInfo = "";
this.appid = app_id;
this.partnerkey = partner_key;
this.appsecret = app_secret;
this.key = partner_key;
}
public void init() {
}
/**
* 获取最后错误号
*/
public String getLasterrCode() {
return last_errcode;
}
/**
*获取入口地址,不包含参数值
*/
public String getGateUrl() {
return gateUrl;
}
/**
* 获取参数值
*
* @param parameter
* 参数名称
* @return String
*/
public String getParameter(String parameter) {
String s = (String) this.parameters.get(parameter);
return (null == s) ? "" : s;
}
//设置密钥
public void setKey(String key) {
this.partnerkey = key;
}
//设置微信密钥
public void setAppKey(String key){
this.appkey = key;
}
// 特殊字符处理
public String UrlEncode(String src) throws UnsupportedEncodingException {
return URLEncoder.encode(src, this.charset).replace("+", "%20");
}
// 获取package的签名包
public String genPackage(SortedMap<String, String> packageParams)
throws UnsupportedEncodingException {
String sign = createSign(packageParams);
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
sb.append(k + "=" + UrlEncode(v) + "&");
}
// 去掉最后一个&
String packageValue = sb.append("sign=" + sign).toString();
// System.out.println("UrlEncode后 packageValue=" + packageValue);
return packageValue;
}
/**
* 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
*/
public String createSign(SortedMap<String, String> packageParams) {
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (null != v && !"".equals(v) && !"sign".equals(k)
&& !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + this.getKey());
System.out.println("md5 sb:" + sb);
String sign = MD5Util.MD5Encode(sb.toString(), this.charset).toUpperCase();
System.out.println("packge签名:" + sign);
return sign;
}
//输出XML
public String parseXML() {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = this.parameters.entrySet();
Iterator it = es.iterator();
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
String k = (String)entry.getKey();
String v = (String)entry.getValue();
if(null != v && !"".equals(v) && !"appkey".equals(k)) {
sb.append("<" + k +">" + getParameter(k) + "</" + k + ">\n");
}
}
sb.append("</xml>");
return sb.toString();
}
/**
* 设置debug信息
*/
protected void setDebugInfo(String debugInfo) {
this.debugInfo = debugInfo;
}
public void setPartnerkey(String partnerkey) {
this.partnerkey = partnerkey;
}
public String getDebugInfo() {
return debugInfo;
}
public String getKey() {
return key;
}
}
package com.xxfc.platform.universal.utils;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XmlFriendlyReplacer;
import com.thoughtworks.xstream.io.xml.XppDriver;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class WeiXinPayUtil{
private final static String WeXinPay_URL ="https://api.mch.weixin.qq.com/pay/unifiedorder";
private final static String WeXinRefund_URL ="https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String getPrepayId(String xml,String method){
return HTTPSUtils.httpRequest(WeXinPay_URL, method, xml);
}
@SuppressWarnings("deprecation")
private static XStream xstream = new XStream(/*new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
}*/
new XppDriver(new
XmlFriendlyReplacer("_-", "_"){
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
// 对所有xml节点的转换都增加CDATA标记
boolean cdata = true;
@SuppressWarnings({ "rawtypes" })
public void startNode(String name, Class clazz) {
super.startNode(name, clazz);
}
protected void writeText(QuickWriter writer, String text) {
if (cdata) {
writer.write("<![CDATA[");
writer.write(text);
writer.write("]]>");
} else {
writer.write(text);
}
}
};
}
})
);
public static String toXml(WxPrepay wxPrepay){
xstream.alias("xml", wxPrepay.getClass());
return xstream.toXML(wxPrepay);
}
/**
* 获取随机字符串
* @return
*/
public static String getNonceStr() {
// 随机数
String currTime = getCurrTime();
// 8位日期
String strTime = currTime.substring(8, currTime.length());
// 四位随机数
String strRandom = buildRandom(4) + "";
// 10位序列号,可以自行调整。
return strTime + strRandom;
}
/**
* 获取当前时间 yyyyMMddHHmmss
* @return String
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
* 取出一个指定长度大小的随机正整数.
*
* @param length
* int 设定所取出随机数的长度。length小于11
* @return int 返回生成的随机数。
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
* 元转换成分
* @param
* @return
*/
public static String getMoney(String amount) {
if(amount==null){
return "";
}
// 金额转化为分为单位
String currency = amount.replaceAll("\\$|\\¥|\\,", ""); //处理包含, ¥ 或者$的金额
int index = currency.indexOf(".");
int length = currency.length();
Long amLong = 0l;
if(index == -1){
amLong = Long.valueOf(currency+"00");
}else if(length - index >= 3){
amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));
}else if(length - index == 2){
amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
}else{
amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
}
return amLong.toString();
}
/**
* ArrayToXml
* @param arr
* @return
*/
public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}
public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}
}
package com.xxfc.platform.universal.utils;
public class WxPrepay {
private String appid;
private String mch_id;
private String nonce_str;
private String sign;
private String body;
private String out_trade_no;
private String attach;
private String total_fee;
private String spbill_create_ip;
private String notify_url;
private String trade_type;
private String openid;
private String out_refund_no;
private String refund_fee;
private String op_user_id;
public WxPrepay(){};
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getAttach() {
return attach;
}
public void setAttach(String attach) {
this.attach = attach;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getSpbill_create_ip() {
return spbill_create_ip;
}
public void setSpbill_create_ip(String spbill_create_ip) {
this.spbill_create_ip = spbill_create_ip;
}
public String getNotify_url() {
return notify_url;
}
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getOut_refund_no() {
return out_refund_no;
}
public void setOut_refund_no(String out_refund_no) {
this.out_refund_no = out_refund_no;
}
public String getRefund_fee() {
return refund_fee;
}
public void setRefund_fee(String refund_fee) {
this.refund_fee = refund_fee;
}
public String getOp_user_id() {
return op_user_id;
}
public void setOp_user_id(String op_user_id) {
this.op_user_id = op_user_id;
}
}
package com.xxfc.platform.universal.weixin.api; package com.xxfc.platform.universal.weixin.api;
import java.util.Map.Entry;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.Iterator; import java.util.*;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import com.github.wxiaoqi.security.common.util.MD5; import com.github.wxiaoqi.security.common.util.MD5;
import com.github.wxiaoqi.security.common.util.MD5Util; import com.github.wxiaoqi.security.common.util.MD5Util;
import com.github.wxiaoqi.security.common.util.OrderUtil; import com.github.wxiaoqi.security.common.util.OrderUtil;
import com.github.wxiaoqi.security.common.util.process.SystemConfig; import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.xxfc.platform.universal.utils.RequestHandler;
import com.xxfc.platform.universal.utils.WeiXinPayUtil;
import com.xxfc.platform.universal.utils.WxPrepay;
import com.xxfc.platform.universal.weixin.util.HTTPUtils; import com.xxfc.platform.universal.weixin.util.HTTPUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document; import org.dom4j.Document;
import org.dom4j.DocumentException; import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper; import org.dom4j.DocumentHelper;
import org.dom4j.Element; import org.dom4j.Element;
import org.dom4j.Node; import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
/** /**
...@@ -44,9 +41,12 @@ public class WXPay { ...@@ -44,9 +41,12 @@ public class WXPay {
* @return * @return
*/ */
public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid){ public static String webPay(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String wyAppid){
WXPrepay prePay = new WXPrepay(); WXPrepay prePay = new WXPrepay();
prePay.setAppid(SystemConfig.WINXIN_AppID);//pay.getAppId() if (StringUtils.isBlank(wyAppid)){
wyAppid=SystemConfig.WINXIN_AppID;
}
prePay.setAppid(wyAppid);//pay.getAppId()
prePay.setBody(body); prePay.setBody(body);
prePay.setPartnerKey(SystemConfig.WINXIN_PARTNER_KEY);//pay.getPartnerKey() prePay.setPartnerKey(SystemConfig.WINXIN_PARTNER_KEY);//pay.getPartnerKey()
prePay.setMch_id(SystemConfig.WINXIN_PARTNER);//pay.getPartnerId() prePay.setMch_id(SystemConfig.WINXIN_PARTNER);//pay.getPartnerId()
...@@ -65,7 +65,7 @@ public class WXPay { ...@@ -65,7 +65,7 @@ public class WXPay {
String jsParam = ""; String jsParam = "";
if (prepayid != null && prepayid.length() > 10) { if (prepayid != null && prepayid.length() > 10) {
// 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式 // 生成微信支付参数,此处拼接为完整的JSON格式,符合支付调起传入格式
jsParam = WXPay.createPackageValueWeb(SystemConfig.WINXIN_AppID, SystemConfig.WINXIN_PARTNER_KEY, prepayid); jsParam = WXPay.createPackageValueWeb(wyAppid, SystemConfig.WINXIN_PARTNER_KEY, prepayid);
} }
return jsParam; return jsParam;
...@@ -115,6 +115,7 @@ public class WXPay { ...@@ -115,6 +115,7 @@ public class WXPay {
} }
} }
sb.append("key=" + AppKey); sb.append("key=" + AppKey);
log.info("-----签名sign==="+sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase(); String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();
return sign; return sign;
} }
...@@ -374,6 +375,92 @@ public class WXPay { ...@@ -374,6 +375,92 @@ public class WXPay {
System.out.println(response_body); System.out.println(response_body);
} }
public static String getPackage(String total_fee,String body,String notify_url,String orderNo,String spbill_create_ip,String openid,String appid,String appsecret){
Map<String,String> map = new LinkedHashMap<String,String>();
Random random = new Random();
String randomStr = MD5.GetMD5String(String.valueOf(random.nextInt(10000)));
String noceStr = MD5Util.MD5Encode(randomStr, "utf-8").toLowerCase();
SortedMap<String, String> packageParams = new TreeMap<String, String>();
packageParams.put("appid",appid);
packageParams.put("mch_id", SystemConfig.WINXIN_PARTNER);
packageParams.put("nonce_str", noceStr);
packageParams.put("body", body);
packageParams.put("attach", "");
packageParams.put("out_trade_no", orderNo);
// 这里写的金额为1 分到时修改
packageParams.put("total_fee",total_fee);
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
String trade_type = "JSAPI";
packageParams.put("trade_type", trade_type);
packageParams.put("openid", openid);
RequestHandler reqHandler = new RequestHandler(null, null);
reqHandler.init(appid, appsecret, SystemConfig.WINXIN_PARTNER_KEY);
String sign = reqHandler.createSign(packageParams);
WxPrepay wxPrepay = new WxPrepay();
wxPrepay.setAppid(appid);
wxPrepay.setMch_id(SystemConfig.WINXIN_PARTNER);
wxPrepay.setNonce_str(noceStr);
wxPrepay.setSign(sign);
wxPrepay.setBody(body);
wxPrepay.setOut_trade_no(orderNo);
wxPrepay.setTotal_fee(total_fee);
wxPrepay.setSpbill_create_ip(spbill_create_ip);
wxPrepay.setNotify_url(notify_url);
wxPrepay.setTrade_type(trade_type);
wxPrepay.setOpenid(openid);
wxPrepay.setAttach("");
String xml = WeiXinPayUtil.toXml(wxPrepay);
log.error("post_prepay_xml: " + xml);
//获取prepay_id
map = StringtoMap(WeiXinPayUtil.getPrepayId(xml,"POST"));
//获取prepay_id后,拼接最后请求支付所需要的package
SortedMap<String, String> finalpackage = new TreeMap<String, String>();
String timestamp = OrderUtil.GetTimestamp();
String packages = "prepay_id="+map.get("prepay_id");
finalpackage.put("appId", appid);
finalpackage.put("timeStamp", timestamp);
finalpackage.put("nonceStr", noceStr);
finalpackage.put("package", packages);
finalpackage.put("signType", "MD5");
//要签名
String finalsign = reqHandler.createSign(finalpackage);
String finaPackage = "\"appId\":\"" + appid + "\",\"timeStamp\":\"" + timestamp
+ "\",\"nonceStr\":\"" + noceStr + "\",\"package\":\""
+ packages + "\",\"signType\" : \"MD5" + "\",\"paySign\":\""
+ finalsign + "\"";
return finaPackage;
}
public static Map<String,String> StringtoMap(String str){
log.error("respon_prepay_xml: " + str);
Map<String,String> map = new LinkedHashMap<String,String>();
try {
Document document = DocumentHelper.parseText(str);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for(Element e : elementList){
map.put(e.getName(), e.getText());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}
......
...@@ -63,6 +63,11 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> { ...@@ -63,6 +63,11 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
MQServiceBiZ mqServiceBiZ; MQServiceBiZ mqServiceBiZ;
@Value("${universal.url}") @Value("${universal.url}")
String weixinHost; String weixinHost;
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public JSONObject preparepay(OrderPayVo orderPayVo) { public JSONObject preparepay(OrderPayVo orderPayVo) {
...@@ -102,13 +107,16 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> { ...@@ -102,13 +107,16 @@ public class OrderPayBiz extends BaseBiz<OrderPayMapper, OrderPay> {
String sellerAccount = null; String sellerAccount = null;
if (type == 2 && payWay == 1) { if (type == 2 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER; sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount()); jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),null);
} else if (type == 1 && payWay == 1) { } else if (type == 1 && payWay == 1) {
sellerAccount = SystemConfig.APP_PARTNER; sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0); jsParam = WXPay.apppay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), 0);
} else if (type == 1 && payWay == 2) { } else if (type == 1 && payWay == 2) {
sellerAccount = SystemConfig.ALIPAY_PID; sellerAccount = SystemConfig.ALIPAY_PID;
jsParam = generateAliPayment(orderPayVo, notifyUrl); jsParam = generateAliPayment(orderPayVo, notifyUrl);
}else if (type == 3 && payWay == 1){
sellerAccount = SystemConfig.APP_PARTNER;
jsParam = WXPay.webPay(amount + "", orderPayVo.getBody(), notify_url, trade_no, orderPayVo.getBuyerIp(), orderPayVo.getBuyerAccount(),wy_appid);
} }
log.info("报名费回调路径jsParam:" + jsParam); log.info("报名费回调路径jsParam:" + jsParam);
if (!StringUtils.isBlank(jsParam)) { if (!StringUtils.isBlank(jsParam)) {
......
package com.xxfc.platform.universal.biz;
import lombok.Data;
/**
* 用户信息类
* @author Administrator
*/
@Data
public class UserMessage {
private String name;
private String idNumber;
}
package com.xxfc.platform.universal.biz;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.universal.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Service
@Slf4j
public class WeixinService {
/**
* 网页
*/
@Value("${wx.appid}")
private String wy_appid;
@Value("${wx.appSercet}")
private String wy_secret;
public static final String frontSessionKey = "frontWeixKey";
public JSONObject getAccessToken(String code){
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?";
String params = "appid="+wy_appid+"&secret="+wy_secret+"&code="+code+"&grant_type=authorization_code";
String result = HttpRequestUtil.httpGet(url + params);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getValidateData(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/auth?access_token=" + access_token + "&openid=" + openid;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getRefreshToken(String refresh_token){
String url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + wy_appid + "&grant_type=refresh_token&refresh_token=" + refresh_token;
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public JSONObject getUserInfo(String access_token,String openid){
String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
String result = HttpRequestUtil.httpGet(url);
JSONObject data = JSON.parseObject(result);
return data;
}
public String getAuthorize(String redirec_url){
String oauth_api = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={APPID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}&state={STATE}#wechat_redirect";
oauth_api = oauth_api.replace("{APPID}", wy_appid)
.replace("{REDIRECT_URI}", redirec_url)
.replace("{SCOPE}", "snsapi_base").replace("{STATE}", "state");
log.info("---oauth_api===="+oauth_api);
return oauth_api;
}
//获取缓存
public String getSession(HttpServletRequest request){
try {
HttpSession session = request.getSession();
String frontSessionValue1 = (String) session.getAttribute(frontSessionKey);
log.info("---session获取===="+frontSessionValue1+"---sessionId==="+session.getId());
if (StringUtils.isBlank(frontSessionValue1)) {
return null;
}
String openId = Base64.decodeStr(frontSessionValue1);
return openId;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
...@@ -3,6 +3,7 @@ package com.xxfc.platform.universal.config; ...@@ -3,6 +3,7 @@ package com.xxfc.platform.universal.config;
import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor; import com.github.wxiaoqi.security.auth.client.interceptor.ServiceAuthRestInterceptor;
import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor; import com.github.wxiaoqi.security.auth.client.interceptor.UserAuthRestInterceptor;
import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler; import com.github.wxiaoqi.security.common.handler.GlobalExceptionHandler;
import com.xxfc.platform.universal.interceptor.WeChatH5LoginInterceptor;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.Primary;
...@@ -29,6 +30,10 @@ public class WebConfiguration implements WebMvcConfigurer { ...@@ -29,6 +30,10 @@ public class WebConfiguration implements WebMvcConfigurer {
addPathPatterns(getIncludePathPatterns()).addPathPatterns("/3p/**"); addPathPatterns(getIncludePathPatterns()).addPathPatterns("/3p/**");
registry.addInterceptor(getUserAuthRestInterceptor()). registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns()); addPathPatterns(getIncludePathPatterns());
registry.addInterceptor(getUserAuthRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
/* registry.addInterceptor(getWeChatH5LoginInterceptor()
).addPathPatterns(getWxIncludePathPatterns());*/
} }
@Bean @Bean
...@@ -41,6 +46,10 @@ public class WebConfiguration implements WebMvcConfigurer { ...@@ -41,6 +46,10 @@ public class WebConfiguration implements WebMvcConfigurer {
return new UserAuthRestInterceptor(); return new UserAuthRestInterceptor();
} }
@Bean
WeChatH5LoginInterceptor getWeChatH5LoginInterceptor() { return new WeChatH5LoginInterceptor();
}
/** /**
* 需要用户和服务认证判断的路径 * 需要用户和服务认证判断的路径
* @return * @return
...@@ -53,6 +62,14 @@ public class WebConfiguration implements WebMvcConfigurer { ...@@ -53,6 +62,14 @@ public class WebConfiguration implements WebMvcConfigurer {
Collections.addAll(list, urls); Collections.addAll(list, urls);
return list; return list;
} }
private ArrayList<String> getWxIncludePathPatterns() {
ArrayList<String> list = new ArrayList<>();
String[] urls = {
"/info/**"
};
Collections.addAll(list, urls);
return list;
}
/* @Bean(name = "customTaskExecutor") /* @Bean(name = "customTaskExecutor")
TaskExecutor getTaskExecutor(){ TaskExecutor getTaskExecutor(){
......
package com.xxfc.platform.universal.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 用户
*/
@RestController
@RequestMapping("info")
@IgnoreUserToken
@Slf4j
public class UserInfoController {
@Autowired
WeixinService weixinService;
@Value("${wx.sendUrl}")
private String sendUrl;
@RequestMapping(value = "getOpenId", method = RequestMethod.GET) //匹配的是href中的download请求
public ObjectRestResponse getOpenId(HttpServletRequest request) throws Exception {
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
log.info("---进入方法getOpenId----openId===="+openId);
if (StringUtils.isBlank(openId)){
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
return ObjectRestResponse.createFailedResultWithObj(1001,"",json);
}
return ObjectRestResponse.succ(openId);
}
return ObjectRestResponse.succ();
}
}
package com.xxfc.platform.universal.controller;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @author Administrator
*/
@Controller
@RequestMapping("/auth")
@Slf4j
public class WeixinController {
public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "callback";
public static final String frontSessionKey = "frontWeixKey";
@Autowired
WeixinService weixinService;
@Value("${wx.url}")
private String url;
@RequestMapping(value ="/app/unauth/wxLogin",method = RequestMethod.GET)
@IgnoreUserToken
public String wxLogin(@RequestParam(value = "redirec_url")String redirec_url){
log.info("-----微信wxLogin---redirec_url=="+redirec_url);
if (StringUtils.isBlank(redirec_url)){
redirec_url="";
}
try {
String encrypt_curr_url = Base64.encode(redirec_url.getBytes("utf-8"));
redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url;
String oauth_api=weixinService.getAuthorize(redirec_url);
return String.format("redirect:"+oauth_api);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
return String.format("网络异常");
}
}
/**
* 微信浏览器获取用户信息
* @param code
* @param callback
* @return
*/
@GetMapping(value = "/app/unauth/userInfo")
public String getUserInformation(String code, String callback, HttpServletRequest request) {
log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback);
try {
authUser(code,request);
callback =new String(Base64.decode(callback), "utf-8");
log.info("callback===" + callback);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
}
return String.format("redirect:"+callback);
}
public void authUser(String code,HttpServletRequest request){
if (StringUtils.isBlank(code)){
log.info("----code为空---");
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
}
String openid = null;
String access_token = null;
try {
JSONObject jsonData = weixinService.getAccessToken(code);
openid = jsonData.getString("openid");
access_token = jsonData.getString("access_token");
String refresh_token = jsonData.getString("refresh_token");
log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
//验证access_token是否失效
JSONObject validateData = weixinService.getValidateData(access_token, openid);
if (!"0".equals(validateData.getString("errcode"))){
//刷新access_token
JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
access_token = refreshData.getString("access_token");
}
String encode = Base64.encode(openid);
HttpSession session = request.getSession();
session.removeAttribute(frontSessionKey);
session.setAttribute(frontSessionKey, encode);
}catch (Exception e){
e.printStackTrace();
log.info("网络异常===" + e.getMessage());
throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
}
}
}
package com.xxfc.platform.universal.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.common.util.UserAgentUtil;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
* 微信登陆拦截器
*
* @author
*
*/
@Slf4j
public class WeChatH5LoginInterceptor extends HandlerInterceptorAdapter {
@Value("${wx.sendUrl}")
private String sendUrl;
@Autowired
WeixinService weixinService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String curr_domain = request.getServerName();
log.info("curr_domain:" + curr_domain);
log.info("address:" + request.getRequestURL().toString());
log.info("params:" + request.getQueryString());
boolean isWx = UserAgentUtil.isWexinBrowser(request);
if (isWx) {
//session里面获取用户信息
String openId=weixinService.getSession(request);
if (StringUtils.isNotBlank(openId)){
return true;
}
Map<String,Object> result=new HashMap<>();
result.put("status",1001);
JSONObject json = new JSONObject();
json.put("sendUrl",sendUrl);
result.put("data",json);
response.getWriter().write(result.toString());
return false;
}
return true;
}
}
...@@ -7,8 +7,10 @@ import com.github.wxiaoqi.security.admin.feign.UserFeign; ...@@ -7,8 +7,10 @@ import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.common.exception.BaseException; import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse; import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode; import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.entity.IdInformation; import com.xxfc.platform.universal.entity.IdInformation;
import com.xxfc.platform.universal.mapper.IdInformationMapper; import com.xxfc.platform.universal.mapper.IdInformationMapper;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils; import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.Validation; import com.xxfc.platform.universal.utils.Validation;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
...@@ -21,6 +23,7 @@ import org.apache.http.util.EntityUtils; ...@@ -21,6 +23,7 @@ import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport; import org.springframework.transaction.interceptor.TransactionAspectSupport;
...@@ -31,9 +34,16 @@ import java.text.SimpleDateFormat; ...@@ -31,9 +34,16 @@ import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
/**
* 认证业务
* @author Administrator
*/
@Service @Service
@Slf4j @Slf4j
public class CertificationService { public class CertificationService {
@Autowired
private UserAuthentication authentication;
/** /**
* 认证相关的数据 * 认证相关的数据
*/ */
...@@ -209,17 +219,20 @@ public class CertificationService { ...@@ -209,17 +219,20 @@ public class CertificationService {
} }
//map携带身份证和姓名进行认证 //map携带身份证和姓名进行认证
Map<String, String> authMap = new HashMap<>(); // Map<String, String> authMap = new HashMap<>();
authMap.put(idCardName, (String) frontData.get(numberName)); // authMap.put(idCardName, (String) frontData.get(numberName));
authMap.put(cName, (String) frontData.get(cName)); // authMap.put(cName, (String) frontData.get(cName));
//3.调用接口进行认证 // //3.调用接口进行认证
String result = certificate(authMap); //
// boolean result = certificate(authMap);
boolean result = authentication.certificate(new UserMessage(){{
setIdNumber(number);
setName(name);
}} );
log.info("----认证结果result=========" + result); log.info("----认证结果result=========" + result);
//认证返回的参数是否为空 //认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result); if (result) {
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
//认证成功后存入保存到数据库 //认证成功后存入保存到数据库
//获得身份证正面记录的身份证号和真实姓名 //获得身份证正面记录的身份证号和真实姓名
//设置姓名 //设置姓名
...@@ -257,9 +270,6 @@ public class CertificationService { ...@@ -257,9 +270,6 @@ public class CertificationService {
// return ObjectRestResponse.succ(objRR.getData()); // return ObjectRestResponse.succ(objRR.getData());
// } // }
} }
}
return ObjectRestResponse.createFailedResult(ResultCode.INCOMPLETE_DATA,"网络异常,请稍后再试"); return ObjectRestResponse.createFailedResult(ResultCode.INCOMPLETE_DATA,"网络异常,请稍后再试");
...@@ -267,7 +277,8 @@ public class CertificationService { ...@@ -267,7 +277,8 @@ public class CertificationService {
//认证 //认证
public String certificate(Map<String, String> querys) { //认证
public boolean certificate(Map<String, String> querys) {
Map<String, String> headers = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + cAppcode); headers.put("Authorization", "APPCODE " + cAppcode);
try { try {
...@@ -280,15 +291,27 @@ public class CertificationService { ...@@ -280,15 +291,27 @@ public class CertificationService {
*/ */
//获取response的body //获取response的body
if (statusCode == 200) { if (statusCode == 200) {
return EntityUtils.toString(response.getEntity()); String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
return true;
}
}
} }
return false;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
return false;
} }
return null;
} }
//身份证照片解析 //身份证照片解析
public String imageParse(String imageUrl, String type) { public String imageParse(String imageUrl, String type) {
Map<String, String> headers = new HashMap<String, String>(); Map<String, String> headers = new HashMap<String, String>();
...@@ -317,10 +340,7 @@ public class CertificationService { ...@@ -317,10 +340,7 @@ public class CertificationService {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
return null; return null;
} }
......
package com.xxfc.platform.universal.service.authenticationInterface;
import com.xxfc.platform.universal.biz.UserMessage;
import java.util.Map;
/**
* 用户认证类
* @author Administrator
*/
public interface UserAuthentication {
/**
* 用户认证方法
* @param message
* @return
*/
boolean certificate(UserMessage message) ;
}
package com.xxfc.platform.universal.service.authenticationInterface.impl;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 调用北京畅游互联科技有限公司接口
*
* @author Administrator
*/
@Service
@Slf4j
@Primary
public class BJCYAuthentication implements UserAuthentication {
private final String host = "http://aliyunverifyidcard.haoservice.com";
private final String path = "/idcard/VerifyIdcardv2";
private final String method = "GET";
private final String appcode = "ee7710ce92054cae9f6c040f6864e6a7";
private final String tokenHead = "Authorization";
private final String token="APPCODE " + appcode;
private final String cardNo ="cardNo";
private final String realName ="realName";
private final Integer resultCode=0;
private final String ret="error_code";
@Override
public boolean certificate(UserMessage message) {
Map<String, String> headers = new HashMap<String, String>();
headers.put(tokenHead, token);
Map<String, String> querys = new HashMap<String, String>();
querys.put(cardNo, message.getIdNumber());
querys.put(realName, message.getName());
try {
HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
StatusLine statusLine = response.getStatusLine();
log.error(response.toString());
int statusCode = statusLine.getStatusCode();
log.error(statusCode+"");
//获取response的body
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + map);
if (MapUtil.isNotEmpty(map) || resultCode.equals(map.get(ret))) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
package com.xxfc.platform.universal.service.authenticationInterface.impl;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.xxfc.platform.universal.biz.UserMessage;
import com.xxfc.platform.universal.service.authenticationInterface.UserAuthentication;
import com.xxfc.platform.universal.utils.CertifHttpUtils;
import com.xxfc.platform.universal.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 调用四川涪擎认证接口
*
* @author Administrator
*/
@Service
@Slf4j
public class XCFQAuthentication implements UserAuthentication {
private String cAppcode="acea1c8811f748b3a65815f11db357c4";
/**
* 认证相关的数据
*/
private String cHost = "https://idcert.market.alicloudapi.com";
private String cPath = "/idcard";
private String cMethod = "GET";
//响应:认证错误码字段名
private String certifRet = "status";
//响应:认证通过码
private String certifResultCode = "01";
//请求:身份证号字段名
private String idCardName = "idCard";
//请求:用户姓名字段名
private String cName = "name";
@Override
public boolean certificate(UserMessage message) {
//map携带身份证和姓名进行认证
Map<String, String> querys = new HashMap<>();
querys.put(idCardName, message.getIdNumber());
querys.put(cName, message.getName());
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authorization", "APPCODE " + cAppcode);
try {
log.info("----querys=========" + querys);
HttpResponse response = HttpUtils.doGet(cHost, cPath, cMethod, headers, querys);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
/**
* 状态码: 200 正常;400 URL无效;401 appCode错误; 403 次数用完; 500 API网管错误
*/
//获取response的body
if (statusCode == 200) {
String result = EntityUtils.toString(response.getEntity());
log.info("----认证结果result=========" + result);
//认证返回的参数是否为空
if (!StringUtils.isBlank(result)) {
Map<String, Object> map = (Map<String, Object>) JSONObject.parse(result);
log.info("----certifRet=========" + certifRet);
if (MapUtil.isNotEmpty(map) || certifResultCode.equals(map.get(certifRet))) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment