Commit 13522d43 by yao.xiao

整合-阿里,微信,缓存等

parent 661008eb
...@@ -121,6 +121,14 @@ ...@@ -121,6 +121,14 @@
<version>2.8.2</version> <version>2.8.2</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -12,11 +12,14 @@ import com.yd.dal.entity.customer.AclCustomerLog; ...@@ -12,11 +12,14 @@ import com.yd.dal.entity.customer.AclCustomerLog;
import com.yd.dal.entity.customer.AclFileUpload; import com.yd.dal.entity.customer.AclFileUpload;
import com.yd.dal.entity.customer.CustomerFileUpload; import com.yd.dal.entity.customer.CustomerFileUpload;
import com.yd.dal.entity.practitioner.*; import com.yd.dal.entity.practitioner.*;
import com.yd.dal.entity.tencent.TenInterfRecord;
import com.yd.dal.service.customer.AclCustomerLogDALService; import com.yd.dal.service.customer.AclCustomerLogDALService;
import com.yd.dal.service.customer.AclFileUploadDALService; import com.yd.dal.service.customer.AclFileUploadDALService;
import com.yd.dal.service.meta.MdCodeDALService; import com.yd.dal.service.meta.MdCodeDALService;
import com.yd.dal.service.practitioner.PractitionerDALService; import com.yd.dal.service.practitioner.PractitionerDALService;
import com.yd.dal.service.practitioner.PractitionerSubordinateDALService; import com.yd.dal.service.practitioner.PractitionerSubordinateDALService;
import com.yd.dal.service.tencent.TenInterfRecordDALService;
import com.yd.dal.service.transaction.TranLogDALService;
import com.yd.rmi.ali.oss.service.OssService; import com.yd.rmi.ali.oss.service.OssService;
import com.yd.util.CommonUtil; import com.yd.util.CommonUtil;
import com.yd.util.HttpUtil; import com.yd.util.HttpUtil;
......
package com.yd.cache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
public class SystemCacheManager {
public static final CacheManager manager = CacheManager.create();
public SystemCacheManager() {
}
public static Cache getCache(String cacheName) {
if (!manager.cacheExists(cacheName)) {
manager.addCache(cacheName);
}
return manager.getCache(cacheName);
}
}
package com.yd.cache;
import com.yd.dal.entity.meta.MdCode;
import com.yd.dal.service.meta.MdCodeDALService;
import com.yd.rmi.ali.ossinterf.service.AliOssInterfService;
import com.yd.util.CommonUtil;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import java.util.*;
@Service("systemConfigService")
@org.springframework.core.annotation.Order(1)
public class SystemConfigService implements CommandLineRunner{
private static Cache systemConfigCache = SystemCacheManager.getCache("systemConfigCache");
@Autowired
private MdCodeDALService mdCodeService;
@Autowired
private AliOssInterfService aliOssInterfService;
/**
* 保存cache
* @param cacheKey
* @param cacheValue
*/
public void setCache(String cacheKey,String cacheValue){
if(!"".equals(cacheKey) && cacheKey != null){
//先清除原有的数据
Element element = systemConfigCache.get(cacheKey);
if(element != null && element.getObjectValue() != null){
systemConfigCache.remove(cacheKey);
}
//保存新的数据
element = new Element(cacheKey,cacheValue);
systemConfigCache.put(element);
}
}
/**
* 获取cache
* @param cacheKey
*/
public String getCache(String cacheKey){
if(!"".equals(cacheKey) && cacheKey != null){
//先清除原有的数据
Element element = systemConfigCache.get(cacheKey);
if(element != null && element.getObjectValue() != null){
return (String)element.getObjectValue();
}
}
return null;
}
/**
* 删除cache
* @param cacheKey
*/
public void deleteCache(String cacheKey){
if(!"".equals(cacheKey) && cacheKey != null){
//先清除原有的数据
Element element = systemConfigCache.get(cacheKey);
if(element != null && element.getObjectValue() != null){
systemConfigCache.remove(cacheKey);
}
}
}
/**
* 根据配置类型去获取相应配置
* @param configType
* @return
*/
public String getSingleConfigValue(String configType){
return getSingleConfigValue(configType,null);
}
/**
* 根据配置类型去获取相应配置
* @param configType 配置类型
* @param codeNameEn 配置具体类型的名称
* @return
*/
public String getSingleConfigValue(String configType,String codeNameEn){
String configValue = null;
Element element = systemConfigCache.get(configType+codeNameEn);
if(element != null && element.getObjectValue() != null){
configValue = (String)element.getObjectValue();
}else{
MdCode mdCode = new MdCode();
mdCode.setCodeType(configType);
mdCode.setIsActive(1);
if(!CommonUtil.isNullOrBlank(codeNameEn)){
mdCode.setCodeNameEn(codeNameEn);
}
// System.out.println("------------------------------查询"+configType+"并放入缓存");
List<MdCode> mdCodeList = mdCodeService.findByMdCode(mdCode);
if(mdCodeList != null && mdCodeList.size()>0){
mdCode = mdCodeList.get(0);
configValue = mdCode.getCodeCode();
element = new Element(configType+codeNameEn,configValue);
systemConfigCache.put(element);
}
}
return configValue;
}
/**
* 慎用!以免出现和keyValueMap中的key冲突,导致转换异常。
* 建议使用getKeyValueMap来替代此方法
* @param configType
* @return
*/
@SuppressWarnings("unchecked")
public List<String> getListConfigValue(String configType){
List<String> configValues = null;
Element element = systemConfigCache.get(configType);
if(element != null && element.getObjectValue() != null){
configValues = (List<String>)element.getObjectValue();
}else{
MdCode mdCode = new MdCode();
mdCode.setCodeType(configType);
mdCode.setIsActive(1);
List<MdCode> mdCodeList = mdCodeService.findByMdCode(mdCode);
if(mdCodeList != null && mdCodeList.size()>0){
configValues = new ArrayList<String>();
for(MdCode md : mdCodeList){
configValues.add(md.getCodeCode());
}
element = new Element(configType,configValues);
systemConfigCache.put(element);
}
}
return configValues;
}
public void clearConfig(String configType){
// getKeyValueMap(configType);
Element element = systemConfigCache.get(configType);
// System.out.println("------------------------------清除"+configType+"缓存前获取的值"+element);
if(element != null && element.getObjectValue() != null){
systemConfigCache.remove(configType);
System.out.println("------------------------------清除"+configType+"缓存");
}
element = systemConfigCache.get(configType);
// System.out.println("------------------------------清除"+configType+"缓存后获取的值"+element);
}
public boolean mobileInfoProduct(Long productId,String configType){
if(productId != null){
MdCode mdCode = new MdCode();
mdCode.setCodeType(configType);
mdCode.setIsActive(1);
List<MdCode> mdCodeList = mdCodeService.findByMdCode(mdCode);
if(!mdCodeList.isEmpty()){
mdCode = mdCodeList.get(0);
String productIdStr = mdCode.getCodeCode();
String[] productIdS = productIdStr.split(",");
List<String> productIdList = Arrays.asList(productIdS);
if(!productIdList.isEmpty() && productIdList.contains(productId.toString())){
return true;
}
}
}
return false;
}
/**
* 试算因子对应保费
* @param elements 试算因子
* @param result 对应价格,无planId拼装数据
* @return
*/
public String getElementsForPrice(String elements,String result){
//当传入price时,存入缓存 当没有传price时,做查询
if (!CommonUtil.isNullOrBlank(result)) {
Element element = new Element(elements,result);
systemConfigCache.put(element);
}else{
Element element = systemConfigCache.get(elements);
if(element != null && element.getObjectValue() != null){
result = (String)element.getObjectValue();
}
}
return result;
}
@Override
public void run(String... arg0) throws Exception {
// SystemConstants.ALI_OSS_ENDPOINT = getSingleConfigValue("ALI_OSS_ENDPOINT");
// SystemConstants.ALI_OSS_ACCESS_KEY_ID = getSingleConfigValue("ALI_OSS_ACCESS_KEY_ID");
// SystemConstants.ALI_OSS_ACCESS_KEY_SECRET = getSingleConfigValue("ALI_OSS_ACCESS_KEY_SECRET");
// SystemConstants.ALI_OSS_BUCKET_NAME = getSingleConfigValue("ALI_OSS_BUCKET_NAME");
SystemConstants.COMMON_CONNECTION_TIMEOUT = Integer.parseInt(getSingleConfigValue("COMMON_CONNECTION_TIMEOUT"));
SystemConstants.COMMON_SO_TIMEOUT = Integer.parseInt(getSingleConfigValue("COMMON_SO_TIMEOUT"));
aliOssInterfService.initAttribute();
}
}
package com.yd.cache;
import com.yd.util.CommonUtil;
import java.util.Date;
public class SystemConstants {
// @Autowired
// private static SystemConfigService systemConfigService;
// public static final String FILE_PATH_PREFIX = "http://www.zuihuibijia.com/";
public static final Integer DEFAULT_PAGINATION_NUMBER = 0;
public static final Integer DEFAULT_PAGINATION_SIZE = 10;
public static final Integer DEFAULT_QUOTE_PLAN_COUNT = 8;
public static Integer COMMON_CONNECTION_TIMEOUT = 10000;
public static Integer COMMON_SO_TIMEOUT = 30000;
public static final Integer OVERSEAS_TRAVEL = 1; //出国旅行
public static final Integer DOMESTIC_TRAVEL = 2; //境内旅行
public static final Integer OVERSEAS_STUDY = 3; //留学旅行
public static final Integer SCHENGEN_TRAVEL = 4; //申根签证
public static final Integer OUTDOOR_SPORT = 5; //户外运动
public static final Integer CRUISE = 6; //邮轮旅行
public static final Integer GENERAL_HEALTH = 7; //综合健康保险
public static final Integer CRITICAL_ILLNESS_INSURANCE = 8; //重大疾病保险
public static final Integer ACCIDENTAL_HEALTH_INSURANCE = 9; //意外健康险
public static final Integer CANCER_PREVENTION_INSURANCE = 10; //防癌保险
public static final Integer HIGH_END_MEDICAL_INSURANCE = 11; //意外健康险
public static final Integer CAR = 12; //意外健康险
public static final Integer HOME_PROPERTY_INSURANCE = 13; //意外健康险
public static final Date DEFAULT_HOLDER_BIRTHDATE = CommonUtil.stringParseDate("1980-01-01","yyyy-MM-dd");//投保人默认生日
// public static final String DEFAULT_BUCKET = systemConfigService.getSingleConfigValue("ALI_OSS_BUCKET_NAME");
}
package com.yd.dal.entity.meta; package com.yd.dal.entity.meta;
import java.util.Date; import lombok.Data;
import java.util.Date;
/**
* ag_md_code
* @author
*/
@Data
public class MdCode { public class MdCode {
private static final long serialVersionUID = 1L;
private Long id; private Long id;
private String codeType; private String codeType;
private Long displayNo;
private String codeCode; private String codeCode;
private String codeName; private String codeName;
private String codeNameEn;
private Integer isActive; private Integer isActive;
private String flag;
private String remark; private String remark;
private Date createAt; private Date createdAt;
private Long createdBy;
public Long getId() { private Date updatedAt;
return id; private Long updatedBy;
}
public void setId(Long id) {
this.id = id;
}
public String getCodeType() {
return codeType;
}
public void setCodeType(String codeType) {
this.codeType = codeType;
}
public String getCodeCode() {
return codeCode;
}
public void setCodeCode(String codeCode) {
this.codeCode = codeCode;
}
public String getCodeName() {
return codeName;
}
public void setCodeName(String codeName) {
this.codeName = codeName;
}
public Integer getIsActive() {
return isActive;
}
public void setIsActive(Integer isActive) {
this.isActive = isActive;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
} }
package com.yd.dal.entity.tencent;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* ag_ten_interf_record
* @author
*/
@Data
public class TenInterfRecord implements Serializable {
/**
* serial id
*/
private Long id;
/**
* 接口类型:TOKEN;ACCESS_TOKEN;JSAPI_TICKET
*/
private String interfType;
/**
* 公众号的唯一标识
*/
private String appid;
/**
* 公众号的appsecret
*/
private String secret;
/**
* authorize接口返回的code
*/
private String code;
/**
* access_token接口时固定为authorization_code
*/
private String grantType;
/**
* access_token接口,服务开发方的appid
*/
private String componentAppid;
/**
* access_token接口,服务开发方的access_token
*/
private String componentAccessToken;
/**
* getticket接口时为wx_card
*/
private String iType;
/**
* access_token接口返回:接口调用凭证
*/
private String accessToken;
/**
* access_token接口返回:接口调用凭证超时时间,单位(秒)
*/
private Long expiresIn;
/**
* access_token接口返回:用户刷新access_token
*/
private String refreshToken;
/**
* access_token接口返回:用户唯一标识
*/
private String openid;
/**
* access_token接口返回:用户授权的作用域,使用逗号(,)分隔
*/
private String iScope;
/**
* getticket接口返回
*/
private String errcode;
/**
* getticket接口返回
*/
private String errmsg;
/**
* getticket接口返回
*/
private String ticket;
/**
* 创建时间
*/
private Date createdAt;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
package com.yd.dal.entity.transaction;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* t_tran_log
* @author
*/
@Data
public class TranLog implements Serializable {
/**
* ID主键
*/
private Long id;
/**
* 日志分类
*/
private String category;
/**
* 类型
*/
private String type;
/**
* 交易号
*/
private String tranNo;
/**
* 请求或响应
*/
private String inOrOut;
/**
* 银盾系统错误代码
*/
private String ydCode;
/**
* 返回代码
*/
private String returnCode;
/**
* 返回信息
*/
private String returnMessage;
/**
* 交互报文
*/
private String tranXml;
/**
* 备注
*/
private String remark;
/**
* 创建日期
*/
private Date createDate;
/**
* 更新日期
*/
private Date updatedDate;
private static final long serialVersionUID = 1L;
}
\ No newline at end of file
...@@ -8,4 +8,6 @@ public interface MdCodeMapper { ...@@ -8,4 +8,6 @@ public interface MdCodeMapper {
List<MdCode> findByCodeType(String codeType); List<MdCode> findByCodeType(String codeType);
String findCodeByType(String codeType); String findCodeByType(String codeType);
List<MdCode> findByMdCode(MdCode mdCode);
} }
package com.yd.dal.mapper.tencent;
import com.yd.dal.entity.tencent.TenInterfRecord;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TenInterfRecordMapper {
int deleteByPrimaryKey(Long id);
int insert(TenInterfRecord record);
int insertSelective(TenInterfRecord record);
TenInterfRecord selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(TenInterfRecord record);
int updateByPrimaryKey(TenInterfRecord record);
List<TenInterfRecord> findByTenInterfRecordOrderBy(@Param("info") TenInterfRecord tencentInterfRecord, @Param("orderBy")String orderBy);
}
\ No newline at end of file
package com.yd.dal.mapper.transaction;
import com.yd.dal.entity.transaction.TranLog;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface TranLogMapper {
int deleteByPrimaryKey(Long id);
int insert(TranLog record);
int insertSelective(TranLog record);
TranLog selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(TranLog record);
int updateByPrimaryKey(TranLog record);
List<TranLog> findByTranLogOrderBy(@Param("info") TranLog tranLogNew, @Param("orderBy") String orderBy);
}
\ No newline at end of file
...@@ -20,4 +20,9 @@ public interface MdCodeDALService { ...@@ -20,4 +20,9 @@ public interface MdCodeDALService {
* @return * @return
*/ */
String findCodeByType(String codeType); String findCodeByType(String codeType);
/**
* 查询mdcode信息
*/
List<MdCode> findByMdCode(MdCode mdCode);
} }
...@@ -30,4 +30,9 @@ public class MdCodeDALServiceImpl implements MdCodeDALService { ...@@ -30,4 +30,9 @@ public class MdCodeDALServiceImpl implements MdCodeDALService {
} }
return null; return null;
} }
@Override
public List<MdCode> findByMdCode(MdCode mdCode) {
return mdCodeMapper.findByMdCode(mdCode);
}
} }
package com.yd.dal.service.tencent.Impl;
import com.yd.dal.entity.tencent.TenInterfRecord;
import com.yd.dal.mapper.tencent.TenInterfRecordMapper;
import com.yd.dal.service.tencent.TenInterfRecordDALService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("tenInterfRecordDALService")
public class TenInterfRecordDALServiceImpl implements TenInterfRecordDALService {
@Resource
private TenInterfRecordMapper tenInterfRecordMapper;
@Override
public void saveTenInterfRecord(TenInterfRecord tencentInterfRecord) {
tenInterfRecordMapper.insertSelective(tencentInterfRecord);
}
@Override
public List<TenInterfRecord> findByTenInterfRecordOrderBy(TenInterfRecord tencentInterfRecord, String orderBy) {
return tenInterfRecordMapper.findByTenInterfRecordOrderBy(tencentInterfRecord, orderBy);
}
}
package com.yd.dal.service.tencent;
import com.yd.dal.entity.tencent.TenInterfRecord;
import java.util.List;
public interface TenInterfRecordDALService {
void saveTenInterfRecord(TenInterfRecord tencentInterfRecord);
List<TenInterfRecord> findByTenInterfRecordOrderBy(TenInterfRecord tencentInterfRecord, String orderBy);
}
package com.yd.dal.service.transaction.Impl;
import com.yd.dal.entity.transaction.TranLog;
import com.yd.dal.mapper.transaction.TranLogMapper;
import com.yd.dal.service.transaction.TranLogDALService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Service("tranLogDALService")
public class TranLogDALServiceImpl implements TranLogDALService {
@Resource
private TranLogMapper tranLogMapper;
@Override
public void logDB(String category,String type,String inOrOut,String tranNo,String tranXml,String returnCode,String returnMessage){
try {
TranLog tranLog = new TranLog();
tranLog.setCategory(category);
tranLog.setType(type);
tranLog.setInOrOut(inOrOut);
tranLog.setTranNo(tranNo);
tranLog.setTranXml(tranXml);
tranLog.setReturnCode(returnCode);
tranLog.setReturnMessage(returnMessage);
tranLog.setCreateDate(new Date());
tranLogMapper.insertSelective(tranLog);
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public List<TranLog> findByTranLogOrderBy(TranLog tranLogNew, String orderBy) {
return tranLogMapper.findByTranLogOrderBy(tranLogNew, orderBy);
}
}
package com.yd.dal.service.transaction;
import com.yd.dal.entity.transaction.TranLog;
import java.util.List;
public interface TranLogDALService {
public void logDB(String category, String type, String inOrOut, String tranNo, String tranXml, String returnCode, String returnMessage);
List<TranLog> findByTranLogOrderBy(TranLog tranLogNew, String orderBy);
}
...@@ -2,6 +2,7 @@ package com.yd.rmi.ali.oss.service.impl; ...@@ -2,6 +2,7 @@ package com.yd.rmi.ali.oss.service.impl;
import com.aliyun.oss.model.*; import com.aliyun.oss.model.*;
import com.yd.api.result.CommonResult; import com.yd.api.result.CommonResult;
import com.yd.cache.SystemConfigService;
import com.yd.rmi.ali.oss.service.OssService; import com.yd.rmi.ali.oss.service.OssService;
import com.yd.rmi.ali.oss.vo.OssOperateTypeEnum; import com.yd.rmi.ali.oss.vo.OssOperateTypeEnum;
import com.yd.rmi.ali.oss.vo.OssRequestVO; import com.yd.rmi.ali.oss.vo.OssRequestVO;
...@@ -21,16 +22,16 @@ import java.util.List; ...@@ -21,16 +22,16 @@ import java.util.List;
@Service("ossService") @Service("ossService")
public class OssServiceImpl implements OssService { public class OssServiceImpl implements OssService {
// @Autowired @Autowired
// private SystemConfigService systemConfigService; private SystemConfigService systemConfigService;
@Autowired @Autowired
private AliOssInterfService aliOssInterfService; private AliOssInterfService aliOssInterfService;
public boolean doesBucketExist(String bucketName){ public boolean doesBucketExist(String bucketName){
// String endpoint = systemConfigService.getSingleConfigValue("ALI_OSS_ENDPOINT"); String endpoint = systemConfigService.getSingleConfigValue("ALI_OSS_ENDPOINT");
// String accessKeyId = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_ID"); String accessKeyId = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_ID");
// String accessKeySecret = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_SECRET"); String accessKeySecret = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_SECRET");
// aliOssInterfService.initAttribute(endpoint, accessKeyId, accessKeySecret); aliOssInterfService.initAttribute(endpoint, accessKeyId, accessKeySecret);
return aliOssInterfService.doesBucketExist(bucketName); return aliOssInterfService.doesBucketExist(bucketName);
} }
...@@ -49,9 +50,9 @@ public class OssServiceImpl implements OssService { ...@@ -49,9 +50,9 @@ public class OssServiceImpl implements OssService {
return null; return null;
} }
// if(CommonUtil.isNullOrBlank(bucketName)){ if(CommonUtil.isNullOrBlank(bucketName)){
// bucketName = systemConfigService.getSingleConfigValue("ALI_OSS_BUCKET_NAME"); bucketName = systemConfigService.getSingleConfigValue("ALI_OSS_BUCKET_NAME");
// } }
OssRequestVO ossRequestVO = new OssRequestVO(); OssRequestVO ossRequestVO = new OssRequestVO();
File file = null; File file = null;
OutputStream os = null; OutputStream os = null;
......
...@@ -3,6 +3,7 @@ package com.yd.rmi.ali.ossinterf.service.impl; ...@@ -3,6 +3,7 @@ package com.yd.rmi.ali.ossinterf.service.impl;
import com.aliyun.oss.HttpMethod; import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient; import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*; import com.aliyun.oss.model.*;
import com.yd.cache.SystemConfigService;
import com.yd.rmi.ali.ossinterf.service.AliOssInterfService; import com.yd.rmi.ali.ossinterf.service.AliOssInterfService;
import com.yd.util.CommonUtil; import com.yd.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -19,19 +20,19 @@ public class AliOssInterfServiceImpl implements AliOssInterfService { ...@@ -19,19 +20,19 @@ public class AliOssInterfServiceImpl implements AliOssInterfService {
private String accessKeyId = null;//SystemConstants.ALI_OSS_ACCESS_KEY_ID; private String accessKeyId = null;//SystemConstants.ALI_OSS_ACCESS_KEY_ID;
private String accessKeySecret = null;//SystemConstants.ALI_OSS_ACCESS_KEY_SECRET; private String accessKeySecret = null;//SystemConstants.ALI_OSS_ACCESS_KEY_SECRET;
// @Autowired @Autowired
// private SystemConfigService systemConfigService; private SystemConfigService systemConfigService;
//
public void initAttribute(){ public void initAttribute(){
// if(CommonUtil.isNullOrBlank(this.endpoint)){ if(CommonUtil.isNullOrBlank(this.endpoint)){
// this.endpoint = systemConfigService.getSingleConfigValue("ALI_OSS_ENDPOINT"); this.endpoint = systemConfigService.getSingleConfigValue("ALI_OSS_ENDPOINT");
// } }
// if(CommonUtil.isNullOrBlank(this.accessKeyId)){ if(CommonUtil.isNullOrBlank(this.accessKeyId)){
// this.accessKeyId = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_ID"); this.accessKeyId = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_ID");
// } }
// if(CommonUtil.isNullOrBlank(this.accessKeySecret)){ if(CommonUtil.isNullOrBlank(this.accessKeySecret)){
// this.accessKeySecret = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_SECRET"); this.accessKeySecret = systemConfigService.getSingleConfigValue("ALI_OSS_ACCESS_KEY_SECRET");
// } }
} }
/** /**
......
package com.yd.rmi.tencent.wechat.service;
import com.yd.rmi.tencent.wechat.vo.WxNATIVEPayQueryReqVO;
import com.yd.rmi.tencent.wechat.vo.WxNATIVEPayQueryRespVO;
import com.yd.rmi.tencent.wechat.vo.WxUserInfo;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder.UnifiedorderResponse;
import java.util.Map;
public interface WechatService {
public String obtainToken(TokenRequest tokenRequest);
public String obtainTicket(TicketRequest ticketRequest);
public UnifiedorderResponse unifiedorder(String appId, String openId, String wCpayMethod, String timeExpire, String mchId, Double orderPrice, String planName, String orderNo, String notifyUrl);
/**
* 生成签名
* @param paraMap
* @param urlEncode
* @param keyToLower
* @param oppid
* @param key
* @return
*/
public String getSignValue(Map<String, String> paraMap,boolean urlEncode,boolean keyToLower,String oppid,String key);
/**
* 微信扫码支付结果查询接口
* @param wxNATIVEPayQueryReqVO
*/
public WxNATIVEPayQueryRespVO nativePayQuery(WxNATIVEPayQueryReqVO wxNATIVEPayQueryReqVO);
/**
* http连接
* @param httpURL 地址
* @param requestXML XML内容
* @return
*/
public String transaction(String authorizeURL, Object object);
/**
* 微信公众号支付组装html
* @param appId
* @param timeStamp
* @param nonceStr
* @param prepay_id
* @return
*/
public String weixinJSBridge(String appid, String timeStamp, String nonceStr, String prepayId, String notifyUrl,
String key);
/**
* JS-SDK使用权限签名算法
* @param jsapi_ticket
* @param url
* @return
*/
public Map<String, String> jsapiTicketSign(String jsapiTicket, String url);
/**
* 微信获取用户的openid
* @param appid
* @param secret
* @param code
* @return
*/
public AccessTokenResponse getOpenID(String appid, String secret, String code);
/**
* 微信获取用户的详细信息
* @param openId
* @param accessToken
* @return WxUserInfo
*/
public WxUserInfo getWxUserInfo(String openId, String accessToken);
}
package com.yd.rmi.tencent.wechat.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yd.api.result.CommonResult;
import com.yd.cache.SystemConfigService;
import com.yd.dal.entity.customer.Customer;
import com.yd.dal.entity.tencent.TenInterfRecord;
import com.yd.dal.entity.transaction.TranLog;
import com.yd.dal.service.tencent.TenInterfRecordDALService;
import com.yd.dal.service.transaction.TranLogDALService;
import com.yd.rmi.tencent.wechat.service.WechatService;
import com.yd.rmi.tencent.wechat.vo.WxNATIVEPayQueryReqVO;
import com.yd.rmi.tencent.wechat.vo.WxNATIVEPayQueryRespVO;
import com.yd.rmi.tencent.wechat.vo.WxUserInfo;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder.UnifiedorderRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder.UnifiedorderResponse;
import com.yd.rmi.tencent.wechatinterf.service.WechatInterfService;
import com.yd.util.CommonUtil;
import com.yd.util.EncryptUtil;
import com.yd.util.JsonUtil;
import com.yd.util.XmlUtil;
import com.yd.util.config.ZHBErrorConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.Map.Entry;
@Service("wechatService")
public class WechatServiceImpl implements WechatService {
@Autowired
private TenInterfRecordDALService tenInterfRecordDALService;
@Autowired
private WechatInterfService wechatInterfService;
@Autowired
private SystemConfigService systemConfigService;
// @Autowired
// private PoOrderService poOrderService;
// @Autowired
// private ProductPlanService productPlanService;
@Autowired
private TranLogDALService tranLogDALService;
@Override
public String obtainToken(TokenRequest tokenRequest) {
String accessToken = null;
String pGrantType = tokenRequest.getGrant_type() == null || "".equals(tokenRequest.getGrant_type()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TOKEN_GRANT_TYPE") : tokenRequest.getGrant_type();
String pAppid = tokenRequest.getAppid() == null || "".equals(tokenRequest.getAppid()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APPID"):tokenRequest.getAppid();
String pSecret = tokenRequest.getSecret() == null || "".equals(tokenRequest.getSecret()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APP_SECRET") : tokenRequest.getSecret();
TenInterfRecord tencentInterfRecord = new TenInterfRecord();
tencentInterfRecord.setInterfType("TOKEN");
tencentInterfRecord.setGrantType(pGrantType);
tencentInterfRecord.setAppid(pAppid);
tencentInterfRecord.setSecret(pSecret);
String orderBy = "created_at desc";
List<TenInterfRecord> tencentTnterfRecordList = tenInterfRecordDALService.findByTenInterfRecordOrderBy(tencentInterfRecord,orderBy);
boolean needReload = false;
if(tencentTnterfRecordList != null && tencentTnterfRecordList.size() >0){
tencentInterfRecord = tencentTnterfRecordList.get(0);
if(tencentInterfRecord.getExpiresIn() != null && !CommonUtil.isNullOrBlank(tencentInterfRecord.getAccessToken())){
Date overdueDate = CommonUtil.dateOperation(tencentInterfRecord.getCreatedAt(), "ADD", "S", tencentInterfRecord.getExpiresIn().intValue());
if(new Date().compareTo(overdueDate) > 0){
needReload = true;
}else{
accessToken = tencentInterfRecord.getAccessToken();
}
}else{
needReload = true;
}
}else{
needReload = true;
}
if(needReload){
TokenResponse tokenResponse = wechatInterfService.token(tokenRequest);
accessToken = tokenResponse.getAccess_token();
Long expiresIn = null;
if(tokenResponse.getExpires_in() != null && !"".equals(tokenResponse.getExpires_in())){
expiresIn = Long.parseLong(tokenResponse.getExpires_in());
}
tencentInterfRecord = new TenInterfRecord();
tencentInterfRecord.setInterfType("TOKEN");
tencentInterfRecord.setGrantType(pGrantType);
tencentInterfRecord.setAppid(pAppid);
tencentInterfRecord.setSecret(pSecret);
tencentInterfRecord.setAccessToken(tokenResponse.getAccess_token());
tencentInterfRecord.setExpiresIn(expiresIn);
tencentInterfRecord.setErrcode(tokenResponse.getErrcode());
tencentInterfRecord.setErrmsg(tokenResponse.getErrmsg());
tencentInterfRecord.setCreatedAt(new Date());
tenInterfRecordDALService.saveTenInterfRecord(tencentInterfRecord);
}
return accessToken;
}
@Override
public String obtainTicket(TicketRequest ticketRequest) {
String ticket = null;
String pType = ticketRequest.getType() == null || "".equals(ticketRequest.getType()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TICKET_TYPE") : ticketRequest.getType();
TenInterfRecord tencentInterfRecord = new TenInterfRecord();
tencentInterfRecord.setInterfType("TICKET");
tencentInterfRecord.setAccessToken(ticketRequest.getAccessToken());
tencentInterfRecord.setIType(pType);
String orderBy = "created_at desc";
List<TenInterfRecord> tencentTnterfRecordList = tenInterfRecordDALService.findByTenInterfRecordOrderBy(tencentInterfRecord,orderBy);
boolean needReload = false;
if(tencentTnterfRecordList != null && tencentTnterfRecordList.size() >0){
tencentInterfRecord = tencentTnterfRecordList.get(0);
if(tencentInterfRecord.getExpiresIn() != null && !CommonUtil.isNullOrBlank(tencentInterfRecord.getTicket())){
Date overdueDate = CommonUtil.dateOperation(tencentInterfRecord.getCreatedAt(), "ADD", "S", tencentInterfRecord.getExpiresIn().intValue());
if(new Date().compareTo(overdueDate) > 0){
needReload = true;
}else{
ticket = tencentInterfRecord.getTicket();
}
}else{
needReload = true;
}
}else{
needReload = true;
}
if(needReload){
TicketResponse ticketResponse = wechatInterfService.ticket(ticketRequest);
ticket = ticketResponse.getTicket();
Long expiresIn = null;
if(ticketResponse.getExpires_in() != null && !"".equals(ticketResponse.getExpires_in())){
expiresIn = Long.parseLong(ticketResponse.getExpires_in());
}
tencentInterfRecord = new TenInterfRecord();
tencentInterfRecord.setInterfType("TICKET");
tencentInterfRecord.setIType(pType);
tencentInterfRecord.setAccessToken(ticketRequest.getAccessToken());
tencentInterfRecord.setTicket(ticket);
tencentInterfRecord.setExpiresIn(expiresIn);
tencentInterfRecord.setErrcode(ticketResponse.getErrcode());
tencentInterfRecord.setErrmsg(ticketResponse.getErrmsg());
tencentInterfRecord.setCreatedAt(new Date());
tenInterfRecordDALService.saveTenInterfRecord(tencentInterfRecord);
}
return ticket;
}
@Override
public AccessTokenResponse getOpenID(String appid, String secret, String code) {
AccessTokenResponse response = null;
String zhbCode = "800000";
String zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
String responseJson = null;
if(!CommonUtil.isNullOrBlank(appid) &&!CommonUtil.isNullOrBlank(appid) &&!CommonUtil.isNullOrBlank(appid)){
String accessTokenUrl = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_ACCESS_TOKEN_URL");
response = new AccessTokenResponse();
String authorizeURL = accessTokenUrl+"?"+
"appid="+appid+
"&secret="+secret+
"&code="+code+
"&grant_type=authorization_code";
tranLogDALService.logDB("wechat", "getOpenId", "URL", appid, authorizeURL, null, null);
responseJson = transaction(authorizeURL,null);
if(!CommonUtil.isNullOrBlank(responseJson)){
response = (AccessTokenResponse) JsonUtil.jsonToObj(responseJson,AccessTokenResponse.class);
zhbMessage = response.getErrmsg();
zhbCode = response.getErrcode();
}else {
zhbCode = "900003";
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
}
}else {
zhbCode = "610002";
String[] params = {"appid、secret、code"};
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode, params);
}
tranLogDALService.logDB("wechat", "getOpenId", "response", appid, responseJson, zhbCode, zhbMessage);
return response;
}
@Override
public UnifiedorderResponse unifiedorder(String appId, String openId, String wCpayMethod, String timeExpire,String mchId,Double orderPrice,String planName,String orderNo,String notifyUrl) {
UnifiedorderResponse response = new UnifiedorderResponse();
String unifiedorderURL = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_UNIFIEDORDER_URL");
String result = "SUCCESS";
String zhbCode = "800000";
String zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
String signType = "MD5";
String responseXml = null;
// String notifyUrl = null;
String key = null;
if(CommonUtil.isNullOrBlank(appId) || CommonUtil.isNullOrBlank(wCpayMethod) ){
result = "FAIL";
zhbCode = "610002";
String[] params = {"appId(微信公众账号ID)、orderId(订单ID)、wCpayMethod(微信支付方式)"};
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode, params);
}
String mchIdYD = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_MCH_ID");//银盾商户号id
String mchIdYD2 = systemConfigService.getSingleConfigValue("YD2-TENCENT_WECHAT_MCH_ID");//银盾商户号id--福利产品
String mchIdAJB = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_MCH_ID");//安吉保商户号id
String simulateSwitch = systemConfigService.getSingleConfigValue("SimulateSwitch");
String spbillCreateIp = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_UNIFIEDORDER_SPBILL_CREATE_IP");
if(mchId.equals(mchIdYD)){//银盾
// notifyUrl = systemConfigService.getSingleConfigValue("YD_TENCENT_WECHAT_UNIFIEDORDER_NOTIFY_URL");//微信支付结果通知地址
key = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_API_KEY");//第三方用户唯一凭证密钥
}else if(mchId.equals(mchIdAJB)){//安吉保
// notifyUrl = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_UNIFIEDORDER_NOTIFY_URL");//微信支付结果通知地址
key = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_API_KEY");//第三方用户唯一凭证密钥
}else if(mchId.equals(mchIdYD2)){//银盾2--福利产品支付
// notifyUrl = systemConfigService.getSingleConfigValue("YD2_TENCENT_WECHAT_UNIFIEDORDER_NOTIFY_URL");//微信支付结果通知地址
key = systemConfigService.getSingleConfigValue("YD2-TENCENT_WECHAT_API_KEY");//第三方用户唯一凭证密钥
}else{
result = "FAIL";
zhbCode = "820001";
String[] params = {"ag_md_code,mchId-key"};
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode, params);
}
if("SUCCESS".equals(result)){
String nonceStr = CommonUtil.getRandomString(30);
int totalFee = (int)(orderPrice*100);
if("1".equals(simulateSwitch)){
totalFee = 1;
}
UnifiedorderRequest unifiedorderRequest = new UnifiedorderRequest();
unifiedorderRequest.setSign_type(signType);
unifiedorderRequest.setAppid(appId);
unifiedorderRequest.setMch_id(mchId);
unifiedorderRequest.setNonce_str(nonceStr);
unifiedorderRequest.setBody(planName);
unifiedorderRequest.setOut_trade_no(orderNo);
unifiedorderRequest.setTotal_fee(totalFee);
unifiedorderRequest.setSpbill_create_ip(spbillCreateIp);
unifiedorderRequest.setNotify_url(notifyUrl);
unifiedorderRequest.setProduct_id(orderNo);
unifiedorderRequest.setTrade_type(wCpayMethod);
unifiedorderRequest.setOpenid(openId);
unifiedorderRequest.setTime_expire(timeExpire);
Map<String,String> paraMap = new HashMap<String,String>();
paraMap.put("appid", appId);
paraMap.put("mch_id", mchId);
paraMap.put("nonce_str", nonceStr);
paraMap.put("body", planName);
paraMap.put("out_trade_no", orderNo);
paraMap.put("total_fee", String.valueOf(totalFee));
paraMap.put("spbill_create_ip", spbillCreateIp);
paraMap.put("notify_url", notifyUrl);
paraMap.put("trade_type", wCpayMethod);
paraMap.put("product_id", orderNo);
paraMap.put("openid", openId);
paraMap.put("sign_type", signType);
paraMap.put("time_expire", timeExpire);
String signValue = getSignValue(paraMap,false,false,appId,key);
paraMap.put("sign", signValue);
unifiedorderRequest.setSign(signValue);
XmlUtil xmlUtil = new XmlUtil(UnifiedorderRequest.class, XmlUtil.CollectionWrapper.class);
String requestXml = xmlUtil.toXml(unifiedorderRequest, "UTF-8");
tranLogDALService.logDB("YD-wechatpay", "unifiedorder", "in", orderNo, requestXml, null, null);
responseXml = transaction(unifiedorderURL, requestXml);
if(responseXml != null && !"".equals(responseXml)){
xmlUtil = new XmlUtil(UnifiedorderResponse.class, XmlUtil.CollectionWrapper.class);
response = xmlUtil.fromXml(responseXml);
}else{
zhbCode = "900003";
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
}
}
tranLogDALService.logDB("YD-wechatpay", "unifiedorder", "out", orderNo, responseXml, zhbCode, zhbMessage);
return response;
}
@Override
public WxUserInfo getWxUserInfo(String openId, String accessToken) {
WxUserInfo userInfo = null;
String zhbCode = "800000";
String zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
String responseJson = null;
if(!CommonUtil.isNullOrBlank(openId) &&!CommonUtil.isNullOrBlank(accessToken)){
userInfo = new WxUserInfo();
String url = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_AUTHORIZE_GETUSERINFO_URL")+"?access_token="+accessToken+"&openid="+openId;
tranLogDALService.logDB("wechat", "getWxUserInfo", "URL", openId, url, null, null);
responseJson = transaction(url,null);
if(!CommonUtil.isNullOrBlank(responseJson)){
userInfo = (WxUserInfo) JsonUtil.jsonToObj(responseJson, WxUserInfo.class);
if(!CommonUtil.isNullOrBlank(userInfo.getErrcode())){
zhbCode = userInfo.getErrcode();
zhbMessage = userInfo.getErrmsg();
}
}else {
zhbCode = "900003";
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode);
}
}else {
zhbCode = "610002";
String[] params = {"appid、accessToken"};
zhbMessage = ZHBErrorConfig.getErrorInfo(zhbCode, params);
}
try {
responseJson=URLEncoder.encode(responseJson ,"utf-8" );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
tranLogDALService.logDB("wechat", "getWxUserInfo", "response", openId, responseJson, zhbCode, zhbMessage);
return userInfo;
}
/**
* http连接
* @param httpURL 地址
* @param object XML内容
* @return
*/
public String transaction(String httpURL,Object object){
String responseXML = null;
HttpsURLConnection connection = null;
OutputStream output = null;
InputStream input = null;
try {
URL url = new URL(httpURL);
connection = (HttpsURLConnection) url.openConnection();
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setAllowUserInteraction(true);
// conn.setRequestMethod("POST"); //默认的请求方式是GET
// conn.setRequestProperty("Content-type", "text/html");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("contentType", "utf-8");
connection.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
connection.connect();
if (object != null && !"".equals(object)) {
output = connection.getOutputStream();
output.write((object.toString()).getBytes("utf-8"));
}
input = connection.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
StringBuffer stringBuffer = new StringBuffer();
if (input != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
String string = null;
while ((string = reader.readLine()) != null) {
stringBuffer.append(string);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
responseXML = stringBuffer.toString();
return responseXML;
}
/**
* 签名算法
* 方法用途:对所有传入参数按照字段名的Unicode码从小到大排序(字典序),并生成url参数串
* @param paraMap 需要排序的Map对象
* @param urlEncode 是否需要RULENCODE
* @param keyToLower 是否需要将Key转换为全小写 true:key转化成小写,false:不转化
*/
@Override
public String getSignValue(Map<String, String> paraMap,boolean urlEncode,boolean keyToLower,String appId,String key){
String signValue = null;
String tmpString = null;
if (paraMap!=null) {
try {
Map<String , String> tmpMap = paraMap;
//将map中的映射关系存入到一个list集合中,而这个关系的数据类型就是Map.Entry
List<Entry<String, String>> infoIds = new ArrayList<Entry<String, String>>(tmpMap.entrySet());
//对所有传入的参数按照字段名的ASCII码从小到到排序(字典序)
Collections.sort(infoIds,new Comparator<Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
//构建URL键值对的格式
StringBuilder buf = new StringBuilder();
for (Entry<String, String> item : infoIds){
if(item.getKey()!=null){
String infokey = item.getKey();
String value = item.getValue();
if(value != null && !"".equals(value)){
if (urlEncode) {
value= URLEncoder.encode(value,"UTF-8");
}
if (keyToLower) {
buf.append(infokey.toLowerCase()+"="+value);
}else{
buf.append(infokey+"="+value);
}
buf.append("&");
}
}
}
tmpString = buf.toString();
if (!tmpString.isEmpty()) {
tmpString = tmpString.substring(0,tmpString.length()-1);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
String stringSignTemp = tmpString+"&key="+key;
signValue = EncryptUtil.encrypt(stringSignTemp,null).toUpperCase();
return signValue;
}
@Override
public WxNATIVEPayQueryRespVO nativePayQuery(WxNATIVEPayQueryReqVO wxNATIVEPayQueryReqVO) {
WxNATIVEPayQueryRespVO response = new WxNATIVEPayQueryRespVO();
boolean success = false;
String message = null;
TranLog tranLog = null;
String tranNo = wxNATIVEPayQueryReqVO.getOrderNo();
if (tranNo != null && !"".equals(tranNo)) {
TranLog obj = new TranLog();
obj.setTranNo(tranNo);
obj.setCategory("YD-wechatpay");
obj.setType("paynotice");
obj.setInOrOut("in");
String orderBy = " id desc";
List<TranLog> tranLogs = tranLogDALService.findByTranLogOrderBy(obj, orderBy);
if (tranLogs.size()>0) {
tranLog = tranLogs.get(0);
}
}else{
success = false;
String[] params = {"订单号-tranNo"};
message = ZHBErrorConfig.getErrorInfo("610001", params);
response.setCommonResult(new CommonResult(success, message));
return response;
}
String returnCode = null ;
String returnMessage = null;
String url = null;
if(tranLog != null){
success = true;
message = ZHBErrorConfig.getErrorInfo("800000");
returnCode = tranLog.getReturnCode();
returnMessage = tranLog.getReturnMessage();
TranLog tranLogNew = new TranLog();
tranLogNew.setTranNo(tranNo);
tranLogNew.setCategory("YD-wechatpay");
tranLogNew.setType("NATIVE-URL");
tranLogNew.setInOrOut("request");
tranLogNew.setReturnCode("SUCCESS");
String orderBy = " id desc";
List<TranLog> tranLogNews = tranLogDALService.findByTranLogOrderBy(tranLogNew,orderBy);
if(tranLogNews.size()>0){
tranLogNew = tranLogNews.get(0);
url = tranLogNew.getReturnMessage();
}
}
response.setResult(returnCode);
response.setResultMessage(returnMessage);
response.setUrl(url);
response.setCommonResult(new CommonResult(success,message));
return response;
}
@Override
public String weixinJSBridge(String appid, String timeStamp, String nonceStr, String prepayId, String notifyUrl,
String key) {
String indexUrl = systemConfigService.getSingleConfigValue("FilePathPrefix");
indexUrl = indexUrl.substring(0,indexUrl.length()-1);;
String signType = "MD5";
String packageStr = "prepay_id="+prepayId;
Map<String,String> paraMap = new HashMap<String,String>();
paraMap.put("appId", appid);
paraMap.put("nonceStr", nonceStr);
paraMap.put("package", packageStr);
paraMap.put("signType",signType);
paraMap.put("timeStamp", timeStamp);
String paySignValue = getSignValue(paraMap,false,false,appid,key);
String result = ""
+"<script>"
+"\n function onBridgeReady(){"
+"\n WeixinJSBridge.invoke("
+"\n 'getBrandWCPayRequest', {"
+"\n \"appId\" : \""+appid+"\","
+"\n \"timeStamp\": \""+timeStamp+"\","
+"\n \"nonceStr\" : \""+nonceStr+"\","
+"\n \"package\" : \""+packageStr+"\","
+"\n \"signType\" : \""+signType+"\","
+"\n \"paySign\" : \""+paySignValue+"\""
+"\n },"
+"\n function(res){"
+"\n if(res.err_msg == \"get_brand_wcpay_request:ok\" ) {"
+"\n window.location.href=\""+notifyUrl+"\";"
+"\n }else if (res.err_msg == \"get_brand_wcpay_request:cancel\"){"
+"\n window.location.href=\""+indexUrl+"\";"
+"\n }else{"
+"\n alert(JSON.stringify(res));"
+"\n alert(res.err_msg);"
+"\n }"
+"\n }"
+"\n );"
+"\n }"
+"\n function callpay(){"
+"\n if (typeof WeixinJSBridge == \"undefined\"){"
+"\n if( document.addEventListener ){"
+"\n document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);"
+"\n }else if (document.attachEvent){"
+"\n document.attachEvent('WeixinJSBridgeReady', onBridgeReady);"
+"\n document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);"
+"\n }"
+"\n }else{"
+"\n onBridgeReady();"
+"\n }"
+"\n }"
+"\n callpay();"
+"\n</script>";
return result;
}
@Override
public Map<String, String> jsapiTicketSign(String jsapiTicket, String url) {
Map<String, String> ret = new HashMap<String, String>();
String nonceStr = createNonceStr();
String timestamp = createTimestamp();
String string1;
String signature = "";
//注意这里参数名必须全部小写,且必须有序
string1 = "jsapi_ticket=" + jsapiTicket +"&noncestr=" + nonceStr +"&timestamp=" + timestamp +"&url=" + url;
System.out.println(string1);
try{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(string1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}catch(UnsupportedEncodingException e){
e.printStackTrace();
}
ret.put("url", url);
ret.put("jsapi_ticket", jsapiTicket);
ret.put("nonceStr", nonceStr);
ret.put("timestamp", timestamp);
ret.put("signature", signature);
return ret;
}
private static String byteToHex(final byte[] hash){
Formatter formatter = new Formatter();
for (byte b : hash){
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}
private static String createNonceStr(){
return UUID.randomUUID().toString();
}
private static String createTimestamp(){
return Long.toString(System.currentTimeMillis() / 1000);
}
// private String transaction(String httpURL,String requestXML,String requestMethod){
// HttpsURLConnection conn = null;
// OutputStream out = null;
// InputStream in = null;
// try {
// URL url = new URL(httpURL);
// conn = (HttpsURLConnection) url.openConnection();
// conn.setReadTimeout(30000);
// conn.setDoInput(true);
// conn.setDoOutput(true);
// conn.setAllowUserInteraction(true);
// if (requestMethod != null) {
// conn.setRequestMethod(requestMethod);
// conn.setRequestProperty("Content-type", "text/html");
// }
// conn.setRequestProperty("Accept-Charset", "utf-8");
// conn.setRequestProperty("contentType", "utf-8");
// conn.setHostnameVerifier(new HostnameVerifier() {
// @Override
// public boolean verify(String arg0, SSLSession arg1) {
// return true;
// }
// });
// conn.connect();
// if(requestXML != null && !"".equals(requestXML)){
// requestXML = URLEncoder.encode(requestXML, "utf-8");
// out = conn.getOutputStream();
// out.write(requestXML.getBytes("utf-8"));
// }
// in = conn.getInputStream();
// } catch (Exception e) {
// e.printStackTrace();
// }finally{
// try {
// if(out != null){out.close();}
// } catch (Exception e2) {
// e2.printStackTrace();
// }
// }
// StringBuffer sbf = new StringBuffer();
// if(in != null){
// try {
// BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
// String str = null ;
// while((str = reader.readLine()) != null){
// sbf.append(str);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// String responseXML = sbf.toString();
// return responseXML;
// }
}
package com.yd.rmi.tencent.wechat.vo;
public class ParamItem {
private String name;//参数名
private String value;//参数值
/**
* 获取属性 name 参数名
* @return name
*/
public String getName(){
return this.name;
}
/**
* 属性赋值 name 参数名
* @param name
*/
public void setName(String name){
this.name = name;
}
/**
* 获取属性 value 参数值
* @return value
*/
public String getValue(){
return this.value;
}
/**
* 属性赋值 value 参数值
* @param value
*/
public void setValue(String value){
this.value = value;
}
public ParamItem() {
super();
}
public ParamItem(String name, String value) {
super();
this.name = name;
this.value = value;
}
}
package com.yd.rmi.tencent.wechat.vo;
import java.util.List;
public class PaymentForm {
private String action;//请求地址
private String actionType;//请求类型 get\post
private String charset;//编码格式 GBK\UTF-8
private List<ParamItem> param;//参数列表
private String errorMessage;//错误信息
/**
* 获取属性 action 请求地址
* @return action
*/
public String getAction(){
return this.action;
}
/**
* 属性赋值 action 请求地址
* @param action
*/
public void setAction(String action){
this.action = action;
}
/**
* 获取属性 actionType 请求类型 get\post
* @return actionType
*/
public String getActionType(){
return this.actionType;
}
/**
* 属性赋值 actionType 请求类型 get\post
* @param actionType
*/
public void setActionType(String actionType){
this.actionType = actionType;
}
/**
* 获取属性 charset 编码格式 GBK\UTF-8
* @return charset
*/
public String getCharset(){
return this.charset;
}
/**
* 属性赋值 charset 编码格式 GBK\UTF-8
* @param charset
*/
public void setCharset(String charset){
this.charset = charset;
}
/**
* 获取属性 param 参数列表
* @return param
*/
public List<ParamItem> getParam(){
return this.param;
}
/**
* 属性赋值 param 参数列表
* @param param
*/
public void setParam(List<ParamItem> param){
this.param = param;
}
/**
* 获取属性 errorMessage 错误消息
* @return the errorMessage
*/
public String getErrorMessage() {
return errorMessage;
}
/**
* 属性赋值 errorMessage 错误消息
* @param errorMessage
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
package com.yd.rmi.tencent.wechat.vo;
public class WxConfigRequestVO {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package com.yd.rmi.tencent.wechat.vo;
public class WxConfigResponseVO {
private String appId;// 必填,公众号的唯一标识
private String timestamp;//必填,生成签名的时间戳
private String nonceStr;// 必填,生成签名的随机串
private String signature;// 必填,签名,见附录1
private String[] jsApiList;// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getNonceStr() {
return nonceStr;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String[] getJsApiList() {
return jsApiList;
}
public void setJsApiList(String[] jsApiList) {
this.jsApiList = jsApiList;
}
}
package com.yd.rmi.tencent.wechat.vo;
public class WxGetUserInfoReqVO {
private String appid;//微信公众号appid
private String code;//微信-code
private Long customerId;
public Long getCustomerId() {
return customerId;
}
public void setCustomerId(Long customerId) {
this.customerId = customerId;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
package com.yd.rmi.tencent.wechat.vo;
import com.yd.api.result.CommonResult;
public class WxGetUserInfoRespVO {
private CommonResult commonResult;
private WxUserInfo userInfo;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
public WxUserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(WxUserInfo userInfo) {
this.userInfo = userInfo;
}
}
package com.yd.rmi.tencent.wechat.vo;
public class WxNATIVEPayQueryReqVO {
private String orderNo;
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
}
package com.yd.rmi.tencent.wechat.vo;
import com.yd.api.result.CommonResult;
public class WxNATIVEPayQueryRespVO {
private String result;
private String resultMessage;
private String url;
private CommonResult commonResult;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package com.yd.rmi.tencent.wechat.vo;
import com.yd.api.result.CommonResult;
public class WxURLForGetOpenId {
private CommonResult commonResult;
private PaymentForm paymentForm;
public CommonResult getCommonResult() {
return commonResult;
}
public void setCommonResult(CommonResult commonResult) {
this.commonResult = commonResult;
}
public PaymentForm getPaymentForm() {
return paymentForm;
}
public void setPaymentForm(PaymentForm paymentForm) {
this.paymentForm = paymentForm;
}
}
package com.yd.rmi.tencent.wechat.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
public class WxUserInfo {
private String subscribe;//用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息
private String openid; //普通用户的标识,对当前开发者帐号唯一
private String nickname; //普通用户昵称
private String sex; //普通用户性别,1为男性,2为女性
private String province; //普通用户个人资料填写的省份
private String city; //普通用户个人资料填写的城市
private String country; //国家,如中国为CN
private String headimgurl; //用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
private String[] privilege; //用户特权信息,json数组,如微信沃卡用户为(chinaunicom)
private String unionid; //用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的
private String language;//语言
private String errcode;//错误代码
private String errmsg;//错误信息
private String subscribeTime;//用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
private String remark;//公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
private String groupid;//用户所在的分组ID(兼容旧的用户分组接口)
private String[] tagidList;//用户被打上的标签ID列表
private String subscribeScene;//返回用户关注的渠道来源,ADD_SCENE_SEARCH 公众号搜索,ADD_SCENE_ACCOUNT_MIGRATION 公众号迁移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 扫描二维码,ADD_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
private String qrScene;//二维码扫码场景(开发者自定义)
private String qrSceneStr;//二维码扫码场景描述(开发者自定义)
/**
* @param openid 普通用户的标识,对当前开发者帐号唯一
*/
public void setOpenid(String openid) {
this.openid = openid;
}
/**
* @return openid 普通用户的标识,对当前开发者帐号唯一
*/
public String getOpenid() {
return openid;
}
/**
* @param nickname 普通用户昵称
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* @return nickname 普通用户昵称
*/
public String getNickname() {
return nickname;
}
/**
* @param sex 普通用户性别,1为男性,2为女性
*/
public void setSex(String sex) {
this.sex = sex;
}
/**
* @return sex 普通用户性别,1为男性,2为女性
*/
public String getSex() {
return sex;
}
/**
* @param province 普通用户个人资料填写的省份
*/
public void setProvince(String province) {
this.province = province;
}
/**
* @return province 普通用户个人资料填写的省份
*/
public String getProvince() {
return province;
}
/**
* @param city 普通用户个人资料填写的城市
*/
public void setCity(String city) {
this.city = city;
}
/**
* @return city 普通用户个人资料填写的城市
*/
public String getCity() {
return city;
}
/**
* @param country 国家,如中国为CN
*/
public void setCountry(String country) {
this.country = country;
}
/**
* @return country 国家,如中国为CN
*/
public String getCountry() {
return country;
}
/**
* @param headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
*/
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
/**
* @return headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空
*/
public String getHeadimgurl() {
return headimgurl;
}
/**
* @param privilege 用户特权信息,json数组,如微信沃卡用户为(chinaunicom)
*/
public void setPrivilege(String[] privilege) {
this.privilege = privilege;
}
/**
* @return privilege 用户特权信息,json数组,如微信沃卡用户为(chinaunicom)
*/
public String[] getPrivilege() {
return privilege;
}
/**
* @param unionid 用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的
*/
public void setUnionid(String unionid) {
this.unionid = unionid;
}
/**
* @return unionid 用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的
*/
public String getUnionid() {
return unionid;
}
/**
* @return language 语言
*/
public String getLanguage() {
return language;
}
/**
* @param language 语言
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* 获取属性 errcode 错误代码
* @return errcode
*/
public String getErrcode() {
return errcode;
}
/**
* 属性赋值 errcode 错误代码
* @param errcode
*/
public void setErrcode(String errcode) {
this.errcode = errcode;
}
/**
* 获取属性 errmsg 错误信息
* @return errmsg
*/
public String getErrmsg() {
return errmsg;
}
/**
* 属性赋值 errmsg 错误信息
* @param errmsg
*/
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
/**
* 获取属性 subscribe 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息
* @return subscribe
*/
public String getSubscribe() {
return subscribe;
}
/**
* 属性赋值 subscribe 用户是否订阅该公众号标识,值为0时,代表此用户没有关注该公众号,拉取不到其余信息
* @param subscribe
*/
public void setSubscribe(String subscribe) {
this.subscribe = subscribe;
}
/**
* 获取属性 subscribeTime 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
* @return subscribeTime
*/
@JsonProperty("subscribe_time")
public String getSubscribeTime() {
return subscribeTime;
}
/**
* 属性赋值 subscribeTime 用户关注时间,为时间戳。如果用户曾多次关注,则取最后关注时间
* @param subscribeTime
*/
public void setSubscribeTime(String subscribeTime) {
this.subscribeTime = subscribeTime;
}
/**
* 获取属性 remark 公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
* @return remark
*/
public String getRemark() {
return remark;
}
/**
* 属性赋值 remark 公众号运营者对粉丝的备注,公众号运营者可在微信公众平台用户管理界面对粉丝添加备注
* @param remark
*/
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 获取属性 groupid 用户所在的分组ID(兼容旧的用户分组接口)
* @return groupid
*/
public String getGroupid() {
return groupid;
}
/**
* 属性赋值 groupid 用户所在的分组ID(兼容旧的用户分组接口)
* @param groupid
*/
public void setGroupid(String groupid) {
this.groupid = groupid;
}
/**
* 获取属性 tagidList 用户被打上的标签ID列表
* @return tagidList
*/
@JsonProperty("tagid_list")
public String[] getTagidList() {
return tagidList;
}
/**
* 属性赋值 tagidList 用户被打上的标签ID列表
* @param tagidList
*/
public void setTagidList(String[] tagidList) {
this.tagidList = tagidList;
}
/**
* 获取属性 subscribeScene 返回用户关注的渠道来源,ADD_SCENE_SEARCH 公众号搜索,ADD_SCENE_ACCOUNT_MIGRATION 公众号迁移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 扫描二维码,ADD_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
* @return subscribeScene
*/
@JsonProperty("subscribe_scene")
public String getSubscribeScene() {
return subscribeScene;
}
/**
* 属性赋值 subscribeScene 返回用户关注的渠道来源,ADD_SCENE_SEARCH 公众号搜索,ADD_SCENE_ACCOUNT_MIGRATION 公众号迁移,ADD_SCENE_PROFILE_CARD 名片分享,ADD_SCENE_QR_CODE 扫描二维码,ADD_SCENEPROFILE LINK 图文页内名称点击,ADD_SCENE_PROFILE_ITEM 图文页右上角菜单,ADD_SCENE_PAID 支付后关注,ADD_SCENE_OTHERS 其他
* @param subscribeScene
*/
public void setSubscribeScene(String subscribeScene) {
this.subscribeScene = subscribeScene;
}
/**
* 获取属性 qrScene 二维码扫码场景(开发者自定义)
* @return qrScene
*/
@JsonProperty("qr_scene")
public String getQrScene() {
return qrScene;
}
/**
* 属性赋值 qrScene 二维码扫码场景(开发者自定义)
* @param qrScene
*/
public void setQrScene(String qrScene) {
this.qrScene = qrScene;
}
/**
* 获取属性 qrSceneStr 二维码扫码场景描述(开发者自定义)
* @return qrSceneStr
*/
@JsonProperty("qr_scene_str")
public String getQrSceneStr() {
return qrSceneStr;
}
/**
* 属性赋值 qrSceneStr 二维码扫码场景描述(开发者自定义)
* @param qrSceneStr
*/
public void setQrSceneStr(String qrSceneStr) {
this.qrSceneStr = qrSceneStr;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.accesstoken;
/**
* https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN
* 代公众号发起网页授权
简介
在公众号授权托管给第三方平台后,第三方平台可以根据本文档相关说明,代替授权公众号发起网页授权。关于OAuth2.0的详细介绍,可以参考OAuth2.0协议标准
作为第三方平台开发商,需要拥有自己的appid以及secret(在创建第三方平台并获得审核成功后可以获取),以及确保授权的公众号具备授权作用域的权限,以及用于回调的域名。
授权流程
微信目前支持Authorization code授权模式,主要流程分为两步:
1. 获取code
2. 通过code换取accesstoken
*
*/
public class AccessTokenRequest {
/*
!!! 开放平台的文档中对于这个接口的描述和公众平台有差异!下面是开放平台中截取的(在公众平台中入参没有component_appid和component_access_token,有secret)
第二步:通过code换取access_token
请求方法
获取第一步的code后,请求以下链接获取access_token:
https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=APPID&code=CODE&grant_type=authorization_code&component_appid=COMPONENT_APPID&component_access_token=COMPONENT_ACCESS_TOKEN
需要注意的是,由于安全方面的考虑,对访问该链接的客户端有IP白名单的要求。
参数说明
参数 是否必须 说明
appid 是 公众号的appid
code 是 填写第一步获取的code参数
grant_type 是 填authorization_code
component_appid 是 服务开发方的appid
component_access_token 是 服务开发方的access_token
返回说明
正确的返回:
{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}
参数 说明
access_token 接口调用凭证
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 授权用户唯一标识
scope 用户授权的作用域,使用逗号(,)分隔
错误返回样例:
{"errcode":40029,"errmsg":"invalid code"}
*/
private String appid;
private String secret;
private String code;
private String grant_type;
private String component_appid;
private String component_access_token;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getGrant_type() {
return grant_type;
}
public void setGrant_type(String grant_type) {
this.grant_type = grant_type;
}
public String getComponent_appid() {
return component_appid;
}
public void setComponent_appid(String component_appid) {
this.component_appid = component_appid;
}
public String getComponent_access_token() {
return component_access_token;
}
public void setComponent_access_token(String component_access_token) {
this.component_access_token = component_access_token;
}
}
\ No newline at end of file
package com.yd.rmi.tencent.wechatinterf.pojo.accesstoken;
public class AccessTokenResponse {
// {
// "access_token":"ACCESS_TOKEN",
// "expires_in":7200,
// "refresh_token":"REFRESH_TOKEN",
// "openid":"OPENID",
// "scope":"SCOPE",
// "unionid":"o6_bmasdasdsad6_2sgVt7hMZOPfL"
// }
private String access_token;
private String expires_in;
private String refresh_token;
private String openid;
private String scope;
private String unionid;
private String errcode;
private String errmsg;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.authorize;
/**
* https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN
* 代公众号发起网页授权
简介
在公众号授权托管给第三方平台后,第三方平台可以根据本文档相关说明,代替授权公众号发起网页授权。关于OAuth2.0的详细介绍,可以参考OAuth2.0协议标准
作为第三方平台开发商,需要拥有自己的appid以及secret(在创建第三方平台并获得审核成功后可以获取),以及确保授权的公众号具备授权作用域的权限,以及用于回调的域名。
授权流程
微信目前支持Authorization code授权模式,主要流程分为两步:
1. 获取code
2. 通过code换取accesstoken
*
*/
public class AuthorizeRequest {
/*
第一步:请求CODE
请求方法
在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(一般而言,已微信认证的服务号拥有snsapi_base和snsapi_userinfo),使用微信客户端打开以下链接(严格按照以下格式,包括顺序和大小写,并请将参数替换为实际内容):
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE&component_appid=component_appid#wechat_redirect
若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
参数说明
参数 是否必须 说明
appid 是 公众号的appid
redirect_uri 是 重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址
response_type 是 填code
scope 是 授权作用域,拥有多个作用域用逗号(,)分隔
state 否 重定向后会带上state参数,开发者可以填写任意参数值,最多128字节
component_appid 是 服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到
返回说明
用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code, state以及appid
redirect_uri?code=CODE&state=STATE&appid=APPID
若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数
redirect_uri?state=STATE
*/
private String appid;
private String redirect_uri;
private String response_type;
private String scope;
private String state;
private String component_appid;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getRedirect_uri() {
return redirect_uri;
}
public void setRedirect_uri(String redirect_uri) {
this.redirect_uri = redirect_uri;
}
public String getResponse_type() {
return response_type;
}
public void setResponse_type(String response_type) {
this.response_type = response_type;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getComponent_appid() {
return component_appid;
}
public void setComponent_appid(String component_appid) {
this.component_appid = component_appid;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.jscode2session;
public class Jscode2sessionRequest {
private String appid;//小程序唯一标识
private String secret;//小程序的 app secret
private String js_code;//登录时获取的 code
private String grant_type;//填写为 authorization_code
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public String getJs_code() {
return js_code;
}
public void setJs_code(String js_code) {
this.js_code = js_code;
}
public String getGrant_type() {
return grant_type;
}
public void setGrant_type(String grant_type) {
this.grant_type = grant_type;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.jscode2session;
public class Jscode2sessionResponse {
private String openid;//用户唯一标识
private String session_key;//会话密钥
private String unionid;//用户在开放平台的唯一标识符
private String errcode;
private String errmsg;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getSession_key() {
return session_key;
}
public void setSession_key(String session_key) {
this.session_key = session_key;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.ticket;
public class TicketRequest {
private String accessToken;
private String type;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
\ No newline at end of file
package com.yd.rmi.tencent.wechatinterf.pojo.ticket;
public class TicketResponse {
private String errcode;
private String errmsg;
private String ticket;
private String expires_in;
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
public String getTicket() {
return ticket;
}
public void setTicket(String ticket) {
this.ticket = ticket;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.token;
/**
* https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
* @author zxh
*
*/
public class TokenRequest {
/*
grant_type 是 获取access_token填写client_credential
appid 是 第三方用户唯一凭证
secret 是 第三方用户唯一凭证密钥,即appsecret
*/
private String grant_type;
private String appid;
private String secret;
public String getGrant_type() {
return grant_type;
}
public void setGrant_type(String grant_type) {
this.grant_type = grant_type;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.token;
public class TokenResponse {
private String access_token;
private String expires_in;
// {"errcode":41002,"errmsg":"appid missing hint: [Phsb7a0311e514]"}
private String errcode;
private String errmsg;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getExpires_in() {
return expires_in;
}
public void setExpires_in(String expires_in) {
this.expires_in = expires_in;
}
public String getErrcode() {
return errcode;
}
public void setErrcode(String errcode) {
this.errcode = errcode;
}
public String getErrmsg() {
return errmsg;
}
public void setErrmsg(String errmsg) {
this.errmsg = errmsg;
}
}
\ No newline at end of file
package com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="xml")
@XmlType(propOrder = { "appid","mch_id","device_info","nonce_str","sign","sign_type","body","detail","attach","out_trade_no","fee_type","total_fee","spbill_create_ip","time_start","time_expire","goods_tag","notify_url","trade_type","product_id","limit_pay","openid","scene_info"})
public class UnifiedorderRequest {
private String appid; //公众账号ID
private String mch_id; //商户号
private String device_info; //设备号
private String nonce_str; //随机字符串
private String sign; //签名
private String sign_type; //签名类型
private String body; //商品描述
private String detail; //商品详情
private String attach; //附加数据
private String out_trade_no; //商户订单号
private String fee_type; //标价币种
private int total_fee; //标价金额
private String spbill_create_ip; //终端IP
private String time_start; //交易起始时间
private String time_expire; //交易结束时间
private String goods_tag; //订单优惠标记
private String notify_url; //通知地址
private String trade_type; //交易类型
private String product_id; //商品ID
private String limit_pay; //指定支付方式
private String openid; //用户标识
private String scene_info; //场景信息
/**
* @param appid 公众账号ID
*/
public void setAppid(String appid) {
this.appid = appid;
}
/**
* @return appid 公众账号ID
*/
@XmlElement(name = "appid")
public String getAppid() {
return appid;
}
/**
* @param mch_id 商户号
*/
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
/**
* @return mch_id 商户号
*/
@XmlElement(name = "mch_id")
public String getMch_id() {
return mch_id;
}
/**
* @param device_info 设备号
*/
public void setDevice_info(String device_info) {
this.device_info = device_info;
}
/**
* @return device_info 设备号
*/
@XmlElement(name = "device_info")
public String getDevice_info() {
return device_info;
}
/**
* @param nonce_str 随机字符串
*/
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
/**
* @return nonce_str 随机字符串
*/
@XmlElement(name = "nonce_str")
public String getNonce_str() {
return nonce_str;
}
/**
* @param sign 签名
*/
public void setSign(String sign) {
this.sign = sign;
}
/**
* @return sign 签名
*/
@XmlElement(name = "sign")
public String getSign() {
return sign;
}
/**
* @param sign_type 签名类型
*/
public void setSign_type(String sign_type) {
this.sign_type = sign_type;
}
/**
* @return sign_type 签名类型
*/
@XmlElement(name = "sign_type")
public String getSign_type() {
return sign_type;
}
/**
* @param body 商品描述
*/
public void setBody(String body) {
this.body = body;
}
/**
* @return body 商品描述
*/
@XmlElement(name = "body")
public String getBody() {
return body;
}
/**
* @param detail 商品详情
*/
public void setDetail(String detail) {
this.detail = detail;
}
/**
* @return detail 商品详情
*/
@XmlElement(name = "detail")
public String getDetail() {
return detail;
}
/**
* @param attach 附加数据
*/
public void setAttach(String attach) {
this.attach = attach;
}
/**
* @return attach 附加数据
*/
@XmlElement(name = "attach")
public String getAttach() {
return attach;
}
/**
* @param out_trade_no 商户订单号
*/
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
/**
* @return out_trade_no 商户订单号
*/
@XmlElement(name = "out_trade_no")
public String getOut_trade_no() {
return out_trade_no;
}
/**
* @param fee_type 标价币种
*/
public void setFee_type(String fee_type) {
this.fee_type = fee_type;
}
/**
* @return fee_type 标价币种
*/
@XmlElement(name = "fee_type")
public String getFee_type() {
return fee_type;
}
/**
* @param total_fee 标价金额
*/
public void setTotal_fee(int total_fee) {
this.total_fee = total_fee;
}
/**
* @return total_fee 标价金额
*/
@XmlElement(name = "total_fee")
public int getTotal_fee() {
return total_fee;
}
/**
* @param spbill_create_ip 终端IP
*/
public void setSpbill_create_ip(String spbill_create_ip) {
this.spbill_create_ip = spbill_create_ip;
}
/**
* @return spbill_create_ip 终端IP
*/
@XmlElement(name = "spbill_create_ip")
public String getSpbill_create_ip() {
return spbill_create_ip;
}
/**
* @param time_start 交易起始时间
*/
public void setTime_start(String time_start) {
this.time_start = time_start;
}
/**
* @return time_start 交易起始时间
*/
@XmlElement(name = "Time_start")
public String getTime_start() {
return time_start;
}
/**
* @param time_expire 交易结束时间
*/
public void setTime_expire(String time_expire) {
this.time_expire = time_expire;
}
/**
* @return time_expire 交易结束时间
*/
@XmlElement(name = "time_expire")
public String getTime_expire() {
return time_expire;
}
/**
* @param goods_tag 订单优惠标记
*/
public void setGoods_tag(String goods_tag) {
this.goods_tag = goods_tag;
}
/**
* @return goods_tag 订单优惠标记
*/
@XmlElement(name = "goods_tag")
public String getGoods_tag() {
return goods_tag;
}
/**
* @param notify_url 通知地址
*/
public void setNotify_url(String notify_url) {
this.notify_url = notify_url;
}
/**
* @return notify_url 通知地址
*/
@XmlElement(name = "notify_url")
public String getNotify_url() {
return notify_url;
}
/**
* @param trade_type 交易类型
*/
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
/**
* @return trade_type 交易类型
*/
@XmlElement(name = "trade_type")
public String getTrade_type() {
return trade_type;
}
/**
* @param product_id 商品ID
*/
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
/**
* @return product_id 商品ID
*/
@XmlElement(name = "product_id")
public String getProduct_id() {
return product_id;
}
/**
* @param limit_pay 指定支付方式
*/
public void setLimit_pay(String limit_pay) {
this.limit_pay = limit_pay;
}
/**
* @return limit_pay 指定支付方式
*/
@XmlElement(name = "limit_pay")
public String getLimit_pay() {
return limit_pay;
}
/**
* @param openid 用户标识
*/
public void setOpenid(String openid) {
this.openid = openid;
}
/**
* @return openid 用户标识
*/
@XmlElement(name = "openid")
public String getOpenid() {
return openid;
}
/**
* @param scene_info 场景信息
*/
public void setScene_info(String scene_info) {
this.scene_info = scene_info;
}
/**
* @return scene_info 场景信息
*/
@XmlElement(name = "scene_info")
public String getScene_info() {
return scene_info;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="xml")
@XmlType(propOrder = { "return_code","return_msg","appid","mch_id","device_info","nonce_str","sign","result_code","err_code","err_code_des","trade_type","prepay_id","code_url","openid"})
public class UnifiedorderResponse {
private String return_code; //返回状态码
private String return_msg; //返回信息
private String appid; //公众账号ID
private String mch_id; //商户号
private String device_info; //设备号
private String nonce_str; //随机字符串
private String sign; //签名
private String result_code; //业务结果
private String err_code; //错误代码
private String err_code_des; //错误代码描述
private String trade_type; //交易类型
private String prepay_id; //预支付交易会话标识
private String code_url; //二维码链接
private String openid;
/**
* @param return_code 返回状态码
*/
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
/**
* @return return_code 返回状态码
*/
@XmlElement(name = "return_code")
public String getReturn_code() {
return return_code;
}
/**
* @param return_msg 返回信息
*/
public void setReturn_msg(String return_msg) {
this.return_msg = return_msg;
}
/**
* @return return_msg 返回信息
*/
@XmlElement(name = "return_msg")
public String getReturn_msg() {
return return_msg;
}
/**
* @param appid 公众账号ID
*/
public void setAppid(String appid) {
this.appid = appid;
}
/**
* @return appid 公众账号ID
*/
@XmlElement(name = "appid")
public String getAppid() {
return appid;
}
/**
* @param mch_id 商户号
*/
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
/**
* @return mch_id 商户号
*/
@XmlElement(name = "mch_id")
public String getMch_id() {
return mch_id;
}
/**
* @param device_info 设备号
*/
public void setDevice_info(String device_info) {
this.device_info = device_info;
}
/**
* @return device_info 设备号
*/
@XmlElement(name = "device_info")
public String getDevice_info() {
return device_info;
}
/**
* @param nonce_str 随机字符串
*/
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
/**
* @return nonce_str 随机字符串
*/
@XmlElement(name = "nonce_str")
public String getNonce_str() {
return nonce_str;
}
/**
* @param sign 签名
*/
public void setSign(String sign) {
this.sign = sign;
}
/**
* @return sign 签名
*/
@XmlElement(name = "sign")
public String getSign() {
return sign;
}
/**
* @param result_code 业务结果
*/
public void setResult_code(String result_code) {
this.result_code = result_code;
}
/**
* @return result_code 业务结果
*/
@XmlElement(name = "result_code")
public String getResult_code() {
return result_code;
}
/**
* @param err_code 错误代码
*/
public void setErr_code(String err_code) {
this.err_code = err_code;
}
/**
* @return err_code 错误代码
*/
@XmlElement(name = "err_code")
public String getErr_code() {
return err_code;
}
/**
* @param err_code_des 错误代码描述
*/
public void setErr_code_des(String err_code_des) {
this.err_code_des = err_code_des;
}
/**
* @return err_code_des 错误代码描述
*/
@XmlElement(name = "err_code_des")
public String getErr_code_des() {
return err_code_des;
}
/**
* @param trade_type 交易类型
*/
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
/**
* @return trade_type 交易类型
*/
@XmlElement(name = "trade_type")
public String getTrade_type() {
return trade_type;
}
/**
* @param prepay_id 预支付交易会话标识
*/
public void setPrepay_id(String prepay_id) {
this.prepay_id = prepay_id;
}
/**
* @return prepay_id 预支付交易会话标识
*/
@XmlElement(name = "prepay_id")
public String getPrepay_id() {
return prepay_id;
}
/**
* @param code_url 二维码链接
*/
public void setCode_url(String code_url) {
this.code_url = code_url;
}
/**
* @return code_url 二维码链接
*/
@XmlElement(name = "code_url")
public String getCode_url() {
return code_url;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.wechatpay;
public class WechatPayReqVO {
private String planName;
private Double totalFee;
private Long planId;
private String orderNo;
private String notifyUrl;
private String wechatPayMethod;
public String getPlanName() {
return planName;
}
public void setPlanName(String planName) {
this.planName = planName;
}
public Double getTotalFee() {
return totalFee;
}
public void setTotalFee(Double totalFee) {
this.totalFee = totalFee;
}
public Long getPlanId() {
return planId;
}
public void setPlanId(Long planId) {
this.planId = planId;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getNotifyUrl() {
return notifyUrl;
}
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
public String getWechatPayMethod() {
return wechatPayMethod;
}
public void setWechatPayMethod(String wechatPayMethod) {
this.wechatPayMethod = wechatPayMethod;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.wechatpay;
public class WxConfigRequestVO {
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
package com.yd.rmi.tencent.wechatinterf.pojo.wechatpay;
public class WxConfigResponseVO {
private String appId;// 必填,公众号的唯一标识
private String timestamp;//必填,生成签名的时间戳
private String nonceStr;// 必填,生成签名的随机串
private String signature;// 必填,签名,见附录1
private String[] jsApiList;// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public String getNonceStr() {
return nonceStr;
}
public void setNonceStr(String nonceStr) {
this.nonceStr = nonceStr;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String[] getJsApiList() {
return jsApiList;
}
public void setJsApiList(String[] jsApiList) {
this.jsApiList = jsApiList;
}
}
package com.yd.rmi.tencent.wechatinterf.service;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.authorize.AuthorizeRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.jscode2session.Jscode2sessionRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.jscode2session.Jscode2sessionResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder.UnifiedorderResponse;
public interface WechatInterfService {
/**
* 公众号支付时网页授权
* 1. 获取code
* @param AuthorizeRequest
* @return
*/
public void authorize(AuthorizeRequest authorizeRequest);
/**
* 公众号支付时网页授权,这里返回值有openid
* 2. 通过code换取accesstoken
* @param AccessTokenRequest
* @return
*/
public AccessTokenResponse accessToken(AccessTokenRequest accessTokenRequest);
/**
* 微信分享授权第一步
* 获取公众号的access_token
* 注意这和网页授权部分的access_token不是一回事!该接口有调用次数限制,且独立(不依赖于authorize接口)
* @param TokenRequest
* @return
*/
public TokenResponse token(TokenRequest tokenRequest);
/**
* 微信分享授权第二步
* 获取jsapi_ticket
* @param ticketRequest
* @return
*/
public TicketResponse ticket(TicketRequest ticketRequest);
/**
* 小程序wx.login登录凭证校验,使用 临时登录凭证code 获取 session_key 和 openid 等
* @param jscode2sessionRequest
* @return Jscode2sessionResponse
*/
public Jscode2sessionResponse jscode2session(Jscode2sessionRequest jscode2sessionRequest);
/**
* 微信支付返回报文校验
* @param unifiedorderResponse
* @param key
* @return
*/
public boolean signValite(UnifiedorderResponse unifiedorderResponse);
public String transaction(String url, String object, String object2);
}
package com.yd.rmi.tencent.wechatinterf.service.impl;
import com.yd.cache.SystemConfigService;
import com.yd.dal.service.transaction.TranLogDALService;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.accesstoken.AccessTokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.authorize.AuthorizeRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.jscode2session.Jscode2sessionRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.jscode2session.Jscode2sessionResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.ticket.TicketResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenRequest;
import com.yd.rmi.tencent.wechatinterf.pojo.token.TokenResponse;
import com.yd.rmi.tencent.wechatinterf.pojo.unifiedorder.UnifiedorderResponse;
import com.yd.rmi.tencent.wechatinterf.service.WechatInterfService;
import com.yd.util.CommonUtil;
import com.yd.util.EncryptUtil;
import com.yd.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.Map.Entry;
@Service("wechatInterfService")
public class WechatInterfServiceImpl implements WechatInterfService {
@Autowired
private SystemConfigService systemConfigService;
@Autowired
private TranLogDALService tranLogDALService;
/**
* 公众号支付时网页授权
* 1. 获取code
* @param authorizeRequest
* @return
* @return
*/
@Override
public void authorize(AuthorizeRequest authorizeRequest) {
String p_appid = authorizeRequest.getAppid();
String p_redirect_uri = authorizeRequest.getRedirect_uri();
String p_response_type = authorizeRequest.getResponse_type();
String p_scope = authorizeRequest.getScope();
String p_state = authorizeRequest.getState();
String url = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_AUTHORIZE_URL")+"?"
+"appid="+p_appid
+"&redirect_uri="+p_redirect_uri
+"&response_type="+p_response_type
+"&scope="+p_scope
+"&state="+p_state
+"#wechat_redirect";
RestTemplate template = new RestTemplate();
String response = template.getForObject(url, String.class);
tranLogDALService.logDB("wechat", "authorize", "out", p_appid, url, null, null);
System.out.println("--------------response--------->"+response);
}
/**
* 公众号支付时网页授权,这里返回值有openid
* 2. 通过code换取accesstoken
* @param accessTokenRequest
* @return AccessTokenResponse
*/
@Override
public AccessTokenResponse accessToken(AccessTokenRequest accessTokenRequest) {
String p_appid = accessTokenRequest.getAppid() == null || "".equals(accessTokenRequest.getAppid()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APPID"):accessTokenRequest.getAppid();
String p_secret = accessTokenRequest.getSecret() == null || "".equals(accessTokenRequest.getSecret()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APP_SECRET"):accessTokenRequest.getSecret();
String p_grant_type = accessTokenRequest.getGrant_type() == null || "".equals(accessTokenRequest.getGrant_type()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_ACCESS_TOKEN_GRANT_TYPE") : accessTokenRequest.getGrant_type();
String url = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_ACCESS_TOKEN_URL")+"?"
+"appid="+p_appid
+"&secret="+p_secret
+"&code="+accessTokenRequest.getCode()
+"&grant_type="+p_grant_type;
tranLogDALService.logDB("wechat", "accessToken2", "in", accessTokenRequest.getCode(), url, null, null);
String responseStr = transaction(url,null,null);
tranLogDALService.logDB("wechat", "accessToken2", "out", accessTokenRequest.getCode(), responseStr, null, null);
return (AccessTokenResponse)JsonUtil.jsonToObj(responseStr,AccessTokenResponse.class);
}
/**
* 微信分享授权第一步
* 获取公众号的access_token
* 注意这和网页授权部分的access_token不是一回事!该接口有调用次数限制,且独立(不依赖于authorize接口)
* @param tokenRequest
* @return
*/
@Override
public TokenResponse token(TokenRequest tokenRequest) {
String p_appid = tokenRequest.getAppid() == null || "".equals(tokenRequest.getAppid()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APPID"):tokenRequest.getAppid();
String p_grant_type = tokenRequest.getGrant_type() == null || "".equals(tokenRequest.getGrant_type()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TOKEN_GRANT_TYPE") : tokenRequest.getGrant_type();
String p_secret = tokenRequest.getSecret() == null || "".equals(tokenRequest.getSecret()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_APP_SECRET") : tokenRequest.getSecret();
String url = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TOKEN_URL")+"?"
+"grant_type="+p_grant_type
+"&appid="+p_appid
+"&secret="+p_secret;
System.out.println("【》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》【微信分享 --4--token-url】"+url+"】");
tranLogDALService.logDB("wechat", "accessToken", "in", tokenRequest.getAppid(), url, null, null);
String responseStr = transaction(url,null,null);
tranLogDALService.logDB("wechat", "accessToken", "out", tokenRequest.getAppid(), responseStr, null, null);
return (TokenResponse)JsonUtil.jsonToObj(responseStr,TokenResponse.class);
}
/**
* 微信分享授权第二步
* 获取jsapi_ticket
* @param ticketRequest
* @return
*/
@Override
public TicketResponse ticket(TicketRequest ticketRequest) {
String p_type = ticketRequest.getType() == null || "".equals(ticketRequest.getType()) ? systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TICKET_TYPE"):ticketRequest.getType();
String url = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_TICKET_URL")+"?"
+"access_token="+ticketRequest.getAccessToken()
+"&type="+p_type;
tranLogDALService.logDB("wechat", "ticket", "in", ticketRequest.getAccessToken(), url, null, null);
String responseStr = transaction(url,null,null);
tranLogDALService.logDB("wechat", "ticket", "out", ticketRequest.getAccessToken(), responseStr, null, null);
return (TicketResponse) JsonUtil.jsonToObj(responseStr,TicketResponse.class);
}
/**
* 小程序wx.login登录凭证校验,使用 临时登录凭证code 获取 session_key 和 openid 等
* @param request
* @return Jscode2sessionResponse
*/
@Override
public Jscode2sessionResponse jscode2session(Jscode2sessionRequest request) {
Jscode2sessionResponse response = null;
String appid = CommonUtil.isNullOrBlank(request.getAppid()) ? systemConfigService.getSingleConfigValue("TENCENT_MINI_PROGRAM_APPID"):request.getAppid();
String secret = CommonUtil.isNullOrBlank(request.getSecret()) ? systemConfigService.getSingleConfigValue("TENCENT_MINI_PROGRAM_SECRET"):request.getSecret();
String grantType = CommonUtil.isNullOrBlank(request.getGrant_type()) ? "authorization_code":request.getGrant_type();
String url = systemConfigService.getSingleConfigValue("TENCENT_JSCODE2SESSION_URL")+"?"
+"appid="+appid
+"&secret="+secret
+"&js_code="+request.getJs_code()
+"&grant_type="+grantType;
String responseStr = transaction(url,null,null);
try{
response = (Jscode2sessionResponse)JsonUtil.jsonToObj(responseStr, Jscode2sessionResponse.class);;
}catch(Exception e){
}
return response;
}
/**
* 签名算法
* 方法用途:对所有传入参数按照字段名的Unicode码从小到大排序(字典序),并生成url参数串
* @param paraMap 需要排序的Map对象
* @param urlEncode 是否需要RULENCODE
* @param keyToLower 是否需要将Key转换为全小写 true:key转化成小写,false:不转化
*/
private static String getSignValue(Map<String, String> paraMap,boolean urlEncode,boolean keyToLower,String key){
String signValue = null;
String tmpString = null;
if (paraMap!=null) {
try {
Map<String , String> tmpMap = paraMap;
//将map中的映射关系存入到一个list集合中,而这个关系的数据类型就是Map.Entry
List<Entry<String, String>> infoIds = new ArrayList<Entry<String, String>>(tmpMap.entrySet());
//对所有传入的参数按照字段名的ASCII码从小到到排序(字典序)
Collections.sort(infoIds,new Comparator<Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
//构建URL键值对的格式
StringBuilder buf = new StringBuilder();
for (Entry<String, String> item : infoIds){
if(item.getKey()!=null){
String infokey = item.getKey();
String value = item.getValue();
if(value != null && !"".equals(value)){
if (urlEncode) {
value= URLEncoder.encode(value,"UTF-8");
}
if (keyToLower) {
buf.append(infokey.toLowerCase()).append("=").append(value);
}else{
buf.append(infokey).append("=").append(value);
}
buf.append("&");
}
}
}
tmpString = buf.toString();
if (!tmpString.isEmpty()) {
tmpString = tmpString.substring(0,tmpString.length()-1);
}
System.out.println("----tmpString-----"+tmpString);
} catch (Exception e) {
System.out.println("----出错了!!!!-----");
return null;
}
}
String stringSignTemp = tmpString+"&key="+key;
return EncryptUtil.encrypt(stringSignTemp,null).toUpperCase();
}
/**
* 对响应的报文进行校验
*/
@Override
public boolean signValite(UnifiedorderResponse unifiedorderResponse) {
boolean result = false;
String key = null;
String code = null;
code = unifiedorderResponse.getReturn_code();
if ("SUCCESS".equals(code)) {//对返回报文进行签名校验
String return_code = unifiedorderResponse.getReturn_code();
String return_msg = unifiedorderResponse.getReturn_msg();
String device_infoResp = unifiedorderResponse.getDevice_info();
String nonce_strResp = unifiedorderResponse.getNonce_str();
String appid = unifiedorderResponse.getAppid();
String mch_id = unifiedorderResponse.getMch_id();
String sign = unifiedorderResponse.getSign();
String openid = unifiedorderResponse.getOpenid();
String trade_type = unifiedorderResponse.getTrade_type();
String result_code = unifiedorderResponse.getResult_code();
String prepay_id = unifiedorderResponse.getPrepay_id();
String err_code = unifiedorderResponse.getErr_code();
String err_code_des = unifiedorderResponse.getErr_code_des();
String code_url = unifiedorderResponse.getCode_url();
if(appid.equals("YD-TENCENT_WECHAT_APPID")){
key = systemConfigService.getSingleConfigValue("YD-TENCENT_WECHAT_API_KEY");//第三方用户唯一凭证密钥
}else if (appid.equals("TENCENT_WECHAT_APPID")) {
key = systemConfigService.getSingleConfigValue("TENCENT_WECHAT_API_KEY");
}
Map<String,String> paraMap = new HashMap<String,String>();
paraMap.put("device_info", device_infoResp);
paraMap.put("return_code", return_code);
paraMap.put("return_msg", return_msg);
paraMap.put("appid", appid);
paraMap.put("mch_id", mch_id);
paraMap.put("nonce_str", nonce_strResp);
paraMap.put("openid", openid);
paraMap.put("result_code", result_code);
paraMap.put("err_code", err_code);
paraMap.put("err_code_des", err_code_des);
if("SUCCESS".equals(result_code)){
paraMap.put("trade_type", trade_type);
paraMap.put("prepay_id", prepay_id);
paraMap.put("code_url", code_url);
}
String signValue = getSignValue(paraMap,false,false,key);
if (sign.equals(signValue)) {
result = true;
}
}
return result;
}
@Override
public String transaction(String httpURL,String requestXML,String requestMethod){
HttpsURLConnection conn = null;
OutputStream out = null;
InputStream in = null;
try {
URL url = new URL(httpURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(30000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setAllowUserInteraction(true);
if (requestMethod != null) {
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("Content-type", "text/html");
}
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("contentType", "utf-8");
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
conn.connect();
if(requestXML != null && !"".equals(requestXML)){
requestXML = URLEncoder.encode(requestXML, "utf-8");
out = conn.getOutputStream();
out.write(requestXML.getBytes("utf-8"));
}
in = conn.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(out != null){out.close();}
} catch (Exception e2) {
e2.printStackTrace();
}
}
StringBuffer sbf = new StringBuffer();
if(in != null){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
String str = null ;
while((str = reader.readLine()) != null){
sbf.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sbf.toString();
}
}
\ No newline at end of file
package com.yd.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.security.*;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class EncryptUtil {
private static final Log logger = LogFactory.getLog(EncryptUtil.class);
private static final String HEX_CHARS = "0123456789abcdef";
/**
* 加密
* @param source
* @return
*/
public static String encrypt(String source,String charSet) {
if(CommonUtil.isNullOrBlank(source)){
return null;
}
if(CommonUtil.isNullOrBlank(charSet)){
charSet = "utf-8";
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
try {
md.update(source.getBytes(charSet));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0){i += 256;}
if (i < 16){buf.append("0");}
buf.append(Integer.toHexString(i));
}
//32位加密
return buf.toString();
// 16位的加密
//return buf.toString().substring(8, 24);
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
return null;
}
}
public static String encryptLiberty(String str,String charSet) {
if (CommonUtil.isNullOrBlank(str)){
return null;
}
if(CommonUtil.isNullOrBlank(charSet)){
charSet = "utf-8";
}
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charSet));
return byteArrayToHexString(md.digest());
} catch (Exception e) {
// System.out.println(e.getMessage());
return null;
}
}
public static String byteArrayToHexString(byte[] b) {
String result = "";
for (byte aB : b) {
result += Integer.toString((aB & 0xff) + 0x100, 16).substring(1);
}
return result;
}
/**
* SHA256WithRSA 加签
*
* @param content
* @param privateKey
* @param charset
* @return
*/
public static String rsa256Sign(String content, String privateKey,String charset){
// org.apache.xml.security.utils.Base64 b = null;
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.getDecoder().decode(privateKey);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encodedKey);
PrivateKey prikey = keyFactory.generatePrivate(keySpec);
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(prikey);
if(charset != null && !"".equals(charset)){
signature.update(content.getBytes(charset));
}else{
signature.update(content.getBytes());
}
byte[] signed = signature.sign();
return new String(Base64.getEncoder().encode(signed));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e){
e.printStackTrace();
} catch (InvalidKeyException e){
e.printStackTrace();
} catch (UnsupportedEncodingException e){
e.printStackTrace();
} catch (SignatureException e){
e.printStackTrace();
}
return null;
}
/**
* SHA256WithRSA 验签
* @param content
* @param sign
* @param publicKey
* @param charset
* @return
*/
public static boolean rsa256CheckContent(String content, String sign, String publicKey,String charset){
try{
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64.getDecoder().decode(publicKey);
PublicKey pubkey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initVerify(pubkey);
if(charset != null && !"".equals(charset)){
signature.update(content.getBytes(charset));
}else{
signature.update(content.getBytes());
}
return signature.verify(Base64.getDecoder().decode(sign.getBytes()));
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
} catch (InvalidKeySpecException e){
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return false;
}
/**
* 私钥加密方法(非对称)
*@param parameterStr 明文字符串
*@param aliasName 证书别名
*@param keystorePwd 证书密码
*@param inputCharset 字符集
*@param privateFilePath 私钥证书路径
*@return
* @author ex_liukai
* @see
*/
public static String axaSign(String parameterStr,String aliasName,
String keystorePwd,String inputCharset,String privateFilePath){
String base64 = "";
try{
KeyStore ks = KeyStore.getInstance("PKCS12");
//私钥证书地址
FileInputStream ksfis = new FileInputStream(privateFilePath);
BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
//私钥密码
char[] keyPwd = keystorePwd.toCharArray();
ks.load(ksbufin, keyPwd);
PrivateKey priK = (PrivateKey)ks.getKey("test-alias", keyPwd);
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initSign(priK);
signature.update(parameterStr.getBytes(inputCharset));
BASE64Encoder encoder = new BASE64Encoder();
base64 = encoder.encode(signature.sign());
}catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(e);
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex);
}
return base64;
}
/**
* 解密方法
*@param parameterStr 明文字符串
*@param sign 加密串
*@param publicFilePath 公钥证书路径
*@return
* @author ex_liukai
* @see
*/
public static boolean axaEnCodeByCer(String parameterStr, String sign,String publicFilePath){
boolean flag = false;
try{
//公钥证书文件
InputStream inStream = new FileInputStream(publicFilePath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate)cf.generateCertificate(inStream);
PublicKey pk = cert.getPublicKey();
Signature signature = Signature.getInstance("SHA1withRSA");
signature.initVerify(pk);
signature.update(parameterStr.getBytes());
BASE64Decoder decoder = new BASE64Decoder();
flag = signature.verify(decoder.decodeBuffer(sign));
} catch (Exception e) {
System.out.println(e.toString());
}
return flag;
}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigest() {
try {
return MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* 返回 MessageDigest MD5
*/
private static MessageDigest getDigestBySha() {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static MessageDigest getDigestBySha1() {
try {
return MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* MD5加密,并返回作为一个十六进制字节
*/
public static byte[] md5(byte[] data) {
return getDigest().digest(data);
}
/**
* SHA-256加密,并返回作为一个十六进制字节
*/
public static byte[] sha256(byte[] data) {
return getDigestBySha().digest(data);
}
public static byte[] sha1(byte[] data) {
return getDigestBySha1().digest(data);
}
/**
* MD5加密,并返回作为一个十六进制字节
* <code>byte[]</code>.
* @param data Data to digest
* @return MD5 digest
*/
public static byte[] md5(String data,String charSet) {
if(CommonUtil.isNullOrBlank(charSet)){
charSet = "UTF-8";
}
byte[] bytes = null;
try {
bytes = md5(data.getBytes(charSet));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
}
return bytes;
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(byte[] data) {
return toHexString(md5(data));
}
/**
* MD5加密,并返回一个32字符的十六进制值
*/
public static String md5Hex(String data,String charSet) {
return toHexString(md5(data,charSet));
}
/**
* SHA256加密
*/
public static String sha256Hex(String data,String charSet) {
if(CommonUtil.isNullOrBlank(charSet)){
charSet = "UTF-8";
}
try {
return toHexString(sha256(data.getBytes(charSet)));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
return null;
}
}
public static String sha1Hex(String data,String charSet) {
if(CommonUtil.isNullOrBlank(charSet)){
charSet = "UTF-8";
}
try {
return toHexString(sha1(data.getBytes(charSet)));
} catch (UnsupportedEncodingException e) {
logger.error("MD5加密出错。",e);
return null;
}
}
private static String toHexString(byte[] b) {
StringBuffer stringbuffer = new StringBuffer();
for (int i = 0; i < b.length; i++) {
stringbuffer.append(HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
stringbuffer.append(HEX_CHARS.charAt(b[i] & 0x0F));
}
return stringbuffer.toString();
}
}
package com.yd.util;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper(); //转换器
public static String objToJson(Object obj){
mapper.setSerializationInclusion(Include.NON_NULL);
String json = null;
try {
json = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object jsonToObj(String json,Class cl){
if(json == null || "".equals(json.trim())){
return null;
}
Object obj = null;
try {
obj = mapper.readValue(json, cl);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return obj;
}
public static String format(String jsonStr) {
int level = 0;
StringBuffer jsonForMatStr = new StringBuffer();
for(int i=0;i<jsonStr.length();i++){
char c = jsonStr.charAt(i);
if(level>0&&'\n'==jsonForMatStr.charAt(jsonForMatStr.length()-1)){
jsonForMatStr.append(getLevelStr(level));
}
switch (c) {
case '{':
case '[':
jsonForMatStr.append(c+"\n");
level++;
break;
case ',':
jsonForMatStr.append(c+"\n");
break;
case '}':
case ']':
jsonForMatStr.append("\n");
level--;
jsonForMatStr.append(getLevelStr(level));
jsonForMatStr.append(c);
break;
default:
jsonForMatStr.append(c);
break;
}
}
return jsonForMatStr.toString();
}
private static String getLevelStr(int level){
StringBuffer levelStr = new StringBuffer();
for(int levelI = 0;levelI<level ; levelI++){
levelStr.append("\t");
}
return levelStr.toString();
}
}
package com.yd.util;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import javax.xml.bind.*;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
//import org.apache.commons.lang.StringUtils;
/**
* 使用Jaxb2.0实现XML<->Java Object的Binder.
*
* 特别支持Root对象是List的情形.
*
* @author
*/
public class XmlUtil {
// 多线程安全的Context.
private JAXBContext jaxbContext;
/**
* @param types
* 所有需要序列化的Root对象的类型.
*/
public XmlUtil(Class<?>... types) {
try {
jaxbContext = JAXBContext.newInstance(types);
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
}
}
/**
* Java Object->Xml.
*/
public String toXml4Dadi(Object root, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* Java Object->Xml.
*/
public String toXml(Object root, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* Java Object->Xml, 特别支持对Root Element是Collection的情形.
*/
@SuppressWarnings("rawtypes")
public String toXml(Collection root, String rootName, String encoding) {
try {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(
new QName(rootName), CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* Xml->Java Object.
*/
@SuppressWarnings("unchecked")
public <T> T fromXml(String xml) {
if(xml == null || "".equals(xml.trim())){
return null;
}
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* Xml->Java Object, 支持大小写敏感或不敏感.
*/
@SuppressWarnings("unchecked")
public <T> T fromXml(String xml, boolean caseSensitive) {
try {
String fromXml = xml;
if (!caseSensitive){
fromXml = xml.toLowerCase();
}
StringReader reader = new StringReader(fromXml);
return (T) createUnmarshaller().unmarshal(reader);
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* 创建Marshaller, 设定encoding(可为Null).
*/
public Marshaller createMarshaller(String encoding) {
try {
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// if (StringUtils.isNotBlank(encoding)) {
if(encoding != null && !"".equals(encoding.trim())){
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
// throw new RuntimeException(e);
e.printStackTrace();
return null;
}
}
/**
* 创建UnMarshaller.
*/
public Unmarshaller createUnmarshaller() {
try {
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
// throw new RuntimeException(e);
return null;
}
}
/**
* 封装Root Element 是 Collection的情况.
*/
public static class CollectionWrapper {
// @SuppressWarnings("unchecked")
@SuppressWarnings("rawtypes")
@XmlAnyElement
protected Collection collection;
}
public static String getNodeValue(String xml,String nodeName){
String nodeValue = null;
if(xml != null && xml.length() > 0){
String head = "<"+nodeName+">";
String tail = "</"+nodeName+">";
if(xml.contains(head) && xml.contains(tail)){
int beginIndex = xml.indexOf(head)+head.length();
int endIndex = xml.indexOf(tail);
nodeValue = xml.substring(beginIndex, endIndex);
if(nodeValue != null && nodeValue.length() >0){
if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){
nodeValue = nodeValue.substring(9, nodeValue.length()-3);
}
}
}
}
return nodeValue;
}
public static String format(String str) {
if(str == null || "".equals(str.trim())){
return null;
}
String formatXml = str;
try{
SAXReader reader = new SAXReader();
// System.out.println(reader);
// 注释:创建一个串的字符输入流
StringReader in = new StringReader(str);
Document doc = reader.read(in);
// System.out.println(doc.getRootElement());
// 注释:创建输出格式
OutputFormat formater = OutputFormat.createPrettyPrint();
//formater=OutputFormat.createCompactFormat();
// 注释:设置xml的输出编码
formater.setEncoding("utf-8");
// 注释:创建输出(目标)
StringWriter out = new StringWriter();
// 注释:创建输出流
XMLWriter writer = new XMLWriter(out, formater);
// 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。
writer.write(doc);
writer.close();
// System.out.println(out.toString());
// 注释:返回我们格式化后的结果
formatXml = out.toString();
}catch(Exception e){
e.printStackTrace();
}
return formatXml;
}
public static void main(String[] args){
String xml = ""
+"<xml><return_code><![CDATA[SUCCESS]]></return_code>"
+"<return_msg><![CDATA[OK]]></return_msg>"
+"<appid><![CDATA[wx350e0551f15c891d]]></appid>"
+"<mch_id><![CDATA[1467966602]]></mch_id>"
+"<nonce_str><![CDATA[sIKggVGaBFGavGlA]]></nonce_str>"
+"<sign><![CDATA[845C8A7FF9A0D456DB2E7C8D68B1CAD3]]></sign>"
+"<result_code><![CDATA[SUCCESS]]></result_code>"
+"<prepay_id><![CDATA[wx20170509102930c05e819bdf0584738530]]></prepay_id>"
+"<trade_type><![CDATA[NATIVE]]></trade_type>"
+"<code_url><![CDATA[weixin://wxpay/bizpayurl?pr=FrUICJf]]></code_url>"
+"</xml>";
String nodeName = "result_code";// "return_code";
String nodeValue = null;
if(xml != null && xml.length() > 0){
String head = "<"+nodeName+">";
String tail = "</"+nodeName+">";
if(xml.contains(head) && xml.contains(tail)){
int beginIndex = xml.indexOf(head)+head.length();
int endIndex = xml.indexOf(tail);
nodeValue = xml.substring(beginIndex, endIndex);
if(nodeValue != null && nodeValue.length() >0){
if(nodeValue.startsWith("<![CDATA[") && nodeValue.endsWith("]]>")){
nodeValue = nodeValue.substring(9, nodeValue.length()-3);
}
}
}
}
System.out.println(nodeValue);
}
}
<?xml version="1.0" encoding="UTF-8" ?> <?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" > <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.yd.dal.mapper.meta.MdCodeMapper"> <mapper namespace="com.yd.dal.mapper.meta.MdCodeMapper">
<resultMap id="md_code_result_map" type="com.yd.dal.entity.meta.MdCode"> <resultMap id="BaseResultMap" type="com.yd.dal.entity.meta.MdCode">
<result column="id" property="id"/> <id column="id" jdbcType="BIGINT" property="id" />
<result column="codeType" property="codeType"/> <result column="code_type" jdbcType="VARCHAR" property="codeType" />
<result column="codeCode" property="codeCode" /> <result column="display_no" jdbcType="INTEGER" property="displayNo" />
<result column="codeName" property="codeName"/> <result column="code_code" jdbcType="VARCHAR" property="codeCode" />
<result column="isActive" property="isActive"/> <result column="code_name" jdbcType="VARCHAR" property="codeName" />
<result column="remark" property="remark"/> <result column="code_name_en" jdbcType="VARCHAR" property="codeNameEn" />
<result column="createAt" property="createAt"/> <result column="is_active" jdbcType="INTEGER" property="isActive" />
<result column="flag" jdbcType="VARCHAR" property="flag" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
<result column="created_at" jdbcType="TIMESTAMP" property="createdAt" />
<result column="created_by" jdbcType="BIGINT" property="createdBy" />
<result column="updated_at" jdbcType="TIMESTAMP" property="updatedAt" />
<result column="updated_by" jdbcType="BIGINT" property="updatedBy" />
</resultMap> </resultMap>
<sql id="Base_Column_List">
id, code_type, display_no, code_code, code_name, code_name_en, is_active, flag, remark,
created_at, created_by, updated_at, updated_by
</sql>
<select id="findByCodeType" resultMap="md_code_result_map"> <select id="findByCodeType" resultMap="BaseResultMap">
SELECT select
t.id as id, <include refid="Base_Column_List" />
t.code_type as codeType, from ag_md_code
t.code_code as codeCode,
t.code_name as codeName,
t.is_active as isActive,
t.remark as remark,
t.created_at as creteAt
FROM ag_md_code t
where t.is_active = 1 and t.code_type = #{codeType} where t.is_active = 1 and t.code_type = #{codeType}
</select> </select>
<select id="findCodeByType" resultType="java.lang.String"> <select id="findCodeByType" resultType="java.lang.String">
...@@ -30,4 +34,48 @@ ...@@ -30,4 +34,48 @@
where t.is_active = 1 and t.code_type = #{codeType} where t.is_active = 1 and t.code_type = #{codeType}
</select> </select>
<select id="findByMdCode" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ag_md_code
<where>
<if test="codeType != null">
and code_type = #{codeType,jdbcType=VARCHAR}
</if>
<if test="displayNo != null">
and display_no = #{displayNo,jdbcType=INTEGER}
</if>
<if test="codeCode != null">
and code_code = #{codeCode,jdbcType=VARCHAR}
</if>
<if test="codeName != null">
and code_name = #{codeName,jdbcType=VARCHAR}
</if>
<if test="codeNameEn != null">
and code_name_en = #{codeNameEn,jdbcType=VARCHAR}
</if>
<if test="isActive != null">
and is_active = #{isActive,jdbcType=INTEGER}
</if>
<if test="flag != null">
and flag = #{flag,jdbcType=VARCHAR}
</if>
<if test="remark != null">
and remark = #{remark,jdbcType=VARCHAR}
</if>
<if test="createdAt != null">
and created_at = #{createdAt,jdbcType=TIMESTAMP}
</if>
<if test="createdBy != null">
and created_by = #{createdBy,jdbcType=BIGINT}
</if>
<if test="updatedAt != null">
and updated_at = #{updatedAt,jdbcType=TIMESTAMP}
</if>
<if test="updatedBy != null">
and updated_by = #{updatedBy,jdbcType=BIGINT}
</if>
</where>
</select>
</mapper> </mapper>
\ No newline at end of file
<?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.yd.dal.mapper.tencent.TenInterfRecordMapper">
<resultMap id="BaseResultMap" type="com.yd.dal.entity.tencent.TenInterfRecord">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="interf_type" jdbcType="VARCHAR" property="interfType" />
<result column="appid" jdbcType="VARCHAR" property="appid" />
<result column="secret" jdbcType="VARCHAR" property="secret" />
<result column="code" jdbcType="VARCHAR" property="code" />
<result column="grant_type" jdbcType="VARCHAR" property="grantType" />
<result column="component_appid" jdbcType="VARCHAR" property="componentAppid" />
<result column="component_access_token" jdbcType="VARCHAR" property="componentAccessToken" />
<result column="i_type" jdbcType="VARCHAR" property="iType" />
<result column="access_token" jdbcType="VARCHAR" property="accessToken" />
<result column="expires_in" jdbcType="BIGINT" property="expiresIn" />
<result column="refresh_token" jdbcType="VARCHAR" property="refreshToken" />
<result column="openid" jdbcType="VARCHAR" property="openid" />
<result column="i_scope" jdbcType="VARCHAR" property="iScope" />
<result column="errcode" jdbcType="VARCHAR" property="errcode" />
<result column="errmsg" jdbcType="VARCHAR" property="errmsg" />
<result column="ticket" jdbcType="VARCHAR" property="ticket" />
<result column="created_at" jdbcType="TIMESTAMP" property="createdAt" />
</resultMap>
<sql id="Base_Column_List">
id, interf_type, appid, secret, code, grant_type, component_appid, component_access_token,
i_type, access_token, expires_in, refresh_token, openid, i_scope, errcode, errmsg,
ticket, created_at
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ag_ten_interf_record
where id = #{id,jdbcType=BIGINT}
</select>
<select id="findByTenInterfRecordOrderBy" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ag_ten_interf_record
<where>
<if test="info.id != null">
and id = #{info.id,jdbcType=VARCHAR}
</if>
<if test="info.interfType != null">
and interf_type = #{info.interfType,jdbcType=VARCHAR}
</if>
<if test="info.appid != null">
and appid = #{info.appid,jdbcType=VARCHAR}
</if>
<if test="info.secret != null">
and secret = #{info.secret,jdbcType=VARCHAR}
</if>
<if test="info.code != null">
and code = #{info.code,jdbcType=VARCHAR}
</if>
<if test="info.grantType != null">
and grant_type = #{info.grantType,jdbcType=VARCHAR}
</if>
<if test="info.componentAppid != null">
and component_appid = #{info.componentAppid,jdbcType=VARCHAR}
</if>
<if test="info.componentAccessToken != null">
and component_access_token = #{info.componentAccessToken,jdbcType=VARCHAR}
</if>
<if test="info.iType != null">
and i_type = #{info.iType,jdbcType=VARCHAR}
</if>
<if test="info.accessToken != null">
and access_token = #{info.accessToken,jdbcType=VARCHAR}
</if>
<if test="info.expiresIn != null">
and expires_in = #{info.expiresIn,jdbcType=BIGINT}
</if>
<if test="info.refreshToken != null">
and refresh_token = #{info.refreshToken,jdbcType=VARCHAR}
</if>
<if test="info.openid != null">
and openid = #{info.openid,jdbcType=VARCHAR}
</if>
<if test="info.iScope != null">
and i_scope = #{info.iScope,jdbcType=VARCHAR}
</if>
<if test="info.errcode != null">
and errcode = #{info.errcode,jdbcType=VARCHAR}
</if>
<if test="info.errmsg != null">
and errmsg = #{info.errmsg,jdbcType=VARCHAR}
</if>
<if test="info.ticket != null">
and ticket = #{info.ticket,jdbcType=VARCHAR}
</if>
<if test="info.createdAt != null">
and created_at = #{info.createdAt,jdbcType=TIMESTAMP}
</if>
</where>
<if test="orderBy != null ">
order by ${orderBy}
</if>
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from ag_ten_interf_record
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.yd.dal.entity.tencent.TenInterfRecord" useGeneratedKeys="true">
insert into ag_ten_interf_record (interf_type, appid, secret,
code, grant_type, component_appid,
component_access_token, i_type, access_token,
expires_in, refresh_token, openid,
i_scope, errcode, errmsg,
ticket, created_at)
values (#{interfType,jdbcType=VARCHAR}, #{appid,jdbcType=VARCHAR}, #{secret,jdbcType=VARCHAR},
#{code,jdbcType=VARCHAR}, #{grantType,jdbcType=VARCHAR}, #{componentAppid,jdbcType=VARCHAR},
#{componentAccessToken,jdbcType=VARCHAR}, #{iType,jdbcType=VARCHAR}, #{accessToken,jdbcType=VARCHAR},
#{expiresIn,jdbcType=BIGINT}, #{refreshToken,jdbcType=VARCHAR}, #{openid,jdbcType=VARCHAR},
#{iScope,jdbcType=VARCHAR}, #{errcode,jdbcType=VARCHAR}, #{errmsg,jdbcType=VARCHAR},
#{ticket,jdbcType=VARCHAR}, #{createdAt,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.yd.dal.entity.tencent.TenInterfRecord" useGeneratedKeys="true">
insert into ag_ten_interf_record
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="interfType != null">
interf_type,
</if>
<if test="appid != null">
appid,
</if>
<if test="secret != null">
secret,
</if>
<if test="code != null">
code,
</if>
<if test="grantType != null">
grant_type,
</if>
<if test="componentAppid != null">
component_appid,
</if>
<if test="componentAccessToken != null">
component_access_token,
</if>
<if test="iType != null">
i_type,
</if>
<if test="accessToken != null">
access_token,
</if>
<if test="expiresIn != null">
expires_in,
</if>
<if test="refreshToken != null">
refresh_token,
</if>
<if test="openid != null">
openid,
</if>
<if test="iScope != null">
i_scope,
</if>
<if test="errcode != null">
errcode,
</if>
<if test="errmsg != null">
errmsg,
</if>
<if test="ticket != null">
ticket,
</if>
<if test="createdAt != null">
created_at,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="interfType != null">
#{interfType,jdbcType=VARCHAR},
</if>
<if test="appid != null">
#{appid,jdbcType=VARCHAR},
</if>
<if test="secret != null">
#{secret,jdbcType=VARCHAR},
</if>
<if test="code != null">
#{code,jdbcType=VARCHAR},
</if>
<if test="grantType != null">
#{grantType,jdbcType=VARCHAR},
</if>
<if test="componentAppid != null">
#{componentAppid,jdbcType=VARCHAR},
</if>
<if test="componentAccessToken != null">
#{componentAccessToken,jdbcType=VARCHAR},
</if>
<if test="iType != null">
#{iType,jdbcType=VARCHAR},
</if>
<if test="accessToken != null">
#{accessToken,jdbcType=VARCHAR},
</if>
<if test="expiresIn != null">
#{expiresIn,jdbcType=BIGINT},
</if>
<if test="refreshToken != null">
#{refreshToken,jdbcType=VARCHAR},
</if>
<if test="openid != null">
#{openid,jdbcType=VARCHAR},
</if>
<if test="iScope != null">
#{iScope,jdbcType=VARCHAR},
</if>
<if test="errcode != null">
#{errcode,jdbcType=VARCHAR},
</if>
<if test="errmsg != null">
#{errmsg,jdbcType=VARCHAR},
</if>
<if test="ticket != null">
#{ticket,jdbcType=VARCHAR},
</if>
<if test="createdAt != null">
#{createdAt,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.yd.dal.entity.tencent.TenInterfRecord">
update ag_ten_interf_record
<set>
<if test="interfType != null">
interf_type = #{interfType,jdbcType=VARCHAR},
</if>
<if test="appid != null">
appid = #{appid,jdbcType=VARCHAR},
</if>
<if test="secret != null">
secret = #{secret,jdbcType=VARCHAR},
</if>
<if test="code != null">
code = #{code,jdbcType=VARCHAR},
</if>
<if test="grantType != null">
grant_type = #{grantType,jdbcType=VARCHAR},
</if>
<if test="componentAppid != null">
component_appid = #{componentAppid,jdbcType=VARCHAR},
</if>
<if test="componentAccessToken != null">
component_access_token = #{componentAccessToken,jdbcType=VARCHAR},
</if>
<if test="iType != null">
i_type = #{iType,jdbcType=VARCHAR},
</if>
<if test="accessToken != null">
access_token = #{accessToken,jdbcType=VARCHAR},
</if>
<if test="expiresIn != null">
expires_in = #{expiresIn,jdbcType=BIGINT},
</if>
<if test="refreshToken != null">
refresh_token = #{refreshToken,jdbcType=VARCHAR},
</if>
<if test="openid != null">
openid = #{openid,jdbcType=VARCHAR},
</if>
<if test="iScope != null">
i_scope = #{iScope,jdbcType=VARCHAR},
</if>
<if test="errcode != null">
errcode = #{errcode,jdbcType=VARCHAR},
</if>
<if test="errmsg != null">
errmsg = #{errmsg,jdbcType=VARCHAR},
</if>
<if test="ticket != null">
ticket = #{ticket,jdbcType=VARCHAR},
</if>
<if test="createdAt != null">
created_at = #{createdAt,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.yd.dal.entity.tencent.TenInterfRecord">
update ag_ten_interf_record
set interf_type = #{interfType,jdbcType=VARCHAR},
appid = #{appid,jdbcType=VARCHAR},
secret = #{secret,jdbcType=VARCHAR},
code = #{code,jdbcType=VARCHAR},
grant_type = #{grantType,jdbcType=VARCHAR},
component_appid = #{componentAppid,jdbcType=VARCHAR},
component_access_token = #{componentAccessToken,jdbcType=VARCHAR},
i_type = #{iType,jdbcType=VARCHAR},
access_token = #{accessToken,jdbcType=VARCHAR},
expires_in = #{expiresIn,jdbcType=BIGINT},
refresh_token = #{refreshToken,jdbcType=VARCHAR},
openid = #{openid,jdbcType=VARCHAR},
i_scope = #{iScope,jdbcType=VARCHAR},
errcode = #{errcode,jdbcType=VARCHAR},
errmsg = #{errmsg,jdbcType=VARCHAR},
ticket = #{ticket,jdbcType=VARCHAR},
created_at = #{createdAt,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
\ No newline at end of file
<?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.yd.dal.mapper.transaction.TranLogMapper">
<resultMap id="BaseResultMap" type="com.yd.dal.entity.transaction.TranLog">
<id column="id" jdbcType="BIGINT" property="id" />
<result column="category" jdbcType="VARCHAR" property="category" />
<result column="type" jdbcType="VARCHAR" property="type" />
<result column="tran_no" jdbcType="VARCHAR" property="tranNo" />
<result column="in_or_out" jdbcType="VARCHAR" property="inOrOut" />
<result column="yd_code" jdbcType="VARCHAR" property="ydCode" />
<result column="return_code" jdbcType="VARCHAR" property="returnCode" />
<result column="return_message" jdbcType="VARCHAR" property="returnMessage" />
<result column="tran_xml" jdbcType="VARCHAR" property="tranXml" />
<result column="remark" jdbcType="VARCHAR" property="remark" />
<result column="create_date" jdbcType="TIMESTAMP" property="createDate" />
<result column="updated_date" jdbcType="TIMESTAMP" property="updatedDate" />
</resultMap>
<sql id="Base_Column_List">
id, category, `type`, tran_no, in_or_out, yd_code, return_code, return_message, tran_xml,
remark, create_date, updated_date
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_tran_log
where id = #{id,jdbcType=BIGINT}
</select>
<select id="findByTranLogOrderBy" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_tran_log
<where>
<if test="info.id != null">
and id = #{info.id,jdbcType=VARCHAR}
</if>
<if test="info.category != null">
and category = #{info.category,jdbcType=VARCHAR}
</if>
<if test="info.type != null">
and `type` = #{info.type,jdbcType=VARCHAR}
</if>
<if test="info.tranNo != null">
and tran_no = #{info.tranNo,jdbcType=VARCHAR}
</if>
<if test="info.inOrOut != null">
and in_or_out = #{info.inOrOut,jdbcType=VARCHAR}
</if>
<if test="info.ydCode != null">
and yd_code = #{info.ydCode,jdbcType=VARCHAR}
</if>
<if test="info.returnCode != null">
and return_code = #{info.returnCode,jdbcType=VARCHAR}
</if>
<if test="info.returnMessage != null">
and return_message = #{info.returnMessage,jdbcType=VARCHAR}
</if>
<if test="info.tranXml != null">
and tran_xml = #{info.tranXml,jdbcType=VARCHAR}
</if>
<if test="info.remark != null">
and remark = #{info.remark,jdbcType=VARCHAR}
</if>
<if test="info.createDate != null">
and create_date = #{info.createDate,jdbcType=TIMESTAMP}
</if>
<if test="info.updatedDate != null">
and updated_date = #{info.updatedDate,jdbcType=TIMESTAMP}
</if>
</where>
<if test="orderBy != null">
order by ${orderBy}
</if>
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_tran_log
where id = #{id,jdbcType=BIGINT}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.yd.dal.entity.transaction.TranLog" useGeneratedKeys="true">
insert into t_tran_log (category, `type`, tran_no,
in_or_out, yd_code, return_code,
return_message, tran_xml, remark,
create_date, updated_date)
values (#{category,jdbcType=VARCHAR}, #{type,jdbcType=VARCHAR}, #{tranNo,jdbcType=VARCHAR},
#{inOrOut,jdbcType=VARCHAR}, #{ydCode,jdbcType=VARCHAR}, #{returnCode,jdbcType=VARCHAR},
#{returnMessage,jdbcType=VARCHAR}, #{tranXml,jdbcType=VARCHAR}, #{remark,jdbcType=VARCHAR},
#{createDate,jdbcType=TIMESTAMP}, #{updatedDate,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.yd.dal.entity.transaction.TranLog" useGeneratedKeys="true">
insert into t_tran_log
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="category != null">
category,
</if>
<if test="type != null">
`type`,
</if>
<if test="tranNo != null">
tran_no,
</if>
<if test="inOrOut != null">
in_or_out,
</if>
<if test="ydCode != null">
yd_code,
</if>
<if test="returnCode != null">
return_code,
</if>
<if test="returnMessage != null">
return_message,
</if>
<if test="tranXml != null">
tran_xml,
</if>
<if test="remark != null">
remark,
</if>
<if test="createDate != null">
create_date,
</if>
<if test="updatedDate != null">
updated_date,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="category != null">
#{category,jdbcType=VARCHAR},
</if>
<if test="type != null">
#{type,jdbcType=VARCHAR},
</if>
<if test="tranNo != null">
#{tranNo,jdbcType=VARCHAR},
</if>
<if test="inOrOut != null">
#{inOrOut,jdbcType=VARCHAR},
</if>
<if test="ydCode != null">
#{ydCode,jdbcType=VARCHAR},
</if>
<if test="returnCode != null">
#{returnCode,jdbcType=VARCHAR},
</if>
<if test="returnMessage != null">
#{returnMessage,jdbcType=VARCHAR},
</if>
<if test="tranXml != null">
#{tranXml,jdbcType=VARCHAR},
</if>
<if test="remark != null">
#{remark,jdbcType=VARCHAR},
</if>
<if test="createDate != null">
#{createDate,jdbcType=TIMESTAMP},
</if>
<if test="updatedDate != null">
#{updatedDate,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.yd.dal.entity.transaction.TranLog">
update t_tran_log
<set>
<if test="category != null">
category = #{category,jdbcType=VARCHAR},
</if>
<if test="type != null">
`type` = #{type,jdbcType=VARCHAR},
</if>
<if test="tranNo != null">
tran_no = #{tranNo,jdbcType=VARCHAR},
</if>
<if test="inOrOut != null">
in_or_out = #{inOrOut,jdbcType=VARCHAR},
</if>
<if test="ydCode != null">
yd_code = #{ydCode,jdbcType=VARCHAR},
</if>
<if test="returnCode != null">
return_code = #{returnCode,jdbcType=VARCHAR},
</if>
<if test="returnMessage != null">
return_message = #{returnMessage,jdbcType=VARCHAR},
</if>
<if test="tranXml != null">
tran_xml = #{tranXml,jdbcType=VARCHAR},
</if>
<if test="remark != null">
remark = #{remark,jdbcType=VARCHAR},
</if>
<if test="createDate != null">
create_date = #{createDate,jdbcType=TIMESTAMP},
</if>
<if test="updatedDate != null">
updated_date = #{updatedDate,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=BIGINT}
</update>
<update id="updateByPrimaryKey" parameterType="com.yd.dal.entity.transaction.TranLog">
update t_tran_log
set category = #{category,jdbcType=VARCHAR},
`type` = #{type,jdbcType=VARCHAR},
tran_no = #{tranNo,jdbcType=VARCHAR},
in_or_out = #{inOrOut,jdbcType=VARCHAR},
yd_code = #{ydCode,jdbcType=VARCHAR},
return_code = #{returnCode,jdbcType=VARCHAR},
return_message = #{returnMessage,jdbcType=VARCHAR},
tran_xml = #{tranXml,jdbcType=VARCHAR},
remark = #{remark,jdbcType=VARCHAR},
create_date = #{createDate,jdbcType=TIMESTAMP},
updated_date = #{updatedDate,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=BIGINT}
</update>
</mapper>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment