6 years ago
parent
commit
32eca0cd3d
  1. 2
      game/src/main/java/com/ccsens/game/bean/dto/ScreenDto.java
  2. 2
      ht/src/main/java/com/ccsens/ht/service/DoctorService.java
  3. 6
      mt/src/main/java/com/ccsens/mt/service/ScoreService.java
  4. 30
      tall/src/main/java/com/ccsens/tall/bean/dto/UserDto.java
  5. 11
      tall/src/main/java/com/ccsens/tall/bean/po/SysDomain.java
  6. 70
      tall/src/main/java/com/ccsens/tall/bean/po/SysDomainExample.java
  7. 183
      tall/src/main/java/com/ccsens/tall/bean/po/SysWx.java
  8. 1191
      tall/src/main/java/com/ccsens/tall/bean/po/SysWxExample.java
  9. 2
      tall/src/main/java/com/ccsens/tall/bean/vo/DomainVo.java
  10. 24
      tall/src/main/java/com/ccsens/tall/bean/vo/UserVo.java
  11. 9
      tall/src/main/java/com/ccsens/tall/persist/dao/SysWxDao.java
  12. 30
      tall/src/main/java/com/ccsens/tall/persist/mapper/SysWxMapper.java
  13. 11
      tall/src/main/java/com/ccsens/tall/service/IUserService.java
  14. 1
      tall/src/main/java/com/ccsens/tall/service/SysDomainService.java
  15. 338
      tall/src/main/java/com/ccsens/tall/service/UserService.java
  16. 69
      tall/src/main/java/com/ccsens/tall/web/UserController.java
  17. 33
      tall/src/main/resources/mapper_raw/SysDomainMapper.xml
  18. 370
      tall/src/main/resources/mapper_raw/SysWxMapper.xml
  19. 6
      util/src/main/java/com/ccsens/util/CodeEnum.java
  20. 11
      util/src/main/java/com/ccsens/util/WebConstant.java
  21. 151
      util/src/main/java/com/ccsens/util/bean/wx/dto/WxGzhAction.java
  22. 18
      util/src/main/java/com/ccsens/util/bean/wx/po/WxAccessToken.java
  23. 12
      util/src/main/java/com/ccsens/util/bean/wx/po/WxBaseEntity.java
  24. 23
      util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhAuthType.java
  25. 97
      util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMenu.java
  26. 53
      util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMsgEvent.java
  27. 34
      util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMsgType.java
  28. 26
      util/src/main/java/com/ccsens/util/bean/wx/po/WxOauth2AccessToken.java
  29. 42
      util/src/main/java/com/ccsens/util/bean/wx/po/WxOauth2UserInfo.java
  30. 21
      util/src/main/java/com/ccsens/util/bean/wx/po/WxOperation.java
  31. 6
      util/src/main/java/com/ccsens/util/exception/BaseException.java
  32. 16
      util/src/main/java/com/ccsens/util/exception/BusinessException.java
  33. 19
      util/src/main/java/com/ccsens/util/exception/WxException.java
  34. 300
      util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java
  35. 406
      util/src/main/java/com/ccsens/util/wx/WxXcxUtil.java

2
game/src/main/java/com/ccsens/game/bean/dto/ScreenDto.java

@ -13,7 +13,7 @@ public class ScreenDto {
public static class MemberGame{
@ApiModelProperty("项目id")
private Long projectId;
@ApiModelProperty("要创建的小游戏的类型 例如:SQ 代表数钱小游戏")
@ApiModelProperty("要创建的小游戏的类型 例如:SQ:数钱 SP:赛跑")
private String gameType;
}

2
ht/src/main/java/com/ccsens/ht/service/DoctorService.java

@ -70,7 +70,7 @@ public class DoctorService implements IDoctorService {
oldDoctor = doctor;
}
}
//查找职务是否存在
//查找科室是否存在
HtPosition position = htPositionDao.selectByPrimaryKey(submit.getPositionId());
if (position == null) {
log.info("{}未找到对应职务。", submit.getPositionId());

6
mt/src/main/java/com/ccsens/mt/service/ScoreService.java

@ -270,12 +270,12 @@ public class ScoreService implements IScoreService{
List<MtJudge> judgeList = judgeDao.selectByExample(judgeExample);
if (CollectionUtil.isNotEmpty(judgeList)) {
for (MtJudge judge : judgeList) {
BigDecimal scoreSUM = scoreDao.sumScoreByJudgeId(judge.getId(), taskId);
if(ObjectUtil.isNotNull(scoreSUM)) {
BigDecimal scoreSum = scoreDao.sumScoreByJudgeId(judge.getId(), taskId);
if(ObjectUtil.isNotNull(scoreSum)) {
judgeScore = new ScoreVo.JudgeScore();
judgeScore.setJudgeId(judge.getId());
judgeScore.setJudgeName(judge.getNickname());
judgeScore.setScore(scoreSUM);
judgeScore.setScore(scoreSum);
judgeScoreList.add(judgeScore);
}

30
tall/src/main/java/com/ccsens/tall/bean/dto/UserDto.java

@ -27,7 +27,7 @@ public class UserDto {
@ApiModelProperty("登录客户端:0-wxmp,1-H5,2-Android,3-IOS")
@NotNull(message = "client is required.")
private Integer client;
@ApiModelProperty("登录类型:0-wxmp,1-phone,2-email,3-accounts")
@ApiModelProperty("登录类型:0-wxmp,1-phone,2-email,3-accounts,4-OAUTH2_Wx,5-Wx_H5,6-OAUTH2_WeiBo")
@NotNull(message = "type is required.")
private Integer type;
@ApiModelProperty("登录信息")
@ -62,7 +62,7 @@ public class UserDto {
public static class UpdatePassword{
@ApiModelProperty("手机号")
@NotEmpty(message = "手机号不能为空")
@Pattern(regexp="^1[34578]\\d{9}$",message="请输入正确的手机号")
@Pattern(regexp="^[1]([3-9])[0-9]{9}$",message="请输入正确的手机号")
private String phone;
@ApiModelProperty("验证码")
@NotEmpty(message = "验证码不能为空.")
@ -79,7 +79,7 @@ public class UserDto {
public static class UserSignup{
@ApiModelProperty("手机号")
@NotEmpty(message = "手机号不能为空")
@Pattern(regexp="^1[34578]\\d{9}$",message="请输入正确的手机号")
@Pattern(regexp="^[1]([3-9])[0-9]{9}$",message="请输入正确的手机号")
private String phone;
@ApiModelProperty("验证码")
@NotEmpty(message = "验证码不能为空.")
@ -96,5 +96,29 @@ public class UserDto {
private byte source = WebConstant.Regist.SOURCE;
}
@Data
@ApiModel
public static class WxMergePhone{
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("手机验证码")
private String smsCode;
@ApiModelProperty("微信code")
private String wxCode;
}
@Data
@ApiModel
public static class WxBindingPhone{
@ApiModelProperty("手机号")
private String phone;
@ApiModelProperty("手机验证码")
private String smsCode;
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private String password;
@ApiModelProperty("微信code")
private String wxCode;
}
}

11
tall/src/main/java/com/ccsens/tall/bean/po/SysDomain.java

@ -14,6 +14,8 @@ public class SysDomain implements Serializable {
private String systemName;
private String backdropUrl;
private Byte showCalendar;
private Long showProjectId;
@ -70,6 +72,14 @@ public class SysDomain implements Serializable {
this.systemName = systemName == null ? null : systemName.trim();
}
public String getBackdropUrl() {
return backdropUrl;
}
public void setBackdropUrl(String backdropUrl) {
this.backdropUrl = backdropUrl == null ? null : backdropUrl.trim();
}
public Byte getShowCalendar() {
return showCalendar;
}
@ -137,6 +147,7 @@ public class SysDomain implements Serializable {
sb.append(", logo=").append(logo);
sb.append(", companyName=").append(companyName);
sb.append(", systemName=").append(systemName);
sb.append(", backdropUrl=").append(backdropUrl);
sb.append(", showCalendar=").append(showCalendar);
sb.append(", showProjectId=").append(showProjectId);
sb.append(", caption=").append(caption);

70
tall/src/main/java/com/ccsens/tall/bean/po/SysDomainExample.java

@ -445,6 +445,76 @@ public class SysDomainExample {
return (Criteria) this;
}
public Criteria andBackdropUrlIsNull() {
addCriterion("backdrop_url is null");
return (Criteria) this;
}
public Criteria andBackdropUrlIsNotNull() {
addCriterion("backdrop_url is not null");
return (Criteria) this;
}
public Criteria andBackdropUrlEqualTo(String value) {
addCriterion("backdrop_url =", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlNotEqualTo(String value) {
addCriterion("backdrop_url <>", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlGreaterThan(String value) {
addCriterion("backdrop_url >", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlGreaterThanOrEqualTo(String value) {
addCriterion("backdrop_url >=", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlLessThan(String value) {
addCriterion("backdrop_url <", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlLessThanOrEqualTo(String value) {
addCriterion("backdrop_url <=", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlLike(String value) {
addCriterion("backdrop_url like", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlNotLike(String value) {
addCriterion("backdrop_url not like", value, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlIn(List<String> values) {
addCriterion("backdrop_url in", values, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlNotIn(List<String> values) {
addCriterion("backdrop_url not in", values, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlBetween(String value1, String value2) {
addCriterion("backdrop_url between", value1, value2, "backdropUrl");
return (Criteria) this;
}
public Criteria andBackdropUrlNotBetween(String value1, String value2) {
addCriterion("backdrop_url not between", value1, value2, "backdropUrl");
return (Criteria) this;
}
public Criteria andShowCalendarIsNull() {
addCriterion("show_calendar is null");
return (Criteria) this;

183
tall/src/main/java/com/ccsens/tall/bean/po/SysWx.java

@ -0,0 +1,183 @@
package com.ccsens.tall.bean.po;
import java.io.Serializable;
import java.util.Date;
public class SysWx implements Serializable {
private Long id;
private Long userId;
private String openId;
private String unionId;
private String nickname;
private String headImgUrl;
private Byte sex;
private String province;
private String city;
private String country;
private String language;
private String privilege;
private Date createdAt;
private Date updatedAt;
private Byte recStatus;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId == null ? null : openId.trim();
}
public String getUnionId() {
return unionId;
}
public void setUnionId(String unionId) {
this.unionId = unionId == null ? null : unionId.trim();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname == null ? null : nickname.trim();
}
public String getHeadImgUrl() {
return headImgUrl;
}
public void setHeadImgUrl(String headImgUrl) {
this.headImgUrl = headImgUrl == null ? null : headImgUrl.trim();
}
public Byte getSex() {
return sex;
}
public void setSex(Byte sex) {
this.sex = sex;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city == null ? null : city.trim();
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country == null ? null : country.trim();
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language == null ? null : language.trim();
}
public String getPrivilege() {
return privilege;
}
public void setPrivilege(String privilege) {
this.privilege = privilege == null ? null : privilege.trim();
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Byte getRecStatus() {
return recStatus;
}
public void setRecStatus(Byte recStatus) {
this.recStatus = recStatus;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userId=").append(userId);
sb.append(", openId=").append(openId);
sb.append(", unionId=").append(unionId);
sb.append(", nickname=").append(nickname);
sb.append(", headImgUrl=").append(headImgUrl);
sb.append(", sex=").append(sex);
sb.append(", province=").append(province);
sb.append(", city=").append(city);
sb.append(", country=").append(country);
sb.append(", language=").append(language);
sb.append(", privilege=").append(privilege);
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", recStatus=").append(recStatus);
sb.append("]");
return sb.toString();
}
}

1191
tall/src/main/java/com/ccsens/tall/bean/po/SysWxExample.java

File diff suppressed because it is too large

2
tall/src/main/java/com/ccsens/tall/bean/vo/DomainVo.java

@ -22,6 +22,8 @@ public class DomainVo {
private String companyName;
@ApiModelProperty("系统名")
private String systemName;
@ApiModelProperty("系统名")
private String backdropUrl;
@ApiModelProperty("标题")
private String caption;
@ApiModelProperty("栏外标题")

24
tall/src/main/java/com/ccsens/tall/bean/vo/UserVo.java

@ -30,6 +30,8 @@ public class UserVo {
private String token;
@ApiModelProperty("刷新token")
private String refresh_token;
@ApiModelProperty("微信信息")
private WxInfo wxInfo;
}
@Data
@ -61,4 +63,26 @@ public class UserVo {
private Long id;
}
@Data
@ApiModel
public static class WxInfo{
@ApiModelProperty("openId")
private String openId;
@ApiModelProperty("unionId")
private String unionId;
@ApiModelProperty("微信名")
private String nickname;
@ApiModelProperty("微信头像")
private String headImgUrl;
@ApiModelProperty("性别")
private Byte sex;
@ApiModelProperty("省")
private String province;
@ApiModelProperty("市")
private String city;
@ApiModelProperty("国家")
private String country;
@ApiModelProperty("语言")
private String language;
}
}

9
tall/src/main/java/com/ccsens/tall/persist/dao/SysWxDao.java

@ -0,0 +1,9 @@
package com.ccsens.tall.persist.dao;
import com.ccsens.tall.persist.mapper.SysWxMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface SysWxDao extends SysWxMapper {
}

30
tall/src/main/java/com/ccsens/tall/persist/mapper/SysWxMapper.java

@ -0,0 +1,30 @@
package com.ccsens.tall.persist.mapper;
import com.ccsens.tall.bean.po.SysWx;
import com.ccsens.tall.bean.po.SysWxExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface SysWxMapper {
long countByExample(SysWxExample example);
int deleteByExample(SysWxExample example);
int deleteByPrimaryKey(Long id);
int insert(SysWx record);
int insertSelective(SysWx record);
List<SysWx> selectByExample(SysWxExample example);
SysWx selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") SysWx record, @Param("example") SysWxExample example);
int updateByExample(@Param("record") SysWx record, @Param("example") SysWxExample example);
int updateByPrimaryKeySelective(SysWx record);
int updateByPrimaryKey(SysWx record);
}

11
tall/src/main/java/com/ccsens/tall/service/IUserService.java

@ -17,16 +17,17 @@ public interface IUserService {
UserVo.TokenBean generateToken(WebConstant.CLIENT_TYPE client_type, Object subject, Map<String, Object> payLoads) throws Exception;
UserVo.TokenBean getUserInfoAndToken(WebConstant.CLIENT_TYPE client_type, UserVo.UserSign userSignVo, Map<String, Object> theMap) throws Exception;
boolean tokenNotExistInCache(Long authId) throws Exception;
UserVo.SmsCode getSignInSmsCode(String phone) throws Exception;
UserVo.SmsCode getSignInSmsCode(String phone,Integer client) throws Exception;
SysUser getUserById(Long aLong) throws Exception;
UserVo.UserSign registerUser(UserDto.UserSignup userSignup)throws Exception;
String bindingPhone(Long currentUserId, String phone, String code)throws Exception;
String bindingNewPhone(Long currentUserId,UserDto.WxBindingPhone wxPhone)throws Exception;
String getPhone(Long userId);
@ -34,6 +35,8 @@ public interface IUserService {
Boolean findAccount(String account);
Boolean findPhone(String phone);
UserVo.UserSign saveAuth(UserDto.UserSignup userSignup);
void updateAccount(UserDto.Account account);
@ -46,8 +49,6 @@ public interface IUserService {
List<Long> selectUserIdByRoleId(Long roleId)throws Exception;
//访问用户管理微服务==========================================================================
// UserVo.TokenBean userManageSignin(UserDto.UserSginin dto)throws Exception;
//默认注册
/**
@ -58,4 +59,6 @@ public interface IUserService {
*@date: 2019/10/29 14:43
*/
long defaultRegisterUser(com.ccsens.cloudutil.bean.tall.dto.UserDto.DefaultUserSingup signup);
}

1
tall/src/main/java/com/ccsens/tall/service/SysDomainService.java

@ -40,6 +40,7 @@ public class SysDomainService implements ISysDomainService{
domainInfo.setLogo("");
domainInfo.setCompanyName("传控电子科技有限公司");
domainInfo.setSystemName("欢迎登录时物链条");
domainInfo.setBackdropUrl("");
domainInfo.setCaption("TM");
domainInfo.setHeadline("TALL");
domainInfo.setShowCalender(1);

338
tall/src/main/java/com/ccsens/tall/service/UserService.java

@ -1,19 +1,21 @@
package com.ccsens.tall.service;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ccsens.tall.bean.dto.UserDto;
import com.ccsens.tall.bean.po.*;
import com.ccsens.tall.bean.vo.UserVo;
import com.ccsens.tall.exception.SmsException;
import com.ccsens.tall.persist.dao.ProMemberDao;
import com.ccsens.tall.persist.dao.ProMemberRoleDao;
import com.ccsens.tall.persist.dao.SysAuthDao;
import com.ccsens.tall.persist.dao.SysUserDao;
import com.ccsens.tall.persist.dao.*;
import com.ccsens.util.*;
import com.ccsens.util.bean.wx.po.WxOauth2UserInfo;
import com.ccsens.util.exception.BaseException;
import com.ccsens.util.wx.WxGzhUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -23,10 +25,12 @@ import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class UserService implements IUserService {
@Autowired
private SysUserDao userDao;
@ -40,6 +44,8 @@ public class UserService implements IUserService {
private Snowflake snowflake;
@Autowired
private RedisUtil redisUtil;
@Autowired
private SysWxDao sysWxDao;
/**
* 登录
@ -63,9 +69,9 @@ public class UserService implements IUserService {
case Wxmp:
return wxmplogin(identifier);
case OAUTH2_Wx:
//微信登录
//Fix Me.
break;
return wxLogin(identifyType,identifier);
case Wx_H5:
return wxH5Login(identifyType,identifier);
case OAUTH2_WeiBo:
//Fix Me.
break;
@ -75,10 +81,139 @@ public class UserService implements IUserService {
return emailLogin(identifier, credential);
case Account:
return accountLogin(identifier, credential);
default:
break;
}
return null;
}
/**
* 微信网页登陆
*
* @param code
* @return
*/
private UserVo.UserSign wxH5Login(WebConstant.IDENTIFY_TYPE identifyType,String code) {
UserVo.UserSign userSignVo = null;
//获取微信信息并保存
WxOauth2UserInfo wxOauth2UserInfo = WxGzhUtil.getOauth2UserInfo(identifyType,code);
SysAuth theAuth = null;
if (ObjectUtil.isNotNull(wxOauth2UserInfo)) {
//查找有无保存的信息
SysWxExample sysWxExample = new SysWxExample();
sysWxExample.createCriteria().andUnionIdEqualTo(wxOauth2UserInfo.getUnionId());
List<SysWx> sysWxList = sysWxDao.selectByExample(sysWxExample);
SysWx sysWx = null;
if (CollUtil.isNotEmpty(sysWxList)) {
//如果有信息,则更新
sysWx = sysWxList.get(0);
BeanUtil.copyProperties(wxOauth2UserInfo, sysWx);
sysWxDao.updateByPrimaryKeySelective(sysWx);
} else {
//没有则保存微信信息
sysWx = new SysWx();
BeanUtil.copyProperties(wxOauth2UserInfo, sysWx);
sysWx.setId(snowflake.nextId());
sysWxDao.insertSelective(sysWx);
}
//查找认证信息
SysAuthExample authExample = new SysAuthExample();
authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Wx_H5.value)
.andIdentifierEqualTo(sysWx.getUnionId()).andCredentialEqualTo(sysWx.getOpenId());
List<SysAuth> authList = authDao.selectByExample(authExample);
if (CollectionUtil.isNotEmpty(authList)) {
theAuth = authList.get(0);
} else {
//1.添加user
SysUser user = new SysUser();
user.setId(snowflake.nextId());
userDao.insertSelective(user);
//2.添加auth
theAuth = new SysAuth();
theAuth.setId(snowflake.nextId());
theAuth.setUserId(user.getId());
theAuth.setIdentifyType((byte) WebConstant.IDENTIFY_TYPE.Wx_H5.value);
theAuth.setIdentifier(sysWx.getUnionId());
theAuth.setCredential(sysWx.getOpenId());
authDao.insertSelective(theAuth);
}
}else{
throw new BaseException(CodeEnum.NOT_SELECT_WX);
}
//2.返回
userSignVo = new UserVo.UserSign();
userSignVo.setUserId(theAuth.getUserId());
userSignVo.setAuthId(theAuth.getId());
return userSignVo;
}
/**
* 微信公众号登陆
*
* @param code
* @return
* @throws Exception
*/
private UserVo.UserSign wxLogin(WebConstant.IDENTIFY_TYPE identifyType,String code) throws Exception {
UserVo.UserSign userSignVo = null;
//获取微信信息并保存
WxOauth2UserInfo wxOauth2UserInfo = WxGzhUtil.getOauth2UserInfo(identifyType,code);
SysAuth theAuth = null;
if (ObjectUtil.isNotNull(wxOauth2UserInfo)) {
//查找有无保存的信息
SysWxExample sysWxExample = new SysWxExample();
sysWxExample.createCriteria().andUnionIdEqualTo(wxOauth2UserInfo.getUnionId());
List<SysWx> sysWxList = sysWxDao.selectByExample(sysWxExample);
SysWx sysWx = null;
if (CollUtil.isNotEmpty(sysWxList)) {
//如果有信息,则更新
sysWx = sysWxList.get(0);
BeanUtil.copyProperties(wxOauth2UserInfo, sysWx);
sysWxDao.updateByPrimaryKeySelective(sysWx);
} else {
//没有则保存微信信息
sysWx = new SysWx();
BeanUtil.copyProperties(wxOauth2UserInfo, sysWx);
sysWx.setId(snowflake.nextId());
sysWxDao.insertSelective(sysWx);
}
//查找认证信息
SysAuthExample authExample = new SysAuthExample();
authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.OAUTH2_Wx.value)
.andIdentifierEqualTo(sysWx.getUnionId()).andCredentialEqualTo(sysWx.getOpenId());
List<SysAuth> authList = authDao.selectByExample(authExample);
if (CollectionUtil.isNotEmpty(authList)) {
theAuth = authList.get(0);
} else {
//1.添加user
SysUser user = new SysUser();
user.setId(snowflake.nextId());
userDao.insertSelective(user);
//2.添加auth
theAuth = new SysAuth();
theAuth.setId(snowflake.nextId());
theAuth.setUserId(user.getId());
theAuth.setIdentifyType((byte) WebConstant.IDENTIFY_TYPE.OAUTH2_Wx.value);
theAuth.setIdentifier(sysWx.getUnionId());
theAuth.setCredential(sysWx.getOpenId());
authDao.insertSelective(theAuth);
}
}else{
throw new BaseException(CodeEnum.NOT_SELECT_WX);
}
//2.返回
userSignVo = new UserVo.UserSign();
userSignVo.setUserId(theAuth.getUserId());
userSignVo.setAuthId(theAuth.getId());
return userSignVo;
}
public void __addSigninRecord(WebConstant.CLIENT_TYPE clientType, String clientIp, Long authId) {
// SigninLog siginLog = new SigninLog();
// siginLog.setId(snowflake.nextId());
@ -91,6 +226,7 @@ public class UserService implements IUserService {
/**
* 手机号登陆
*
* @param phone
* @param smsVerifyCode
* @return
@ -267,7 +403,23 @@ public class UserService implements IUserService {
* 发送验证码
*/
@Override
public UserVo.SmsCode getSignInSmsCode(String phone) throws Exception {
public UserVo.SmsCode getSignInSmsCode(String phone,Integer client) throws Exception {
//获取登陆客户端类型
WebConstant.CLIENT_TYPE client_type = null;
if(ObjectUtil.isNotNull(client)) {
client_type = WebConstant.CLIENT_TYPE.valueOf(client);
}else {
client_type = WebConstant.CLIENT_TYPE.valueOf(1);
}
//验证手机号的正确性
String regex = "[1]([3-9])[0-9]{9}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
if (!isMatch) {
throw new BaseException(CodeEnum.PHONE_ERR);
}
UserVo.SmsCode smsCodeVo = null;
//1.验证发送间隔是否大于指定间隔
if (redisUtil.hasKey(RedisKeyManager.getSigninSmsExistKey(phone))) {
@ -275,8 +427,8 @@ public class UserService implements IUserService {
}
//2.生成随机验证码
//String verifyCode = RandomUtil.randomNumbers(4);
String verifyCode = "1111";
String verifyCode = RandomUtil.randomNumbers(4);
// String verifyCode = "1111";
//3.保存到redis中
Integer codeValidInSeconds = WebConstant.Expired_Verify_Code_In_Seconds;
@ -285,7 +437,7 @@ public class UserService implements IUserService {
redisUtil.set(RedisKeyManager.getSigninSmsExistKey(phone), verifyCode, codeExistINSeconds);
//5.发送验证码
//SmsUtil.sendSms(identifier,verifyCode,"微信小程序",codeValidInSeconds);
SmsUtil.sendSms(phone,verifyCode,client_type.phase,codeValidInSeconds);
//6.返回
smsCodeVo = new UserVo.SmsCode();
@ -327,8 +479,7 @@ public class UserService implements IUserService {
Boolean flag = findAccount(userSignup.getAccount());
if (!flag) {
userSignVo = saveAuth(userSignup);
}else {
} else {
throw new BaseException("账号已存在");
}
} else {
@ -408,6 +559,29 @@ public class UserService implements IUserService {
return CollectionUtil.isNotEmpty(authList);
}
/**
* 查找手机号
*/
@Override
public Boolean findPhone(String phone) {
//验证手机号的正确性
String regex = "[1]([3-9])[0-9]{9}$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(phone);
boolean isMatch = m.matches();
if (!isMatch) {
throw new BaseException(CodeEnum.PHONE_ERR);
}
Boolean flag = false;
SysAuthExample authExample = new SysAuthExample();
authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Phone.value)
.andIdentifierEqualTo(phone);
List<SysAuth> authList = authDao.selectByExample(authExample);
return CollectionUtil.isNotEmpty(authList);
}
/**
* 修改账号信息
*/
@ -433,51 +607,61 @@ public class UserService implements IUserService {
return !redisUtil.hasKey(RedisKeyManager.getTokenCachedKey(authId));
}
/**
* 微信绑定新手机号没有账号注册
*
* @param currentUserId
* @param wxPhone
* @return
* @throws Exception
*/
@Override
public String bindingPhone(Long currentUserId, String phone, String code) throws Exception {
if (redisUtil.hasKey(RedisKeyManager.getSigninSmsKey(phone))) {
if (code.equals(redisUtil.get(RedisKeyManager.getSigninSmsKey(phone)).toString())) {
//查找改用户以前绑定的手机,如果有 替换
SysAuthExample authExample = new SysAuthExample();
authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Phone.value)
.andUserIdEqualTo(currentUserId);
List<SysAuth> authList = authDao.selectByExample(authExample);
if (CollectionUtil.isNotEmpty(authList)) {
for (SysAuth auth : authList) {
if (auth.getIdentifier().equals(phone)) {
throw new BaseException(-1, "您的账号已经绑定过此手机,请勿重复绑定");
} else {
throw new BaseException(-1, "您的账号已绑定手机" + auth.getIdentifier());
}
}
} else {
//改手机对应账户,如果有,提示
List<SysAuth> phoneList = null;
SysAuth theAuth = null;
SysAuthExample phoneExample = new SysAuthExample();
authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Phone.value)
.andIdentifierEqualTo(phone);
phoneList = authDao.selectByExample(phoneExample);
if (CollectionUtil.isNotEmpty(authList)) {//已被注册 提示
throw new BaseException(-1, "该手机号已被注册,请更换手机号重试");
} else {
//绑定 添加auth
SysAuth auth = new SysAuth();
auth.setId(snowflake.nextId());
auth.setUserId(currentUserId);
auth.setIdentifyType((byte) WebConstant.IDENTIFY_TYPE.Phone.value);
auth.setIdentifier(phone);
auth.setCredential(code);
authDao.insertSelective(auth);
}
}
}
} else {
throw new BaseException(-1, "验证信息不正确");
}
return phone;
public String bindingNewPhone(Long currentUserId, UserDto.WxBindingPhone wxPhone) throws Exception {
// if (isSmsCodeCorrect(wxPhone.getPhone(), wxPhone.getSmsCode())) {
// //查找该用户以前绑定的手机
// SysAuthExample authExample = new SysAuthExample();
// authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Phone.value)
// .andUserIdEqualTo(currentUserId);
// List<SysAuth> authList = authDao.selectByExample(authExample);
// if (CollectionUtil.isNotEmpty(authList)) {
// for (SysAuth auth : authList) {
// if (auth.getIdentifier().equals(wxPhone.getPhone())) {
// throw new BaseException(-1, "您的账号已经绑定过此手机,请勿重复绑定");
// } else {
// throw new BaseException(-1, "您的账号已绑定手机" + auth.getIdentifier());
// }
// }
// } else {
// //改手机对应账户,如果有,提示
// List<SysAuth> phoneList = null;
// SysAuth theAuth = null;
// SysAuthExample phoneExample = new SysAuthExample();
// authExample.createCriteria().andIdentifyTypeEqualTo((byte) WebConstant.IDENTIFY_TYPE.Phone.value)
// .andIdentifierEqualTo(wxPhone.getPhone());
// phoneList = authDao.selectByExample(phoneExample);
// if (CollectionUtil.isNotEmpty(phoneList)) {//已被注册 提示
// //合并
// } else {
// throw new BaseException(CodeEnum.NOT_REGISTER);
//// //绑定 添加auth
//// SysAuth auth = new SysAuth();
//// auth.setId(snowflake.nextId());
//// auth.setUserId(currentUserId);
//// auth.setIdentifyType((byte) WebCo nstant.IDENTIFY_TYPE.Phone.value);
//// auth.setIdentifier(phone);
//// auth.setCredential(code);
//// authDao.insertSelective(auth);
// }
// }
// }else {
// throw new BaseException(CodeEnum.SMS_CODE_CORRECT);
// }
return null;
}
/**
* 更改绑定手机号
*/
@Override
public void updatePhone(Long currentUserId, UserDto.UpdatePhone updatePhone) throws Exception {
if (isSmsCodeCorrect(updatePhone.getNewPhone(), updatePhone.getCode())) {
@ -521,7 +705,7 @@ public class UserService implements IUserService {
}
/**
*判断验证码是否有效
* 判断验证码是否有效
*/
private Boolean isSmsCodeCorrect(String phone, String smsCode) throws Exception {
Boolean correct = false;
@ -549,10 +733,10 @@ public class UserService implements IUserService {
List<SysAuth> authList = authDao.selectByExample(sysAuthExample);
if (CollectionUtil.isNotEmpty(authList)) {
SysAuth auth = authList.get(0);
if(!ShiroKit.authenticate(passwordDto.getPassword(), auth.getCredential(), auth.getSalt())){
if (!ShiroKit.authenticate(passwordDto.getPassword(), auth.getCredential(), auth.getSalt())) {
auth.setCredential(ShiroKit.md5(passwordDto.getPassword(), auth.getSalt()));
authDao.updateByPrimaryKeySelective(auth);
}else {
} else {
throw new BaseException("新密码不能和旧密码相同");
}
} else {
@ -569,6 +753,7 @@ public class UserService implements IUserService {
/**
* 通过用户查找手机号
*
* @param userId
* @return
*/
@ -679,4 +864,39 @@ public class UserService implements IUserService {
UserVo.UserSign userSign = saveAuth(up);
return userSign.getUserId();
}
@Override
public UserVo.TokenBean getUserInfoAndToken(WebConstant.CLIENT_TYPE client_type, UserVo.UserSign userSignVo, Map<String, Object> theMap) throws Exception {
UserVo.TokenBean tokenBean = generateToken(client_type, userSignVo.getUserId(), theMap);
//获取手机号
String phone = getPhone(userSignVo.getUserId());
//获取账号
String account = selectAccountByPhone(phone);
//获取用户的微信信息
SysAuth sysAuth = authDao.selectByPrimaryKey(userSignVo.getAuthId());
UserVo.WxInfo wxInfo = new UserVo.WxInfo();
SysWx sysWx = getSysWx(sysAuth.getIdentifier());
if(ObjectUtil.isNotNull(sysAuth)){
BeanUtil.copyProperties(sysWx,wxInfo);
}
tokenBean.setId(userSignVo.getUserId());
tokenBean.setPhone(phone);
tokenBean.setAccount(account);
tokenBean.setWxInfo(wxInfo);
return tokenBean;
}
private SysWx getSysWx(String unionId){
SysWx sysWx = null;
SysWxExample sysWxExample = new SysWxExample();
sysWxExample.createCriteria().andUnionIdEqualTo(unionId);
List<SysWx> sysWxList = sysWxDao.selectByExample(sysWxExample);
if(CollectionUtil.isNotEmpty(sysWxList)){
sysWx = sysWxList.get(0);
}
return sysWx;
}
}

69
tall/src/main/java/com/ccsens/tall/web/UserController.java

@ -63,6 +63,7 @@ public class UserController {
switch (identify_type) {
case Wxmp:
case OAUTH2_Wx:
case Wx_H5:
case OAUTH2_WeiBo: {
break;
}
@ -90,14 +91,8 @@ public class UserController {
if (ObjectUtil.isNotNull(userSignVo)) {
Map<String, Object> theMap = CollectionUtil.newHashMap();
theMap.put("authId", String.valueOf(userSignVo.getAuthId()));
UserVo.TokenBean tokenBean = userService.generateToken(client_type, userSignVo.getUserId(), theMap);
//获取手机号
String phone = userService.getPhone(userSignVo.getUserId());
//获取账号
String account = userService.selectAccountByPhone(phone);
tokenBean.setId(userSignVo.getUserId());
tokenBean.setPhone(phone);
tokenBean.setAccount(account);
UserVo.TokenBean tokenBean = userService.getUserInfoAndToken(client_type, userSignVo, theMap);
return JsonResponse.newInstance().ok(tokenBean);
} else {
return JsonResponse.newInstance().fail("登陆信息不正确.");
@ -109,8 +104,9 @@ public class UserController {
})
@RequestMapping(value = "/smscode", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public JsonResponse<UserVo.SmsCode> getSmsCode(HttpServletRequest request,
@ApiParam @RequestParam String phone) throws Exception {
UserVo.SmsCode smsCodeVo = userService.getSignInSmsCode(phone);
@ApiParam @RequestParam String phone,
@ApiParam @RequestParam Integer client) throws Exception {
UserVo.SmsCode smsCodeVo = userService.getSignInSmsCode(phone,client);
return JsonResponse.newInstance().ok(smsCodeVo);
}
@ -145,11 +141,21 @@ public class UserController {
@ApiImplicitParams({
})
@RequestMapping(value = "/account", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public JsonResponse<List<UserVo.Account>> accounts(HttpServletRequest request,
@ApiParam @RequestParam String account) throws Exception {
// List<UserVo.Account> accounts = userService.findAccount();
userService.findAccount(account);
return JsonResponse.newInstance().ok();
public JsonResponse accounts(@ApiParam @RequestParam String account) throws Exception {
Boolean flag = userService.findAccount(account);
return JsonResponse.newInstance().ok(flag);
}
@ApiOperation(value = "/检查手机号是否被注册", notes = "")
@ApiImplicitParams({
})
@RequestMapping(value = "/phone", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
public JsonResponse findPhone(@ApiParam @RequestParam String phone) throws Exception {
Boolean flag = userService.findPhone(phone);
return JsonResponse.newInstance().ok(flag);
}
// @ApiOperation(value = "/修改账号信息",notes = "")
@ -162,16 +168,27 @@ public class UserController {
// }
// @ApiOperation(value = "/微信绑定手机",notes = "")
// @ApiImplicitParams({
// })
// @RequestMapping(value="/phone",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
// public JsonResponse bindingPhone(HttpServletRequest request,
// @ApiParam @RequestBody UserDto.Phone phone) throws Exception {
// Long currentUserId = Long.valueOf(((Claims) request.getAttribute(WebConstant.REQUEST_KEY_CLAIMS)).getSubject());
// String returnPhone = userService.bindingPhone(currentUserId,phone.getPhone(),phone.getCode());
// return JsonResponse.newInstance().ok(returnPhone);
// }
@ApiOperation(value = "/微信合并已有账号",notes = "")
@ApiImplicitParams({
})
@RequestMapping(value="/merge",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
public JsonResponse bindingPhone(HttpServletRequest request,
@ApiParam @RequestBody UserDto.WxMergePhone wxPhone) throws Exception {
Long currentUserId = Long.valueOf(((Claims) request.getAttribute(WebConstant.REQUEST_KEY_CLAIMS)).getSubject());
// String returnPhone = userService.bindingPhone(currentUserId,wxPhone);
return JsonResponse.newInstance().ok();
}
@ApiOperation(value = "/微信绑定账号(没有账号,注册)",notes = "")
@ApiImplicitParams({
})
@RequestMapping(value="/phone",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
public JsonResponse bindingPhone(HttpServletRequest request,
@ApiParam @RequestBody UserDto.WxBindingPhone wxPhone) throws Exception {
Long currentUserId = Long.valueOf(((Claims) request.getAttribute(WebConstant.REQUEST_KEY_CLAIMS)).getSubject());
String returnPhone = userService.bindingNewPhone(currentUserId,wxPhone);
return JsonResponse.newInstance().ok(returnPhone);
}
@ApiOperation(value = "/更改绑定手机", notes = "")
@ApiImplicitParams({
@ -282,6 +299,8 @@ public class UserController {
List<Long> memberIdInfo = proMemberService.getMemberIdByProjectId(projectId);
return memberIdInfo;
}
}

33
tall/src/main/resources/mapper_raw/SysDomainMapper.xml

@ -7,6 +7,7 @@
<result column="logo" jdbcType="VARCHAR" property="logo" />
<result column="company_name" jdbcType="VARCHAR" property="companyName" />
<result column="system_name" jdbcType="VARCHAR" property="systemName" />
<result column="backdrop_url" jdbcType="VARCHAR" property="backdropUrl" />
<result column="show_calendar" jdbcType="TINYINT" property="showCalendar" />
<result column="show_project_id" jdbcType="BIGINT" property="showProjectId" />
<result column="caption" jdbcType="VARCHAR" property="caption" />
@ -74,7 +75,7 @@
</where>
</sql>
<sql id="Base_Column_List">
id, domain_name, logo, company_name, system_name, show_calendar, show_project_id,
id, domain_name, logo, company_name, system_name, backdrop_url, show_calendar, show_project_id,
caption, headline, created_at, updated_at, rec_status
</sql>
<select id="selectByExample" parameterType="com.ccsens.tall.bean.po.SysDomainExample" resultMap="BaseResultMap">
@ -109,15 +110,15 @@
</delete>
<insert id="insert" parameterType="com.ccsens.tall.bean.po.SysDomain">
insert into t_sys_domain (id, domain_name, logo,
company_name, system_name, show_calendar,
show_project_id, caption, headline,
created_at, updated_at, rec_status
)
company_name, system_name, backdrop_url,
show_calendar, show_project_id, caption,
headline, created_at, updated_at,
rec_status)
values (#{id,jdbcType=BIGINT}, #{domainName,jdbcType=VARCHAR}, #{logo,jdbcType=VARCHAR},
#{companyName,jdbcType=VARCHAR}, #{systemName,jdbcType=VARCHAR}, #{showCalendar,jdbcType=TINYINT},
#{showProjectId,jdbcType=BIGINT}, #{caption,jdbcType=VARCHAR}, #{headline,jdbcType=VARCHAR},
#{createdAt,jdbcType=TIMESTAMP}, #{updatedAt,jdbcType=TIMESTAMP}, #{recStatus,jdbcType=TINYINT}
)
#{companyName,jdbcType=VARCHAR}, #{systemName,jdbcType=VARCHAR}, #{backdropUrl,jdbcType=VARCHAR},
#{showCalendar,jdbcType=TINYINT}, #{showProjectId,jdbcType=BIGINT}, #{caption,jdbcType=VARCHAR},
#{headline,jdbcType=VARCHAR}, #{createdAt,jdbcType=TIMESTAMP}, #{updatedAt,jdbcType=TIMESTAMP},
#{recStatus,jdbcType=TINYINT})
</insert>
<insert id="insertSelective" parameterType="com.ccsens.tall.bean.po.SysDomain">
insert into t_sys_domain
@ -137,6 +138,9 @@
<if test="systemName != null">
system_name,
</if>
<if test="backdropUrl != null">
backdrop_url,
</if>
<if test="showCalendar != null">
show_calendar,
</if>
@ -175,6 +179,9 @@
<if test="systemName != null">
#{systemName,jdbcType=VARCHAR},
</if>
<if test="backdropUrl != null">
#{backdropUrl,jdbcType=VARCHAR},
</if>
<if test="showCalendar != null">
#{showCalendar,jdbcType=TINYINT},
</if>
@ -222,6 +229,9 @@
<if test="record.systemName != null">
system_name = #{record.systemName,jdbcType=VARCHAR},
</if>
<if test="record.backdropUrl != null">
backdrop_url = #{record.backdropUrl,jdbcType=VARCHAR},
</if>
<if test="record.showCalendar != null">
show_calendar = #{record.showCalendar,jdbcType=TINYINT},
</if>
@ -255,6 +265,7 @@
logo = #{record.logo,jdbcType=VARCHAR},
company_name = #{record.companyName,jdbcType=VARCHAR},
system_name = #{record.systemName,jdbcType=VARCHAR},
backdrop_url = #{record.backdropUrl,jdbcType=VARCHAR},
show_calendar = #{record.showCalendar,jdbcType=TINYINT},
show_project_id = #{record.showProjectId,jdbcType=BIGINT},
caption = #{record.caption,jdbcType=VARCHAR},
@ -281,6 +292,9 @@
<if test="systemName != null">
system_name = #{systemName,jdbcType=VARCHAR},
</if>
<if test="backdropUrl != null">
backdrop_url = #{backdropUrl,jdbcType=VARCHAR},
</if>
<if test="showCalendar != null">
show_calendar = #{showCalendar,jdbcType=TINYINT},
</if>
@ -311,6 +325,7 @@
logo = #{logo,jdbcType=VARCHAR},
company_name = #{companyName,jdbcType=VARCHAR},
system_name = #{systemName,jdbcType=VARCHAR},
backdrop_url = #{backdropUrl,jdbcType=VARCHAR},
show_calendar = #{showCalendar,jdbcType=TINYINT},
show_project_id = #{showProjectId,jdbcType=BIGINT},
caption = #{caption,jdbcType=VARCHAR},

370
tall/src/main/resources/mapper_raw/SysWxMapper.xml

@ -0,0 +1,370 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ccsens.tall.persist.mapper.SysWxMapper">
<resultMap id="BaseResultMap" type="com.ccsens.tall.bean.po.SysWx">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="user_id" jdbcType="BIGINT" property="userId" />
<result column="open_id" jdbcType="VARCHAR" property="openId" />
<result column="union_id" jdbcType="VARCHAR" property="unionId" />
<result column="nickname" jdbcType="VARCHAR" property="nickname" />
<result column="head_img_url" jdbcType="VARCHAR" property="headImgUrl" />
<result column="sex" jdbcType="TINYINT" property="sex" />
<result column="province" jdbcType="VARCHAR" property="province" />
<result column="city" jdbcType="VARCHAR" property="city" />
<result column="country" jdbcType="VARCHAR" property="country" />
<result column="language" jdbcType="VARCHAR" property="language" />
<result column="privilege" jdbcType="VARCHAR" property="privilege" />
<result column="created_at" jdbcType="TIMESTAMP" property="createdAt" />
<result column="updated_at" jdbcType="TIMESTAMP" property="updatedAt" />
<result column="rec_status" jdbcType="TINYINT" property="recStatus" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
id, user_id, open_id, union_id, nickname, head_img_url, sex, province, city, country,
language, privilege, created_at, updated_at, rec_status
</sql>
<select id="selectByExample" parameterType="com.ccsens.tall.bean.po.SysWxExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from t_sys_wx
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_sys_wx
where id = #{id,jdbcType=BIGINT}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_sys_wx
where id = #{id,jdbcType=BIGINT}
</delete>
<delete id="deleteByExample" parameterType="com.ccsens.tall.bean.po.SysWxExample">
delete from t_sys_wx
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.ccsens.tall.bean.po.SysWx">
insert into t_sys_wx (id, user_id, open_id,
union_id, nickname, head_img_url,
sex, province, city,
country, language, privilege,
created_at, updated_at, rec_status
)
values (#{id,jdbcType=BIGINT}, #{userId,jdbcType=BIGINT}, #{openId,jdbcType=VARCHAR},
#{unionId,jdbcType=VARCHAR}, #{nickname,jdbcType=VARCHAR}, #{headImgUrl,jdbcType=VARCHAR},
#{sex,jdbcType=TINYINT}, #{province,jdbcType=VARCHAR}, #{city,jdbcType=VARCHAR},
#{country,jdbcType=VARCHAR}, #{language,jdbcType=VARCHAR}, #{privilege,jdbcType=VARCHAR},
#{createdAt,jdbcType=TIMESTAMP}, #{updatedAt,jdbcType=TIMESTAMP}, #{recStatus,jdbcType=TINYINT}
)
</insert>
<insert id="insertSelective" parameterType="com.ccsens.tall.bean.po.SysWx">
insert into t_sys_wx
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userId != null">
user_id,
</if>
<if test="openId != null">
open_id,
</if>
<if test="unionId != null">
union_id,
</if>
<if test="nickname != null">
nickname,
</if>
<if test="headImgUrl != null">
head_img_url,
</if>
<if test="sex != null">
sex,
</if>
<if test="province != null">
province,
</if>
<if test="city != null">
city,
</if>
<if test="country != null">
country,
</if>
<if test="language != null">
language,
</if>
<if test="privilege != null">
privilege,
</if>
<if test="createdAt != null">
created_at,
</if>
<if test="updatedAt != null">
updated_at,
</if>
<if test="recStatus != null">
rec_status,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=BIGINT},
</if>
<if test="userId != null">
#{userId,jdbcType=BIGINT},
</if>
<if test="openId != null">
#{openId,jdbcType=VARCHAR},
</if>
<if test="unionId != null">
#{unionId,jdbcType=VARCHAR},
</if>
<if test="nickname != null">
#{nickname,jdbcType=VARCHAR},
</if>
<if test="headImgUrl != null">
#{headImgUrl,jdbcType=VARCHAR},
</if>
<if test="sex != null">
#{sex,jdbcType=TINYINT},
</if>
<if test="province != null">
#{province,jdbcType=VARCHAR},
</if>
<if test="city != null">
#{city,jdbcType=VARCHAR},
</if>
<if test="country != null">
#{country,jdbcType=VARCHAR},
</if>
<if test="language != null">
#{language,jdbcType=VARCHAR},
</if>
<if test="privilege != null">
#{privilege,jdbcType=VARCHAR},
</if>
<if test="createdAt != null">
#{createdAt,jdbcType=TIMESTAMP},
</if>
<if test="updatedAt != null">
#{updatedAt,jdbcType=TIMESTAMP},
</if>
<if test="recStatus != null">
#{recStatus,jdbcType=TINYINT},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.ccsens.tall.bean.po.SysWxExample" resultType="java.lang.Long">
select count(*) from t_sys_wx
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update t_sys_wx
<set>
<if test="record.id != null">
id = #{record.id,jdbcType=BIGINT},
</if>
<if test="record.userId != null">
user_id = #{record.userId,jdbcType=BIGINT},
</if>
<if test="record.openId != null">
open_id = #{record.openId,jdbcType=VARCHAR},
</if>
<if test="record.unionId != null">
union_id = #{record.unionId,jdbcType=VARCHAR},
</if>
<if test="record.nickname != null">
nickname = #{record.nickname,jdbcType=VARCHAR},
</if>
<if test="record.headImgUrl != null">
head_img_url = #{record.headImgUrl,jdbcType=VARCHAR},
</if>
<if test="record.sex != null">
sex = #{record.sex,jdbcType=TINYINT},
</if>
<if test="record.province != null">
province = #{record.province,jdbcType=VARCHAR},
</if>
<if test="record.city != null">
city = #{record.city,jdbcType=VARCHAR},
</if>
<if test="record.country != null">
country = #{record.country,jdbcType=VARCHAR},
</if>
<if test="record.language != null">
language = #{record.language,jdbcType=VARCHAR},
</if>
<if test="record.privilege != null">
privilege = #{record.privilege,jdbcType=VARCHAR},
</if>
<if test="record.createdAt != null">
created_at = #{record.createdAt,jdbcType=TIMESTAMP},
</if>
<if test="record.updatedAt != null">
updated_at = #{record.updatedAt,jdbcType=TIMESTAMP},
</if>
<if test="record.recStatus != null">
rec_status = #{record.recStatus,jdbcType=TINYINT},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update t_sys_wx
set id = #{record.id,jdbcType=BIGINT},
user_id = #{record.userId,jdbcType=BIGINT},
open_id = #{record.openId,jdbcType=VARCHAR},
union_id = #{record.unionId,jdbcType=VARCHAR},
nickname = #{record.nickname,jdbcType=VARCHAR},
head_img_url = #{record.headImgUrl,jdbcType=VARCHAR},
sex = #{record.sex,jdbcType=TINYINT},
province = #{record.province,jdbcType=VARCHAR},
city = #{record.city,jdbcType=VARCHAR},
country = #{record.country,jdbcType=VARCHAR},
language = #{record.language,jdbcType=VARCHAR},
privilege = #{record.privilege,jdbcType=VARCHAR},
created_at = #{record.createdAt,jdbcType=TIMESTAMP},
updated_at = #{record.updatedAt,jdbcType=TIMESTAMP},
rec_status = #{record.recStatus,jdbcType=TINYINT}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.ccsens.tall.bean.po.SysWx">
update t_sys_wx
<set>
<if test="userId != null">
user_id = #{userId,jdbcType=BIGINT},
</if>
<if test="openId != null">
open_id = #{openId,jdbcType=VARCHAR},
</if>
<if test="unionId != null">
union_id = #{unionId,jdbcType=VARCHAR},
</if>
<if test="nickname != null">
nickname = #{nickname,jdbcType=VARCHAR},
</if>
<if test="headImgUrl != null">
head_img_url = #{headImgUrl,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=TINYINT},
</if>
<if test="province != null">
province = #{province,jdbcType=VARCHAR},
</if>
<if test="city != null">
city = #{city,jdbcType=VARCHAR},
</if>
<if test="country != null">
country = #{country,jdbcType=VARCHAR},
</if>
<if test="language != null">
language = #{language,jdbcType=VARCHAR},
</if>
<if test="privilege != null">
privilege = #{privilege,jdbcType=VARCHAR},
</if>
<if test="createdAt != null">
created_at = #{createdAt,jdbcType=TIMESTAMP},
</if>
<if test="updatedAt != null">
updated_at = #{updatedAt,jdbcType=TIMESTAMP},
</if>
<if test="recStatus != null">
rec_status = #{recStatus,jdbcType=TINYINT},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.ccsens.tall.bean.po.SysWx">
update t_sys_wx
set user_id = #{userId,jdbcType=BIGINT},
open_id = #{openId,jdbcType=VARCHAR},
union_id = #{unionId,jdbcType=VARCHAR},
nickname = #{nickname,jdbcType=VARCHAR},
head_img_url = #{headImgUrl,jdbcType=VARCHAR},
sex = #{sex,jdbcType=TINYINT},
province = #{province,jdbcType=VARCHAR},
city = #{city,jdbcType=VARCHAR},
country = #{country,jdbcType=VARCHAR},
language = #{language,jdbcType=VARCHAR},
privilege = #{privilege,jdbcType=VARCHAR},
created_at = #{createdAt,jdbcType=TIMESTAMP},
updated_at = #{updatedAt,jdbcType=TIMESTAMP},
rec_status = #{recStatus,jdbcType=TINYINT}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>

6
util/src/main/java/com/ccsens/util/CodeEnum.java

@ -57,7 +57,6 @@ public enum CodeEnum {
NOT_POWER(45,"对不起,您的权限不足,无法进行此操作",true),
SMS_CODE_CORRECT(46,"验证信息错误",true),
QUESTION_RULE_NOT_FOUND(47,"该评测规则未知,请联系开发人员。", true),
REPORT_DOCTOR_ERROR(48, "对不起,您没有修改报告单结果的权限。", true),
NOT_LOGIN(49, "对不起,您尚未登录或登录已失效,请重新登录。", true),
@ -84,7 +83,10 @@ public enum CodeEnum {
GAME_PENDING(66, "游戏尚未开始,请等待主持人开始", true),
GAME_PREPARATION(67, "游戏已经开始倒计时了", true),
GAME_PROCESSING (68, "游戏已经在火热进行啦", true),
GAME_COMPLETED(69, "抱歉,您来晚了,游戏已结束", true)
GAME_COMPLETED(69, "抱歉,您来晚了,游戏已结束", true),
NOT_REGISTER(70,"该手机号尚未注册账号,请填写用户名与密码进行注册同时绑定微信",true),
PHONE_ERR(71,"请输入正确的手机号",true),
NOT_SELECT_WX(72,"未查到对应的微信信息",true)
;
public CodeEnum addMsg(String msg){

11
util/src/main/java/com/ccsens/util/WebConstant.java

@ -133,7 +133,8 @@ public class WebConstant {
}
public enum CLIENT_TYPE {
Wxmp(0,"微信小程序"), H5(1,"Web H5"),Android(2,"Android App"),IOS(3,"IOS App");
Wxmp(0,"微信小程序"), H5(1,"网页"),Android(2
,"安卓客户端"),IOS(3,"苹果客户端");
public int value;
public String phase;
@ -154,7 +155,10 @@ public class WebConstant {
}
public enum IDENTIFY_TYPE {
Wxmp(0,"微信小程序"), Phone(1,"电话"), Email(2,"Email"), Account(3,"账号"),OAUTH2_Wx(4,"微信"),OAUTH2_WeiBo(5,"微博");
Wxmp(0,"微信小程序"), Phone(1,"电话")
, Email(2,"Email"), Account(3,"账号")
,OAUTH2_Wx(4,"微信公众号"),Wx_H5(5,"网页微信登陆")
,OAUTH2_WeiBo(6,"微博");
public int value;
public String phase;
@ -170,7 +174,8 @@ public class WebConstant {
case 2: return Email;
case 3: return Account;
case 4: return OAUTH2_Wx;
case 5: return OAUTH2_WeiBo;
case 5: return Wx_H5;
case 6: return OAUTH2_WeiBo;
default: return null;
}
}

151
util/src/main/java/com/ccsens/util/bean/wx/dto/WxGzhAction.java

@ -0,0 +1,151 @@
package com.ccsens.util.bean.wx.dto;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.Data;
import java.util.List;
/**
* @author __zHangSan
*/
@Data
@JacksonXmlRootElement(localName = "xml")
public class WxGzhAction {
@Data
private static class ScanCodeInfo{
@JacksonXmlProperty(localName = "ScanType")
private String scanType;
@JacksonXmlProperty(localName = "ScanResult")
private String scanResult;
};
@Data
private static class SendPicsInfo{
@Data
private static class Item{
@JacksonXmlProperty(localName = "PicMd5Sum")
private String picMd5Sum;
}
@JacksonXmlProperty(localName = "Count")
private Integer count;
@JacksonXmlProperty(localName = "PicList")
private List<Item> picList;
}
@Data
private static class SendLocationInfo{
@JacksonXmlProperty(localName = "Location_X")
private String x;
@JacksonXmlProperty(localName = "Location_Y")
private String y;
@JacksonXmlProperty(localName = "Scale")
private String scale;
@JacksonXmlProperty(localName = "Label")
private String label;
@JacksonXmlProperty(localName = "Poiname")
private String poiname;
}
@JacksonXmlProperty(localName = "FromUserName")
private String openId;
@JacksonXmlProperty(localName = "ToUserName")
private String gzhId;
@JacksonXmlProperty(localName = "CreateTime")
private Long createTime;
@JacksonXmlProperty(localName = "MsgType")
private String msgType;
/**
* MsgType: Text (Content,MsgId)
*/
@JacksonXmlProperty(localName = "Content")
private String content;
@JacksonXmlProperty(localName = "MsgId")
private String msgId;
/**
* MsgType: image (PicUrl,MediaId,MsgId)
*/
@JacksonXmlProperty(localName = "PicUrl")
private String picUrl;
@JacksonXmlProperty(localName = "MediaId")
private String mediaId;
/**
* MsgType: voice (MediaId,Format,MsgId)
* Recognition: 开通语音识别后生效
*/
@JacksonXmlProperty(localName = "Format")
private String format;
@JacksonXmlProperty(localName = "Recognition")
private String recognition;
/**
* MsgType: video/shortvideo(MediaId,ThumbMediaId,MsgId)
*/
@JacksonXmlProperty(localName = "ThumbMediaId")
private String thumbMediaId;
/**
* MsgType: location(Location_x,Location_y,Scale,Label,MsgId)
*/
@JacksonXmlProperty(localName = "Location_X")
private String x;
@JacksonXmlProperty(localName = "Location_Y")
private String y;
@JacksonXmlProperty(localName = "Scale")
private String scale;
@JacksonXmlProperty(localName = "Label")
private String label;
/**
* MsgType: link(Title,Description,Url,MsgId)
*/
@JacksonXmlProperty(localName = "Title")
private String title;
@JacksonXmlProperty(localName = "Description")
private String description;
@JacksonXmlProperty(localName = "Url")
private String url;
/**
* MsgType: event
*/
@JacksonXmlProperty(localName = "Event")
private String event;
@JacksonXmlProperty(localName = "EventKey")
private String eventKey;
/**
* Event: subscribe/SCAN
*/
@JacksonXmlProperty(localName = "Ticket")
private String ticket;
/**
* Event: Location
*/
@JacksonXmlProperty(localName = "Latitude")
private String latitude;
@JacksonXmlProperty(localName = "Longitude")
private String longitude;
@JacksonXmlProperty(localName = "Precision")
private String precision;
/**
* Event: VIEW/view_miniprogram
*/
@JacksonXmlProperty(localName = "MenuId")
private String menuId;
/**
* Event: scancode_push/scancode_waitmsg
*/
@JacksonXmlProperty(localName = "ScanCodeInfo")
private ScanCodeInfo scanCodeInfo;
/**
* Event: pic_sysphoto/pic_photo_or_album/pic_weixin
*/
@JacksonXmlProperty(localName = "SendPicsInfo")
private SendPicsInfo sendPicsInfo;
/**
* Event: location_select
*/
@JacksonXmlProperty(localName = "SendLocationInfo")
private SendLocationInfo sendLocationInfo;
}

18
util/src/main/java/com/ccsens/util/bean/wx/po/WxAccessToken.java

@ -0,0 +1,18 @@
package com.ccsens.util.bean.wx.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxAccessToken extends WxBaseEntity{
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private Long expiresIn;
@JsonIgnore
private Long createdAt;
}

12
util/src/main/java/com/ccsens/util/bean/wx/po/WxBaseEntity.java

@ -0,0 +1,12 @@
package com.ccsens.util.bean.wx.po;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxBaseEntity {
private Integer errcode;
private String errmsg;
}

23
util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhAuthType.java

@ -0,0 +1,23 @@
package com.ccsens.util.bean.wx.po;
import lombok.Getter;
import lombok.Setter;
/**
* @author __zHangSan
*/
public enum WxGzhAuthType {
//基本授权类型,静默,只能获取openId
SNSAPI_BASE("snsapi_base"),
//信息授权类型,弹出提示框,可以获取openId,unionId,nickanme,city等用户信息
SNSAPI_USERINFO("snsapi_userinfo");
@Getter
@Setter
private String text;
private WxGzhAuthType(String text){
this.text = text;
}
}

97
util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMenu.java

@ -0,0 +1,97 @@
package com.ccsens.util.bean.wx.po;
import cn.hutool.core.collection.CollectionUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import java.util.List;
/**
* @author __zHangSan
*/
@Data
public class WxGzhMenu {
public enum ButtonType{
//点击推事件
CLICK("click"),
//跳转URL
VIEW("view"),
//小程序
MINIPROGRAM("miniprogram"),
//扫码推事件
SCANCODE_PUSH("scancode_push"),
//扫码推事件且弹出“消息接收中”提示框
SCANCODE_WAITMSG("scancode_waitmsg"),
//弹出系统拍照发图
PIC_SYSPHOTO("pic_sysphoto"),
//弹出拍照或者相册发图
PIC_PHOTO_OR_ALBUM("pic_photo_or_album"),
//弹出微信相册发图器
PIC_WEIXIN("pic_weixin"),
//弹出地理位置选择器
LOCATION_SELECT("location_select"),
//下发消息(除文本消息)
MEDIA_ID("media_id"),
//跳转图文消息URL
VIEW_LIMITED("view_limited");
@JsonValue
private String text;
ButtonType(String text){
this.text = text;
}
}
@Builder(toBuilder = true)
@Getter
public static class Button{
/**
* 必须
*/
private ButtonType type;
/**
* 必须
*/
private String name;
/**
* click等点击类型必须
*/
private String key;
/**
* viewminiprogram类型必须
*/
private String url;
/**
* media_id类型和view_limited类型必须
*/
@JsonProperty("media_id")
private String mediaId;
/**
* miniprogram类型必须
*/
private String appid;
private String pagepath;
/**
* optional
*/
@JsonProperty("sub_button")
private List<Button> subButton;
}
@JsonProperty("button")
private List<Button> buttons;
public static WxGzhMenu newInstance(){
return new WxGzhMenu();
}
public WxGzhMenu add(Button button){
if(buttons == null){
buttons = CollectionUtil.newArrayList();
}
buttons.add(button);
return this;
}
}

53
util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMsgEvent.java

@ -0,0 +1,53 @@
package com.ccsens.util.bean.wx.po;
import lombok.Getter;
import lombok.Setter;
/**
* @author __zHangSan
*/
public enum WxGzhMsgEvent {
/**
* 关注/取消关注事件
*/
SUBSCRIBE("subscribe"),UNSUBSCRIBE("unsubscribe"),
/**
* 扫描带参数公众号二维码事件
* 未关注产生Event: SUBSCRIBE EventKey: qrscene_xxx
* 已关注产生Event: Scan EventKey: scene_value
*/
SCAN("SCAN"),
/**
* 上报地理位置事件
*/
LOCATION("LOCATION"),
/**
* 自定义菜单事件
*/
//点击菜单拉取消息时的事件推送
CLICK("CLICK"),
//点击菜单跳转链接时的事件推送
VIEW("VIEW"),
//扫码推事件的事件推送
SCANCODE_PUSH("scancode_push"),
//扫码推事件且弹出“消息接收中”提示框的事件推送
SCANCODE_WAITMSG("scancode_waitmsg"),
//弹出系统拍照发图的事件推送
PIC_SYSPHOTO("pic_sysphoto"),
//弹出拍照或者相册发图的事件推送
PIC_PHOTO_OR_ALBUM("pic_photo_or_album"),
//弹出微信相册发图器的事件推送
PIC_WEIXIN("pic_weixin"),
//弹出地理位置选择器的事件推送
LOCATION_SELECT("location_select"),
//点击菜单跳转小程序的事件推送
VIEW_MINIPROGRAM("view_miniprogram");
@Getter
@Setter
private String text;
private WxGzhMsgEvent(String text){
this.text = text;
}
}

34
util/src/main/java/com/ccsens/util/bean/wx/po/WxGzhMsgType.java

@ -0,0 +1,34 @@
package com.ccsens.util.bean.wx.po;
import lombok.Getter;
import lombok.Setter;
/**
* @author __zHangSan
*/
public enum WxGzhMsgType {
/**
* 1.普通消息
*/
//1.1 文本消息
TEXT("text"),
IMAGE("image"),
VOICE("voice"),
VIDEO("video"),
SHORTVIDEO("shortvideo"),
LOCATION("location"),
LINK("link"),
/**
* 2.事件推送
*/
EVENT("event");
@Getter
@Setter
private String text;
private WxGzhMsgType(String text){
this.text = text;
}
}

26
util/src/main/java/com/ccsens/util/bean/wx/po/WxOauth2AccessToken.java

@ -0,0 +1,26 @@
package com.ccsens.util.bean.wx.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxOauth2AccessToken extends WxBaseEntity{
@JsonProperty("access_token")
private String accessToken;
@JsonProperty("expires_in")
private int expiresIn;
@JsonProperty("refresh_token")
private String refreshToken;
@JsonProperty("openid")
private String openId;
@JsonProperty("scope")
private String scope;
@JsonProperty("unionid")
private String unionId;
@JsonIgnore
private Long createdAt;
}

42
util/src/main/java/com/ccsens/util/bean/wx/po/WxOauth2UserInfo.java

@ -0,0 +1,42 @@
package com.ccsens.util.bean.wx.po;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.util.List;
/**
* @author __zHangSan
*/
@Data
public class WxOauth2UserInfo extends WxBaseEntity{
@JsonProperty("openid")
private String openId;
@JsonProperty("nickname")
private String nickname;
@JsonProperty("sex")
private int sex;
@JsonProperty("province")
private String province;
@JsonProperty("city")
private String city;
@JsonProperty("country")
private String country;
@JsonProperty("headimgurl")
private String headImgUrl;
@JsonProperty("privilege")
private List<String> privilegeList;
@JsonProperty("unionid")
private String unionId;
@JsonProperty("language")
private String language;
}

21
util/src/main/java/com/ccsens/util/bean/wx/po/WxOperation.java

@ -0,0 +1,21 @@
package com.ccsens.util.bean.wx.po;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* @author __zHangSan
*/
public enum WxOperation {
/**
* 创建公众号底部菜单
*/
CREATE_MENU("CreateMenu");
@JsonValue
private String text;
WxOperation(String text){
this.text = text;
}
}

6
util/src/main/java/com/ccsens/util/exception/BaseException.java

@ -7,6 +7,8 @@ import lombok.Getter;
public class BaseException extends RuntimeException {
private Integer code;
private CodeEnum codeEnum;
private String operation;
public BaseException(String message){
super(message);
this.code = -1;
@ -23,4 +25,8 @@ public class BaseException extends RuntimeException {
this.codeEnum = codeEnum;
}
public BaseException(){
}
}

16
util/src/main/java/com/ccsens/util/exception/BusinessException.java

@ -0,0 +1,16 @@
package com.ccsens.util.exception;
/**
* @author __zHangSan
*/
public class BusinessException extends BaseException {
private String type = "BusinessError";
public BusinessException(){
}
public BusinessException(Integer errcode, String errmsg){
super(errcode,errmsg);
}
}

19
util/src/main/java/com/ccsens/util/exception/WxException.java

@ -0,0 +1,19 @@
package com.ccsens.util.exception;
import lombok.Data;
/**
* @author __zHangSan
*/
@Data
public class WxException extends BaseException{
private String type = "WxError";
public WxException(){
}
public WxException(Integer errcode, String errmsg){
super(errcode,errmsg);
}
}

300
util/src/main/java/com/ccsens/util/wx/WxGzhUtil.java

@ -0,0 +1,300 @@
package com.ccsens.util.wx;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import com.ccsens.util.DateUtil;
import com.ccsens.util.JacksonUtil;
import com.ccsens.util.WebConstant;
import com.ccsens.util.bean.wx.po.*;
import com.ccsens.util.exception.BaseException;
import com.ccsens.util.exception.BusinessException;
import com.ccsens.util.exception.WxException;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;
/**
* @author __zHangSan
*/
public class WxGzhUtil {
private static final Logger logger = LoggerFactory.getLogger(WxGzhUtil.class);
/**
* 全局唯一accessToken
*/
private static WxAccessToken globalWxAccessToken;
/**
* accessToken 过期提前10分钟刷新
*/
private static final Integer ACCESS_TOKEN_RESERVED_SECONDS = 10 * 60;
private static final String URL_LOGIN
= "https://api.weixin.qq.com/sns/jscode2session?appid=%1$s&secret=%2$s&js_code=%3$s&grant_type=%4$s";
private static final String URL_GET_ACCESS_TOKEN
= "https://api.weixin.qq.com/cgi-bin/token?grant_type=%1$s&appid=%2$s&secret=%3$s";
private static final String URL_GET_WX_CODE_A
= "https://api.weixin.qq.com/wxa/getwxacode?access_token=%1$s";
private static final String URL_GET_WX_CODE_B
= "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%1$s";
private static final String URL_GET_WX_CODE_C
= "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%1$s";
private static final String URL_PREPARE_PAY
= "https://api.mch.weixin.qq.com/pay/unifiedorder";
private static final String URL_PAY_TO_USR_WX
= "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
private static final String URL_PAY_TO_USR_BANK
= "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
private static final String URL_CREATE_MENU
= " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%1$s";
private static final String URL_QUERY_MENU
= "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=%1$s";
private static final String GZH_AUTH_URL
= "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%1$s&redirect_uri=%2$s&response_type=code&scope=%3$s&state=STATE#wechat_redirect";
private static final String URL_GET_OAUTH2_ACCESS_TOKEN
= "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%1$s&secret=%2$s&code=%3$s&grant_type=authorization_code";
private static final String URL_GET_OAUTH2_USERINFO
= "https://api.weixin.qq.com/sns/userinfo?access_token=%1$s&openid=%2$s";
private static final String APPID = "wx7af1bf1e14facf82";
private static final String SECRET = "a6613fae11b497639c0224b820aaf6d9";
private static final String APPID_H5 = "wxd1842e073e0e6d91";
private static final String SECRET_H5 = "96d69b79039caf92a2abafa999880cad";
private static final String TOKEN = "nNzkL9KkZUOIS8uU";
private static final String ENCODING_AES_KEY = "MQEXG7grhRNsARbUzem6OwnGr2ZW9o5jsauNqaQWOuu";
private static final String MCHID = "";
private static final String KEY = "";
private static String appId(WebConstant.IDENTIFY_TYPE identifyType){
switch (identifyType){
case Wx_H5:
return APPID_H5;
case OAUTH2_Wx:
default:
return APPID;
}
}
private static String secret(WebConstant.IDENTIFY_TYPE identifyType){
switch (identifyType){
case Wx_H5:
return SECRET_H5;
case OAUTH2_Wx:
default:
return SECRET;
}
}
/**
* 数组转字符串
*/
private static String arrayToString(String[] arr) {
StringBuilder bf = new StringBuilder();
for (String s : arr) {
bf.append(s);
}
return bf.toString();
}
/**
* sha1加密
*/
private static String sha1Encode(String sourceString) {
String resultString = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
resultString = byte2hexString(md.digest(sourceString.getBytes()));
} catch (Exception ex) {
ex.printStackTrace();
}
return resultString;
}
/**
* 字节数组转字符串
*/
private static String byte2hexString(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte aByte : bytes) {
if (((int) aByte & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) aByte & 0xff, 16));
}
return buf.toString().toUpperCase();
}
/**
* 公众号接入验证
* @param signature signature
* @param timestamp timestamp
* @param nonce nonce
* @param echostr echostr
* @return true or false
*/
public static boolean checkSignature(String signature,String timestamp,String nonce,String echostr){
if(StrUtil.isEmpty(signature) || StrUtil.isEmpty(timestamp) || StrUtil.isEmpty(nonce) || StrUtil.isEmpty(echostr)){
return false;
}
String[] tmpArr = { TOKEN, timestamp, nonce };
Arrays.sort(tmpArr);
String sign = sha1Encode( arrayToString(tmpArr));
Console.log("sign:{} , signature: {}",sign,signature);
if (sign.equalsIgnoreCase(signature)) {
return true;
}
return false;
}
/**
* 获取Access_token
*/
public static String getAccessToken() throws BaseException {
if(globalWxAccessToken == null ||
globalWxAccessToken.getCreatedAt() + globalWxAccessToken.getExpiresIn()
>= DateUtil.currentSeconds() - ACCESS_TOKEN_RESERVED_SECONDS){
WxAccessToken wxAccessToken = null;
String url = String.format(URL_GET_ACCESS_TOKEN,"client_credential",SECRET);
String response = HttpRequest.get(url).execute().body();
Console.log("getAccessToken: {}",response);
try {
if(StrUtil.isEmpty(response) || null == (wxAccessToken = JacksonUtil.jsonToBean(response, WxAccessToken.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wxAccessToken.getErrcode()){
throw new WxException(wxAccessToken.getErrcode(),wxAccessToken.getErrmsg());
}
if (StrUtil.isEmpty(wxAccessToken.getAccessToken())) {
throw new BusinessException(-1,"can't find the access_token attribute.");
}
globalWxAccessToken = wxAccessToken;
globalWxAccessToken.setCreatedAt(DateUtil.currentSeconds());
}
return globalWxAccessToken.getAccessToken();
}
/**
* 查询微信公众号底部菜单
*/
public static String queryMenu() throws BaseException {
String url = String.format(URL_QUERY_MENU,getAccessToken());
String menuString = HttpRequest.get(url).execute().body();
Console.log("url:{}, menuString: {}",url,menuString);
return menuString;
}
/**
* 创建微信公众号底部菜单
*/
public static void createMenu(WxGzhMenu gzhMenu) throws BaseException {
String url = String.format(URL_CREATE_MENU,getAccessToken());
String menuString = null;
try {
menuString = JacksonUtil.beanToJson(gzhMenu);
Console.log(menuString);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new BusinessException(-1,e.getMessage());
}
String response = HttpRequest.post(url).body(menuString).execute().body();
if(StrUtil.isEmpty(response)){
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
Map<String,Object> map = null;
try {
map = JacksonUtil.jsonToMap(response);
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
Object errcode = map.get("errcode");
if(errcode == null || ((Integer)errcode) != 0) {
throw new WxException((Integer)errcode,(String)map.get("errmsg"));
}
}
public static String getAuthedUrl(String url, WxGzhAuthType wxGzhAuthType){
return String.format(GZH_AUTH_URL,APPID, URLUtil.encode(url),wxGzhAuthType.getText());
}
/**
* 获取网页授权凭证
* @param code OAuth2授权码
* @return WxOauth2AccessToken
*/
public static WxOauth2AccessToken getOauth2AccessToken(WebConstant.IDENTIFY_TYPE identifyType,String code) throws BaseException {
WxOauth2AccessToken wxOauth2AccessToken = null;
String url = String.format(URL_GET_OAUTH2_ACCESS_TOKEN,appId(identifyType),secret(identifyType),code);
String response = HttpRequest.get(url).execute().body();
Console.log("url: {}\nresponse: {}",url,response);
try {
if(StrUtil.isEmpty(response) || null == (wxOauth2AccessToken = JacksonUtil.jsonToBean(response,WxOauth2AccessToken.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wxOauth2AccessToken.getErrcode()){
throw new WxException(wxOauth2AccessToken.getErrcode(),wxOauth2AccessToken.getErrmsg());
}
if (StrUtil.isEmpty(wxOauth2AccessToken.getAccessToken())) {
throw new BusinessException(-1,"can't find the access_token attribute.");
}
wxOauth2AccessToken.setCreatedAt(DateUtil.currentSeconds());
return wxOauth2AccessToken;
}
/**
* 通过网页授权获取用户信息
*
* @param accessToken 网页授权接口调用凭证
* @param openId 用户标识
* @return SNSUserInfo
*/
public static WxOauth2UserInfo getOauth2UserInfo(String accessToken, String openId) throws BaseException {
WxOauth2UserInfo wxOauth2UserInfo = null;
String url = String.format(URL_GET_OAUTH2_USERINFO,accessToken,openId);
String response = HttpRequest.get(url).execute().body();
Console.log("url: {}\nresponse: {}",url,response);
try {
if(StrUtil.isEmpty(response) || null == (wxOauth2UserInfo = JacksonUtil.jsonToBean(response,WxOauth2UserInfo.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wxOauth2UserInfo.getErrcode()){
throw new WxException(wxOauth2UserInfo.getErrcode(),wxOauth2UserInfo.getErrmsg());
}
if (StrUtil.isEmpty(wxOauth2UserInfo.getOpenId())) {
throw new BusinessException(-1,"can't find the openid attribute.");
}
return wxOauth2UserInfo;
}
/**
* 通过网页授权code拉取用户信息封装了getOauth2AccessToken和getOauth2UserInfo(accessToken,openId)
* @param code 网页授权码
* @return WxOauth2UserInfo
* @throws BaseException 异常
*/
public static WxOauth2UserInfo getOauth2UserInfo(WebConstant.IDENTIFY_TYPE identifyType,String code) throws BaseException {
WxOauth2AccessToken wxOauth2AccessToken = getOauth2AccessToken(identifyType,code);
return getOauth2UserInfo(wxOauth2AccessToken.getAccessToken(),wxOauth2AccessToken.getOpenId());
}
}

406
util/src/main/java/com/ccsens/util/wx/WxXcxUtil.java

@ -0,0 +1,406 @@
package com.ccsens.util.wx;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.ccsens.util.HttpsUtil;
import com.ccsens.util.JacksonUtil;
import com.ccsens.util.WebConstant;
import com.ccsens.util.exception.BusinessException;
import com.ccsens.util.exception.WxException;
import lombok.Data;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.util.*;
@Data
class GetUserInfoException extends RuntimeException{
private int code;
public GetUserInfoException(int code,String message){
super(message);
this.code = code;
}
}
@Data
class PayException extends RuntimeException{
private int code;
public PayException(int code,String message){
super(message);
this.code = code;
}
public PayException(String message){
super(message);
this.code = -1;
}
}
/**
* @author __zHangSan
*/
public class WxXcxUtil {
/**
* 被Jasckson使用的内部类 必须是static的
*/
public static class WechatUser {
public String openid;
public String session_key;
public String unionid;
public Integer errcode;
public String errmsg;
}
/**
* Get wx code
*/
public static class WechatCode{
public String scene;
public String page;
public Integer width;
public Boolean auto_color;
public Boolean line_color;
public Boolean is_hyaline;
}
/**
* Prepare pay
*/
public static class PreparePayBean{
public String appid;//小程序ID
public String mch_id;//商户号
public String device_info;//设备号
public String nonce_str;//随机字符串
public String sign;//签名
public String sign_type; //签名类型
public String body;//商品描述
public String detail;//商品详情
public String attach;//附加数据
public String out_trade_no;//商户订单号
public String fee_type;//货币类型
public Integer total_fee; //金额(分)
public String spbill_create_ip;//终端IP
public String time_start;//交易起始时间
public String time_expire;//交易结束时间
public String goods_tag;//商品标记
public String notify_url;//通知地址
public String trade_type;//交易类型
public String product_id;//商品id
public String limit_pay;//指定支付方式
public String openid;//用户标识
}
/**
* Prepare pay result
*/
public static class PreparePayResultBean{
public String return_code;
public String return_msg;
public String result_code;
public String prepay_id;
public String err_code;
public String err_code_des;
}
/**
* Prepare pay resign
*/
public static class PreparePayReSignBean{
public String nonceStr;
public String _package;
public long timeStamp;
public String paySign;
public String signType;
}
private static final String URL_LOGIN
= "https://api.weixin.qq.com/sns/jscode2session?appid=%1$s&secret=%2$s&js_code=%3$s&grant_type=%4$s";
private static final String URL_GET_ACCESS_TOKEN
= "https://api.weixin.qq.com/cgi-bin/token?grant_type=%1$s&appid=%2$s&secret=%3$s";
private static final String URL_GET_WX_CODE_A
= "https://api.weixin.qq.com/wxa/getwxacode?access_token=%1$s";
private static final String URL_GET_WX_CODE_B
= "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%1$s";
private static final String URL_GET_WX_CODE_C
= "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=%1$s";
private static final String URL_PREPARE_PAY
= "https://api.mch.weixin.qq.com/pay/unifiedorder";
private static final String URL_PAY_TO_USR_WX
= "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
private static final String URL_PAY_TO_USR_BANK
= "https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank";
private static final String URL_CREATE_MENU
= " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%1$s";
private static final String appid = "wx7af1bf1e14facf82";
private static final String secret = "a6613fae11b497639c0224b820aaf6d9";
private static final String mchid = "";
private static final String key = "";
/**
* 小程序登陆根据code获取用户信息(openid,sessionKey,)
* @param code
* @return
* @throws ConnectException
* @throws Exception
*/
public static WechatUser getUserInfo(String code) throws Exception {
WechatUser wechatUser = null;
String url = String.format(URL_LOGIN, appid, secret, code, "authorization_code");
String response = HttpRequest.get(url).execute().body();
try {
if(StrUtil.isEmpty(response) || null == (wechatUser = JacksonUtil.jsonToBean(response, WechatUser.class))) {
throw new BusinessException(-1,"the response of HttpRequest is empty.");
}
} catch (IOException e) {
throw new BusinessException(-1,e.getMessage());
}
if(null != wechatUser.errcode){
throw new WxException(wechatUser.errcode, wechatUser.errmsg);
}
return wechatUser;
}
/**
* 获取小程序二维码/小程序码
* @return
* @throws Exception
*/
public static void getWxCode(String page,String scene,String path) throws Exception {
String url = String.format(URL_GET_WX_CODE_B, WxGzhUtil.getAccessToken());
WechatCode wechatCode = new WechatCode();
wechatCode.page = page;
wechatCode.scene = scene;
String postStr = JacksonUtil.beanToJson(wechatCode);
System.out.println(postStr);
HttpsUtil.httpsRequest(url,"POST",postStr,path);
}
/**
* 统一下单
*/
public static PreparePayReSignBean preparePay(String openid,String out_trade_no,String body,int total_fee,String spbill_create_ip,
String notify_url) throws Exception {
PreparePayBean preparePayBean = new PreparePayBean();
preparePayBean.appid = appid;
preparePayBean.mch_id = mchid;
preparePayBean.openid = openid;
preparePayBean.total_fee = total_fee;
preparePayBean.out_trade_no = out_trade_no;
//以utf-8编码放入paymentPo,微信支付要求字符编码统一采用UTF-8字符编码
preparePayBean.body = new String(body.getBytes("ISO-8859-1"),"UTF-8");
//preparePayBean.body = new String("小程序-充值");
preparePayBean.spbill_create_ip = spbill_create_ip;
preparePayBean.notify_url = notify_url;
preparePayBean.trade_type = "JSAPI";
preparePayBean.nonce_str = createNonceStr();
// 把请求参数打包成数组
Map<String,Object> sParaTemp = new HashMap();
sParaTemp.put("appid", preparePayBean.appid);
sParaTemp.put("mch_id", preparePayBean.mch_id);
sParaTemp.put("openid", preparePayBean.openid);
sParaTemp.put("total_fee",preparePayBean.total_fee + "");
sParaTemp.put("out_trade_no", preparePayBean.out_trade_no);
sParaTemp.put("body", preparePayBean.body);
sParaTemp.put("spbill_create_ip", preparePayBean.spbill_create_ip);
sParaTemp.put("notify_url",preparePayBean.notify_url);
sParaTemp.put("trade_type", preparePayBean.trade_type);
sParaTemp.put("nonce_str", preparePayBean.nonce_str);
preparePayBean.sign = createSign(sParaTemp);
String reqrXml = JacksonUtil.beanToXml(preparePayBean,"xml");
String respXml = HttpsUtil.httpsRequest(URL_PREPARE_PAY,"POST",reqrXml);
System.out.println("---------------PreparePay Request Xml-----------------");
System.out.println(reqrXml);
System.out.println("---------------PreparePay Response Xml-----------------");
System.out.println(respXml);
System.out.println("---------------PreparePay end-----------------");
PreparePayResultBean resultBean = null;
PreparePayReSignBean reSignBean = new PreparePayReSignBean();
resultBean = JacksonUtil.xmlToBean(new ByteArrayInputStream(respXml.getBytes()),PreparePayResultBean.class);
if(ObjectUtil.isNull(resultBean)) {
throw new PayException("PreparePay 返回的resultBean为空");
}
if(!StrUtil.isEmpty(resultBean.return_code)
&& !StrUtil.isEmpty(resultBean.result_code)){
if(resultBean.result_code.equals("SUCCESS") && resultBean.return_code.equals(resultBean.result_code)){
reSignBean.nonceStr = createNonceStr();
reSignBean._package = "prepay_id="+resultBean.prepay_id;
reSignBean.timeStamp = System.currentTimeMillis() / 1000;
reSignBean.signType = "MD5";
// 把请求参数打包成数组
sParaTemp = new HashMap();
sParaTemp.put("appId", appid);
sParaTemp.put("package", reSignBean._package);
sParaTemp.put("nonceStr", reSignBean.nonceStr);
sParaTemp.put("signType", reSignBean.signType);
sParaTemp.put("timeStamp",reSignBean.timeStamp + "");
reSignBean.paySign = createSign(sParaTemp);
return reSignBean;
}else{
throw new PayException("[" + resultBean.err_code + "]"
+ resultBean.err_code_des);
}
}else {
throw new PayException(resultBean.return_msg);
}
}
/**
* Create Sign
* @param sParaTemp
* @return
*/
public static String createSign(Map<String,Object> sParaTemp){
// 除去数组中的空值和签名参数
Map sPara = paraFilter(sParaTemp);
// 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
String prestr = createLinkString(sPara);
//MD5运算生成签名
String sign = sign(prestr, key, "utf-8").toUpperCase();
return sign;
}
/**
* 除去数组中的空值和签名参数
* @param sArray 签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
private static Map paraFilter(Map<String,Object> sArray) {
Map result = new HashMap();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = "" + sArray.get(key);
if (StrUtil.isEmpty(value) || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把数组所有元素排序并按照参数=参数值的模式用&字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
private static String createLinkString(Map<String,String> params) {
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
StringBuilder prestr = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {
prestr.append(key).append("=").append(value);
} else {
prestr.append(key).append("=").append(value).append("&");
}
}
return prestr.toString();
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
private static String sign(String text, String key, String input_charset) {
text = text + "&key=" + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* getContentBytes
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
private static String createNonceStr(){
return UUID.randomUUID().toString().replace("-","");
}
public static Map<String,Object> payToUsrWx(
String partner_trade_no,String openid,int total_fee,String desc,String spbill_create_ip)
throws Exception{
final String SUCCESS = "SUCCESS";
//1.构造请求字符串
Map<String,Object> reqMap = new HashMap<>();
reqMap.put("mch_appid",appid);
reqMap.put("mchid",mchid);
//reqMap.put("device_info",null); //不能添加空字段,Jackson会生成闭包xml <device_info/>导致签名失败
reqMap.put("nonce_str",createNonceStr());
reqMap.put("partner_trade_no",partner_trade_no);
reqMap.put("openid",openid);
reqMap.put("check_name","NO_CHECK");
//reqMap.put("re_user_name",null);
reqMap.put("amount",total_fee + "");
reqMap.put("desc",desc);
reqMap.put("spbill_create_ip",spbill_create_ip);
reqMap.put("sign",createSign(reqMap));
//2.发送付款请求
String reqrXml = JacksonUtil.mapToXml(reqMap,"xml");
String respXml = HttpsUtil.httpsRequest(URL_PAY_TO_USR_WX,"POST",reqrXml,
WebConstant.PATH_WX_CRET,mchid);
System.out.println("---------------PayToUsrWx Request Xml-----------------");
System.out.println(reqrXml);
System.out.println("---------------PayToUsrWx Response Xml-----------------");
System.out.println(respXml);
System.out.println("---------------PayToUsrWx end-----------------");
//3.判断成功失败
Map<String,Object> respMap = JacksonUtil.xmlToMap(new ByteArrayInputStream(respXml.getBytes()));
String return_code,result_code;
return_code = (String)respMap.get("return_code");
result_code = (String)respMap.get("result_code");
if(!StrUtil.isEmpty(return_code) && !StrUtil.isEmpty(result_code)){
if(return_code.equals(SUCCESS) && return_code.equals(result_code)){
return respMap;
}else{
throw new PayException("[" + respMap.get("err_code") + "]"
+ respMap.get("err_code_des"));
}
}else {
throw new PayException((String) respMap.get("return_msg"));
}
//return null;
}
public static Map<String,String> payToUsrBank(){
//Fix Me
return null;
}
}
Loading…
Cancel
Save