记得上下班打卡 | git大法好,push需谨慎

Commit c17b0f74 authored by jiangxiulong's avatar jiangxiulong

Merge remote-tracking branch 'origin/dev' into dev

parents 53b111d2 9c322356
......@@ -15,21 +15,40 @@ public class DragonConstant {
public static final String REFUND_TYPE_JS_WEPAY="JSWEPAY";//,"微信内网页、微信公众号"),
public static final String REFUND_TYPE_APPLET_WEPAY="APPLETWEPAY";//,"微信小程序");
public enum payChannelEnum{
public enum PayChannelEnum{
ALIPAY("alipay","支付宝"),
WEPAY ("wePay","微信"),
CLOUDPAY("cloudPay","云闪付");
WEPAY ("wepay","微信"),
APPLEPAY ("applepay","applepay"),
CLOUDPAY("cloudpay","云闪付");
private String code;
private String message;
payChannelEnum(String code, String message) {
PayChannelEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
}
public enum DeviceFromEnum{
WEB("web",""),WAP("wap","")
,APP("app",""),JS("js",""),APPLE("apple","");
private String code;
private String message;
DeviceFromEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
}
/**
* 支付状态
*/
public enum payStatusEnum{
public enum PayStatusEnum{
STATUS_UNPAID("0","未支付,或支付中"),
STATUS_PAID("1","已支付"),
STATUS_SUCCESS("2","已支付,通知成功,交易结束"),
......@@ -38,16 +57,30 @@ public class DragonConstant {
private String code;
private String message;
payStatusEnum(String code, String message) {
PayStatusEnum(String code, String message) {
this.code = code;
this.message = message;
}
public PayStatusEnum getEnumByCode(String code){
PayStatusEnum[] arry = PayStatusEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].getCode().equals(code)) {
return arry[i];
}
}
return null;
}
public String getCode() {
return code;
}
}
/**
* 退款状态
*/
public enum refundStatusEnum{
public enum RefundStatusEnum{
STATUS_UNFILLED("0","未处理"),
STATUS_REFUNDED("1","退款成功"),
STATUS_SUCCESS("2","退款成功,通知成功,交易结束"),
......@@ -61,7 +94,7 @@ public class DragonConstant {
private String code;
private String message;
refundStatusEnum(String code, String message) {
RefundStatusEnum(String code, String message) {
this.code = code;
this.message = message;
}
......@@ -74,7 +107,7 @@ public class DragonConstant {
/**
* 支付业务类型
*/
public enum bussinessTypeEnum{
public enum BussinessTypeEnum{
TYPE_TICKET("TICKET","票务购买(实物购买)"),
TYPE_PRODUCT("PRODUCT","商品购买(实物购买)"),
TYPE_COST("COST","活动资费(活动成本费、活动报名费)"),
......@@ -87,16 +120,20 @@ public class DragonConstant {
private String code;
private String message;
bussinessTypeEnum(String code, String message) {
BussinessTypeEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
}
/**
* 支付类型
*/
public enum payTypeEnum{
public enum PayTypeEnum{
PAYMENT_TYPE_APP_ALIPAY("APPALIPAY","App内支付宝支付"),
PAYMENT_TYPE_APP_WEPAY("APPWEPAY","App内微信支付"),
PAYMENT_TYPE_APP_IAP("APPIAP","App内IAP(In-App Purchase)支付,iOS虚拟道具支付"),
......@@ -109,16 +146,20 @@ public class DragonConstant {
private String code;
private String message;
payTypeEnum(String code, String message) {
PayTypeEnum(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
}
/**
* 退款类型
*/
public enum refundTypeEnum{
public enum RefundTypeEnum{
REFUND_TYPE_APP_ALIPAY("APPALIPAY","App内支付宝支付"),
REFUND_TYPE_APP_WEPAY("APPWEPAY","App内微信支付"),
REFUND_TYPE_APP_IAP("APPIAP","App内IAP(In-App Purchase)支付,iOS虚拟道具支付"),
......@@ -131,7 +172,7 @@ public class DragonConstant {
private String code;
private String message;
refundTypeEnum(String code, String message) {
RefundTypeEnum(String code, String message) {
this.code = code;
this.message = message;
}
......@@ -144,14 +185,14 @@ public class DragonConstant {
/**
* MYSQL_REDIS_QUEUE
*/
public enum mysqlRedisQueueEnum{
public enum MysqlRedisQueueEnum{
DRAGON_PAY_KEY("dragon-pay","同步数据-支付"),
DRAGON_REFUND_KEY ("dragon-refund","同步数据-退款"),
DRAGON_PAY_GROUP("dragon-pay-group","同步数据-支付-组"),
DRAGON_REFUND_GROUP ("dragon-refund-group","同步数据-退款-组");
private String code;
private String message;
mysqlRedisQueueEnum(String code, String message) {
MysqlRedisQueueEnum(String code, String message) {
this.code = code;
this.message = message;
}
......@@ -164,7 +205,7 @@ public class DragonConstant {
/**
* CHANNEL_REDIS_QUEUE
*/
public enum channelRedisQueueEnum{
public enum ChannelRedisQueueEnum{
WECHAT_PAY_KEY("wechat-pay","微信-支付-回调"),
WECHAT_REFUND_KEY("wechat-pay","微信-退款-回调"),
ALIPAY_PAY_KEY("alipay-pay","支付宝-支付-回调"),
......@@ -175,7 +216,7 @@ public class DragonConstant {
ALIPAY_REFUND_GROUP ("alipay-refund-group","支付宝-退款-回调-组");
private String code;
private String message;
channelRedisQueueEnum(String code, String message) {
ChannelRedisQueueEnum(String code, String message) {
this.code = code;
this.message = message;
}
......@@ -184,7 +225,7 @@ public class DragonConstant {
/**
* CHANNEL_REFUND_URL
*/
public enum channelRefundUrlEnum{
public enum ChannelRefundUrlEnum{
JSAPI_REFUND_URL("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds","JSAPI-退款-接口"),
APP_REFUND_URL("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds","APP-退款-接口"),
H5_REFUND_URL("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds","H5-退款-接口"),
......@@ -192,7 +233,7 @@ public class DragonConstant {
MCH_REFUND_URL("https://api.mch.weixin.qq.com/v3/refund/domestic/refunds","小程序-退款-接口");
private String code;
private String message;
channelRefundUrlEnum(String code, String message) {
ChannelRefundUrlEnum(String code, String message) {
this.code = code;
this.message = message;
}
......
package com.liquidnet.service.dragon.dto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
......@@ -13,11 +15,10 @@ import javax.validation.constraints.NotNull;
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/9 10:56
*/
@Data
public class DragonPayBaseReqDto {
@ApiModelProperty(position = 14, required = true, value = "性别[32]", example = "{\"val\":\"MS00\",\"desc\":\"其他性别\"}")
@NotNull(message = "性别不能为空")
private String type;
private String price;
private BigDecimal price;
private String name;
private String detail;
private String orderCode;
......
package com.liquidnet.service.dragon.service;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import com.liquidnet.service.dragon.dto.DragonRefundAppDto;
import java.math.BigDecimal;
public interface IDragonOrdersService {
void sendRedisQueue();
ResponseDto<DragonPayBaseRespDto> alipay(DragonPayBaseReqDto dragonPayBaseReqDto);
}
......@@ -47,11 +47,12 @@ public class IDGenerator {
return orderCode;
}
public static String payCode(){
return "PAY"+nextTimeId();
}
public static String refundCode(){
String refundCode = System.currentTimeMillis()+"";
int randomCode = RandomUtil.getRandomInt(0,10000);
StringUtils.leftPad(refundCode, 3, "0");
return refundCode.concat(StringUtils.leftPad(randomCode+"", (randomCode/10), "0")+"R");
return "RED"+nextTimeId();
}
/**
......@@ -64,4 +65,9 @@ public class IDGenerator {
String qrCode = MD5Utils.md5(orderTicketId).toLowerCase();
return "QR" + qrCode.substring(5) + "" + qrCode.substring(0, 4);
}
public static void main(String[] args) {
System.out.println(IDGenerator.payCode());
System.out.println(IDGenerator.refundCode());
}
}
......@@ -22,3 +22,5 @@ liquidnet:
mongodb:
sslEnabled: false
database: dev_ln_scene
dragon:
alipay-gataway-url: https://openapi.alipay.com/gateway.do
......@@ -92,4 +92,9 @@ public class DragonOrders implements Serializable {
*/
private LocalDateTime updatedAt;
/**
* deleted_at
*/
private LocalDateTime deletedAt;
}
......@@ -32,8 +32,8 @@ public class RedisStreamConfig {
.pollTimeout(Duration.ofMillis(1))
.build();
var listenerContainer = StreamMessageListenerContainer.create(factory, options);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.mysqlRedisQueueEnum.DRAGON_PAY_GROUP.getCode(), "dragon-pay-0"),
StreamOffset.create(DragonConstant.mysqlRedisQueueEnum.DRAGON_PAY_KEY.getCode(), ReadOffset.lastConsumed()), redisPayReceiver);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.MysqlRedisQueueEnum.DRAGON_PAY_GROUP.getCode(), "dragon-pay-0"),
StreamOffset.create(DragonConstant.MysqlRedisQueueEnum.DRAGON_PAY_KEY.getCode(), ReadOffset.lastConsumed()), redisPayReceiver);
listenerContainer.start();
return subscription;
}
......@@ -46,8 +46,8 @@ public class RedisStreamConfig {
.pollTimeout(Duration.ofMillis(1))
.build();
var listenerContainer = StreamMessageListenerContainer.create(factory, options);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.mysqlRedisQueueEnum.DRAGON_PAY_GROUP.getCode(), "dragon-pay-1"),
StreamOffset.create(DragonConstant.mysqlRedisQueueEnum.DRAGON_PAY_KEY.getCode(), ReadOffset.lastConsumed()), redisPayReceiver);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.MysqlRedisQueueEnum.DRAGON_PAY_GROUP.getCode(), "dragon-pay-1"),
StreamOffset.create(DragonConstant.MysqlRedisQueueEnum.DRAGON_PAY_KEY.getCode(), ReadOffset.lastConsumed()), redisPayReceiver);
listenerContainer.start();
return subscription;
}
......@@ -60,8 +60,8 @@ public class RedisStreamConfig {
.pollTimeout(Duration.ofMillis(1))
.build();
var listenerContainer = StreamMessageListenerContainer.create(factory, options);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_GROUP.getCode(), "dragon-refund-0"),
StreamOffset.create(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode(), ReadOffset.lastConsumed()), redisRefundReceiver);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_GROUP.getCode(), "dragon-refund-0"),
StreamOffset.create(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode(), ReadOffset.lastConsumed()), redisRefundReceiver);
listenerContainer.start();
return subscription;
}
......@@ -74,8 +74,8 @@ public class RedisStreamConfig {
.pollTimeout(Duration.ofMillis(1))
.build();
var listenerContainer = StreamMessageListenerContainer.create(factory, options);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_GROUP.getCode(), "dragon-refund-1"),
StreamOffset.create(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode(), ReadOffset.lastConsumed()), redisRefundReceiver);
var subscription = listenerContainer.receiveAutoAck(Consumer.from(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_GROUP.getCode(), "dragon-refund-1"),
StreamOffset.create(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode(), ReadOffset.lastConsumed()), redisRefundReceiver);
listenerContainer.start();
return subscription;
}
......
......@@ -31,14 +31,11 @@ public class BaseDao implements IBaseDao {
@Override
public Boolean batchSql(final String sql, final LinkedList<Object[]> values) {
TransactionCallback<Boolean> callback = new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(final TransactionStatus transactionStatus) {
if (values.size() > 0) {
int[] ints = jdbcTemplate.batchUpdate(sql, values);
}
return true;
TransactionCallback<Boolean> callback = transactionStatus -> {
if (values.size() > 0) {
int[] ints = jdbcTemplate.batchUpdate(sql, values);
}
return true;
};
try {
TransactionTemplate tt = new TransactionTemplate(transactionManager);
......@@ -53,31 +50,24 @@ public class BaseDao implements IBaseDao {
public Boolean batchSqls(final LinkedList<String> sql,
final LinkedList<Object[]>... values) {
try {
TransactionCallback<Boolean> callback = new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(final TransactionStatus transactionStatus) {
int i = 0;
for (LinkedList<Object[]> o : values) {
if (sql.size() < i + 1) {
break;
}
if (!o.isEmpty()) {
jdbcTemplate.batchUpdate(sql.get(i), o);
}
i++;
TransactionCallback<Boolean> callback = transactionStatus -> {
int i = 0;
for (LinkedList<Object[]> o : values) {
if (sql.size() < i + 1) {
break;
}
if (!o.isEmpty()) {
jdbcTemplate.batchUpdate(sql.get(i), o);
}
return true;
i++;
}
return true;
};
TransactionTemplate tt = new TransactionTemplate(transactionManager);
return tt.execute(callback);
} catch (Exception ex) {
// if (ex instanceof LiquidnetServiceException) {
// log.error("###Error.Code:{} - {}", ((LiquidnetServiceException) ex).getCode(), ex.getMessage());
// } else {
log.error("###Error.Sqls:{}\nParameters:{},Ex:{}", JsonUtils.toJson(sql), JsonUtils.toJson(values), ex.getMessage());
// }
return false;
}
}
......@@ -85,14 +75,11 @@ public class BaseDao implements IBaseDao {
@Override
public Boolean batchSqlNoArgs(final LinkedList<String> sql) {
try {
TransactionCallback<Boolean> callback = new TransactionCallback<Boolean>() {
@Override
public Boolean doInTransaction(final TransactionStatus transactionStatus) {
for (String o : sql) {
jdbcTemplate.execute(o);
}
return true;
TransactionCallback<Boolean> callback = transactionStatus -> {
for (String o : sql) {
jdbcTemplate.execute(o);
}
return true;
};
TransactionTemplate tt = new TransactionTemplate(transactionManager);
......@@ -115,18 +102,14 @@ public class BaseDao implements IBaseDao {
final Object[] innerO = param;
KeyHolder keyHolder = new GeneratedKeyHolder();
try {
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(innersql,
Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < innerO.length; i++) {
ps.setObject(i + 1, innerO[i]);
}
return ps;
jdbcTemplate.update(con -> {
PreparedStatement ps = con.prepareStatement(innersql,
Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < innerO.length; i++) {
ps.setObject(i + 1, innerO[i]);
}
return ps;
}, keyHolder);
} catch (Exception e) {
log.error("###\nSQL.Preparing:{}\nParameters:{}", sql, JsonUtils.toJson(param), e);
......
......@@ -26,100 +26,72 @@ import java.io.IOException;
@Slf4j
@Component
public class ConsumerAdamUCenterProcessor {
@Resource
IBaseDao baseDao;
// @RabbitListener(bindings = @QueueBinding(
// exchange = @Exchange(MQConst.EXCHANGES_LIQUIDNET_SQL), key = MQConst.ROUTING_KEY_SQL,
// value = @Queue(MQConst.QUEUES_SQL_MAIN)
// ))
//// @RabbitListener(queues = MQConst.QUEUES_SQL_MAIN)
// public void consumerSql(Message msg, Channel channel) {
// @Resource
// IBaseDao baseDao;
//
// private void consumerSqlDaoHandler(Message msg, Channel channel) {
// MessageProperties properties = msg.getMessageProperties();
// String consumerQueue = properties.getConsumerQueue();
// long deliveryTag = properties.getDeliveryTag();
// log.info("CONSUMER SQL ==> [consumerQueue:{},deliveryTag:{}]", consumerQueue, deliveryTag);
// SqlMapping.SqlMessage sqlMessage = JsonUtils.fromJson(new String(msg.getBody()), SqlMapping.SqlMessage.class);
// log.debug("CONSUMER SQL ==> Preparing:{}", JsonUtils.toJson(sqlMessage.getSqls()));
// log.debug("CONSUMER SQL ==> Parameters:{}", JsonUtils.toJson(sqlMessage.getArgs()));
//
// try {
// Boolean rstBatchSqls = baseDao.batchSqls(sqlMessage.getSqls(), sqlMessage.getArgs());
// log.debug("CONSUMER SQL result of execution:{}", rstBatchSqls);
// if (rstBatchSqls) {
// channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
// channel.basicAck(deliveryTag, false);
// } else {
// channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
// }
// } catch (Exception e) {
// log.error("error:CONSUMER SQL:{}", JsonUtils.toJson(sqlMessage), e);
// try {
// channel.basicReject(msg.getMessageProperties().getDeliveryTag(), true);
// } catch (IOException ioException) {
// log.error("error:CONSUMER SQL:basicReject.msg.tag:{}", msg.getMessageProperties().getDeliveryTag(), ioException);
// log.warn("###CONSUMER SQL[consumerQueue:{},deliveryTag={},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage));
// channel.basicAck(deliveryTag, false);
// }
// } catch (IOException e) {
// log.error("CONSUMER SQL[consumerQueue:{},deliveryTag:{},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage), e);
// }
// }
private void consumerSqlDaoHandler(Message msg, Channel channel) {
MessageProperties properties = msg.getMessageProperties();
String consumerQueue = properties.getConsumerQueue();
long deliveryTag = properties.getDeliveryTag();
log.info("CONSUMER SQL ==> [consumerQueue:{},deliveryTag:{}]", consumerQueue, deliveryTag);
SqlMapping.SqlMessage sqlMessage = JsonUtils.fromJson(new String(msg.getBody()), SqlMapping.SqlMessage.class);
log.debug("CONSUMER SQL ==> Preparing:{}", JsonUtils.toJson(sqlMessage.getSqls()));
log.debug("CONSUMER SQL ==> Parameters:{}", JsonUtils.toJson(sqlMessage.getArgs()));
try {
Boolean rstBatchSqls = baseDao.batchSqls(sqlMessage.getSqls(), sqlMessage.getArgs());
log.debug("CONSUMER SQL result of execution:{}", rstBatchSqls);
if (rstBatchSqls) {
channel.basicAck(deliveryTag, false);
} else {
log.warn("###CONSUMER SQL[consumerQueue:{},deliveryTag={},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage));
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
log.error("CONSUMER SQL[consumerQueue:{},deliveryTag:{},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage), e);
}
}
/* ================================================================== | 用户注册 */
@RabbitListener(
bindings = @QueueBinding(
exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
key = MQConst.RK_SQL_UREGISTER,
value = @Queue(MQConst.QUEUES_SQL_UREGISTER)
),
concurrency = "5"
)
public void consumerSqlForURegister(Message msg, Channel channel) {
this.consumerSqlDaoHandler(msg, channel);
}
/* ================================================================== | 用户信息 */
@RabbitListener(
bindings = @QueueBinding(
exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
key = MQConst.RK_SQL_UCENTER,
value = @Queue(MQConst.QUEUES_SQL_UCENTER)
),
concurrency = "5"
)
public void consumerSqlForUCenter(Message msg, Channel channel) {
this.consumerSqlDaoHandler(msg, channel);
}
/* ================================================================== | 会员购买 */
@RabbitListener(
bindings = @QueueBinding(
exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
key = MQConst.RK_SQL_UMEMBER,
value = @Queue(MQConst.QUEUES_SQL_UMEMBER)
),
concurrency = "5"
)
public void consumerSqlForUMember(Message msg, Channel channel) {
this.consumerSqlDaoHandler(msg, channel);
}
//
// /* ================================================================== | 用户注册 */
//
// @RabbitListener(
// bindings = @QueueBinding(
// exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
// key = MQConst.RK_SQL_UREGISTER,
// value = @Queue(MQConst.QUEUES_SQL_UREGISTER)
// ),
// concurrency = "5"
// )
// public void consumerSqlForURegister(Message msg, Channel channel) {
// this.consumerSqlDaoHandler(msg, channel);
// }
//
// /* ================================================================== | 用户信息 */
//
// @RabbitListener(
// bindings = @QueueBinding(
// exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
// key = MQConst.RK_SQL_UCENTER,
// value = @Queue(MQConst.QUEUES_SQL_UCENTER)
// ),
// concurrency = "5"
// )
// public void consumerSqlForUCenter(Message msg, Channel channel) {
// this.consumerSqlDaoHandler(msg, channel);
// }
//
// /* ================================================================== | 会员购买 */
//
// @RabbitListener(
// bindings = @QueueBinding(
// exchange = @Exchange(MQConst.EX_LNS_SQL_UCENTER),
// key = MQConst.RK_SQL_UMEMBER,
// value = @Queue(MQConst.QUEUES_SQL_UMEMBER)
// ),
// concurrency = "5"
// )
// public void consumerSqlForUMember(Message msg, Channel channel) {
// this.consumerSqlDaoHandler(msg, channel);
// }
/* ================================================================== | */
}
package com.liquidnet.service.consumer.dragon.service.processor;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.consumer.dragon.service.IBaseDao;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: ConsumerPayProcessor
* @Package com.liquidnet.service.consumer.dragon.service.processor
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/8 10:59
*/
@Slf4j
@Component
public class ConsumerPayProcessor implements StreamListener<String, MapRecord<String, String, String>> {
@Resource
IBaseDao baseDao;
@Override
public void onMessage(MapRecord<String, String, String> message) {
log.info("接受到来自redis PAY 的消息");
System.out.println("message id "+message.getId());
System.out.println("stream "+message.getStream());
System.out.println("body "+message.getValue());
}
private void consumerSqlDaoHandler(Message msg, Channel channel) {
MessageProperties properties = msg.getMessageProperties();
String consumerQueue = properties.getConsumerQueue();
long deliveryTag = properties.getDeliveryTag();
log.info("CONSUMER SQL ==> [consumerQueue:{},deliveryTag:{}]", consumerQueue, deliveryTag);
SqlMapping.SqlMessage sqlMessage = JsonUtils.fromJson(new String(msg.getBody()), SqlMapping.SqlMessage.class);
log.debug("CONSUMER SQL ==> Preparing:{}", JsonUtils.toJson(sqlMessage.getSqls()));
log.debug("CONSUMER SQL ==> Parameters:{}", JsonUtils.toJson(sqlMessage.getArgs()));
try {
Boolean rstBatchSqls = baseDao.batchSqls(sqlMessage.getSqls(), sqlMessage.getArgs());
log.debug("CONSUMER SQL result of execution:{}", rstBatchSqls);
if (rstBatchSqls) {
channel.basicAck(deliveryTag, false);
} else {
log.warn("###CONSUMER SQL[consumerQueue:{},deliveryTag={},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage));
channel.basicAck(deliveryTag, false);
}
} catch (IOException e) {
log.error("CONSUMER SQL[consumerQueue:{},deliveryTag:{},sqlMessage:{}]", consumerQueue, deliveryTag, JsonUtils.toJson(sqlMessage), e);
}
}
}
package com.liquidnet.service.consumer.dragon.service.processor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: ConsumerRefundProcessor
* @Package com.liquidnet.service.consumer.dragon.service.processor
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/8 10:59
*/
@Slf4j
@Component
public class ConsumerRefundProcessor implements StreamListener<String, MapRecord<String, String, String>> {
@Override
public void onMessage(MapRecord<String, String, String> message) {
log.info("接受到来自redis REFUND 的消息");
System.out.println("message id "+message.getId());
System.out.println("stream "+message.getStream());
System.out.println("body "+message.getValue());
}
}
......@@ -61,7 +61,7 @@ public class RedisRefundReceiver implements StreamListener<String, MapRecord<Str
try {
HashMap<String, String> map = new HashMap<>();
map.put("message", msg);
MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode());
MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode());
stringRedisTemplate.opsForStream().add(record);
return true;
} catch (Exception e) {
......
package com.liquidnet.service.dragon.channel.alipay.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.Properties;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayUtil
* @Package com.liquidnet.service.dragon.channel.alipay.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/9 15:20
*/
public class AlipayConfigUtil {
private static final Log LOG = LogFactory.getLog(AlipayConfigUtil.class);
/**
* 通过静态代码块读取上传文件的验证格式配置文件,静态代码块只执行一次(单例)
*/
private static Properties properties = new Properties();
/**
* 私有构造方法
**/
private AlipayConfigUtil() {
}
static {
try {
// 从类路径下读取属性文件
properties.load(AlipayConfigUtil.class.getClassLoader()
.getResourceAsStream("alipay_config.properties"));
} catch (IOException e) {
LOG.error(e);
}
}
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 合作身份者ID,签约账号,以2088开头由16位纯数字组成的字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
public static final String partner = (String) properties.get("partner");
// 收款支付宝账号,以2088开头由16位纯数字组成的字符串,一般情况下收款账号就是签约账号
public static final String seller_id = (String) properties.get("seller_id");
// MD5密钥,安全检验码,由数字和字母组成的32位字符串,查看地址:https://b.alipay.com/order/pidAndKey.htm
public static final String key = (String) properties.get("key");
// 服务器异步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static final String notify_url = (String) properties.get("notify_url");
// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
public static final String return_url = (String) properties.get("return_url");
// 签名方式
public static final String sign_type = (String) properties.get("sign_type");
// 调试用,创建TXT日志文件夹路径,见AlipayCore.java类中的logResult(String sWord)打印方法。
public static final String log_path = (String) properties.get("log_path");
// 字符编码格式 目前支持 gbk 或 utf-8
public static final String input_charset = (String) properties.get("input_charset");
// 支付类型 ,无需修改
public static final String payment_type = (String) properties.get("payment_type");
// 调用的接口名,无需修改
public static final String service = (String) properties.get("service");
//支付宝被扫地址
public static final String trade_pay_url = (String) properties.get("trade_pay_url");
//支付宝交易查询地址
public static final String trade_query_url = (String) properties.get("trade_query_url");
//app_id
public static final String app_id = (String) properties.get("app_id");
//商户私钥
public static final String mch_private_key = (String) properties.get("mch_private_key");
//支付宝公钥
public static final String ali_public_key = (String) properties.get("ali_public_key");
// 防钓鱼时间戳 若要使用请调用类文件submit中的query_timestamp函数
public static final String anti_phishing_key = "";
// 客户端的IP地址 非局域网的外网IP地址,如:221.0.0.1
public static final String exter_invoke_ip = "";
}
package com.liquidnet.service.dragon.channel.alipay.req;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import java.math.BigDecimal;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayTradePayReq
* @Package com.liquidnet.service.dragon.channel.alipay.req
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/9 17:50
*/
@Data
public class AlipayTradePayReq {
private String productCode;
private BigDecimal totalAmount;
private String subject;
private String body;
private String outTradeNo;
private String timeExpire;
@Override
public String toString(){
return JSON.toJSONString(this);
}
}
/*
* Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liquidnet.service.dragon.channel.alipay.sign;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
/**
* 签名加密MD%
*/
public class MD5 {
/**
* 签名字符串
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String sign(String text, String key, String input_charset) {
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if(mysign.equals(sign)) {
return true;
}
else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
}
\ No newline at end of file
package com.liquidnet.service.dragon.channel.alipay.strategy;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
@Component
public class AlipayStrategyContext {
private final Map<String, IAlipayStrategy> handlerMap = new HashMap<>();
public IAlipayStrategy getStrategy(String type) {
return handlerMap.get(type);
}
public void putStrategy(String code, IAlipayStrategy strategy) {
handlerMap.put(code, strategy);
}
}
package com.liquidnet.service.dragon.channel.alipay.strategy;
import com.liquidnet.service.dragon.channel.alipay.strategy.annotation.StrategyAlipayHandler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
@Component
public class AlipayStrategyListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(StrategyAlipayHandler.class);
AlipayStrategyContext strategyContext = event.getApplicationContext().getBean(AlipayStrategyContext.class);
beans.forEach((name, bean) -> {
StrategyAlipayHandler typeHandler = bean.getClass().getAnnotation(StrategyAlipayHandler.class);
strategyContext.putStrategy(typeHandler.value().getCode(), (IAlipayStrategy) bean);
});
}
}
\ No newline at end of file
package com.liquidnet.service.dragon.channel.alipay.strategy;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
public interface IAlipayStrategy {
ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto);
}
package com.liquidnet.service.dragon.channel.alipay.strategy.annotation;
import com.liquidnet.service.dragon.constant.DragonConstant;
import java.lang.annotation.*;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: TODO
* @class: StrategyGetFundDataHandler
* @Package com.liquidnet.service.reconciliation.strategy.annotation
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/10/27 15:29
*/
@Documented
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface StrategyAlipayHandler {
DragonConstant.DeviceFromEnum value();
}
package com.liquidnet.service.dragon.channel.alipay.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.alipay.strategy.IAlipayStrategy;
import com.liquidnet.service.dragon.channel.alipay.strategy.annotation.StrategyAlipayHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayStrategyWapImpl
* @Package com.liquidnet.service.dragon.channel.alipay.strategy.impl
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:34
*/
@Component
@StrategyAlipayHandler(DragonConstant.DeviceFromEnum.APP)
public class AlipayStrategyAppImpl implements IAlipayStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.alipay.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.alipay.strategy.IAlipayStrategy;
import com.liquidnet.service.dragon.channel.alipay.strategy.annotation.StrategyAlipayHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayStrategyWapImpl
* @Package com.liquidnet.service.dragon.channel.alipay.strategy.impl
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:34
*/
@Component
@StrategyAlipayHandler(DragonConstant.DeviceFromEnum.WAP)
public class AlipayStrategyWapImpl implements IAlipayStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.alipay.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.alipay.strategy.IAlipayStrategy;
import com.liquidnet.service.dragon.channel.alipay.strategy.annotation.StrategyAlipayHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayStrategyWapImpl
* @Package com.liquidnet.service.dragon.channel.alipay.strategy.impl
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:34
*/
@Component
@StrategyAlipayHandler(DragonConstant.DeviceFromEnum.WEB)
public class AlipayStrategyWebImpl implements IAlipayStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.alipay.util;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AlipayUtil
* @Package com.liquidnet.service.dragon.channel.alipay.util
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/9 15:20
*/
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.dragon.channel.alipay.config.AlipayConfigUtil;
import com.liquidnet.service.dragon.channel.alipay.req.AlipayTradePayReq;
import com.liquidnet.service.dragon.channel.alipay.sign.MD5;
import com.liquidnet.service.dragon.utils.PayAlipayUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigDecimal;
import java.util.*;
@Slf4j
public class AlipayUtil {
private static final Logger logger = LoggerFactory.getLogger(AlipayUtil.class);
private AlipayUtil() {
}
/**
* 支付宝支付
* @param alipayTradePayReq
* @return
*/
public static Map<String, Object> tradePagePay(AlipayTradePayReq alipayTradePayReq) {
logger.info("AlipayUtil.tradePay-->> req : {}",alipayTradePayReq.toString());
String timeExpress = "5m";// 支付超时,线下扫码交易定义为5分钟
AlipayClient alipayClient = PayAlipayUtils.getHttpClient();
SortedMap<String, Object> paramMap = new TreeMap<>();
paramMap.put("product_code", alipayTradePayReq.getProductCode());
paramMap.put("total_amount", alipayTradePayReq.getTotalAmount().toString());
paramMap.put("subject", alipayTradePayReq.getSubject());
paramMap.put("body", alipayTradePayReq.getBody());
paramMap.put("out_trade_no", alipayTradePayReq.getOutTradeNo());
paramMap.put("timeout_express", timeExpress);
AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
request.setNotifyUrl("https://testpay.zhengzai.tv");
// request.setTimestamp(DateUtil.now());
logger.info("bizContent :{}",JSONObject.toJSONString(paramMap));
request.setBizContent(JSONObject.toJSONString(paramMap));
try {
AlipayTradePagePayResponse response = alipayClient.sdkExecute(request);
JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
logger.info("支付宝返回结果:{}", responseJSON);
return responseJSON;
} catch (AlipayApiException e) {
logger.error("支付宝支付异常:{}", e);
JSONObject resultJSON = new JSONObject();
resultJSON.put("outTradeNo", alipayTradePayReq.getOutTradeNo());
resultJSON.put("totalAmount", alipayTradePayReq.getTotalAmount().toString());
resultJSON.put("errorCode", "9999");
return resultJSON;
}
}
/**
* 支付宝支付
* @param alipayTradePayReq
* @return
*/
public static Map<String, Object> tradeWapPay(AlipayTradePayReq alipayTradePayReq) {
logger.info("AlipayUtil.tradePay-->> req : {}",alipayTradePayReq.toString());
String timeExpress = "5m";// 支付超时,线下扫码交易定义为5分钟
AlipayClient alipayClient = PayAlipayUtils.getHttpClient();
SortedMap<String, Object> paramMap = new TreeMap<>();
paramMap.put("product_code", alipayTradePayReq.getProductCode());
paramMap.put("total_amount", alipayTradePayReq.getTotalAmount().toString());
paramMap.put("subject", alipayTradePayReq.getSubject());
paramMap.put("body", alipayTradePayReq.getBody());
paramMap.put("out_trade_no", alipayTradePayReq.getOutTradeNo());
paramMap.put("timeout_express", timeExpress);
AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
request.setNotifyUrl("https://testpay.zhengzai.tv");
// request.setTimestamp(DateUtil.now());
logger.info("bizContent :{}",JSONObject.toJSONString(paramMap));
request.setBizContent(JSONObject.toJSONString(paramMap));
try {
AlipayTradeWapPayResponse response = alipayClient.sdkExecute(request);
if(response.isSuccess()){
}
JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
logger.info("支付宝返回结果:{}", responseJSON);
return responseJSON;
} catch (AlipayApiException e) {
logger.error("支付宝支付异常:{}", e);
JSONObject resultJSON = new JSONObject();
resultJSON.put("outTradeNo", alipayTradePayReq.getOutTradeNo());
resultJSON.put("totalAmount", alipayTradePayReq.getTotalAmount().toString());
resultJSON.put("errorCode", "9999");
return resultJSON;
}
}
/**
* 订单查询
*
* @return
*/
public static Map<String, Object> tradeQuery(String outTradeNo) {
logger.info("======>支付宝交易查询");
String charset = "UTF-8";
String format = "json";
String signType = "RSA2";
AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfigUtil.trade_query_url, AlipayConfigUtil.app_id, AlipayConfigUtil.mch_private_key, format, charset, AlipayConfigUtil.ali_public_key, signType);
SortedMap<String, Object> bizContentMap = new TreeMap<>();
bizContentMap.put("out_trade_no", outTradeNo);
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
request.setBizContent(JSONObject.toJSONString(bizContentMap));
try {
AlipayTradeQueryResponse response = alipayClient.execute(request);
JSONObject responseJSON = JSONObject.parseObject(JSONObject.toJSONString(response));
logger.info("支付宝订单查询返回结果:{}", responseJSON);
return responseJSON;
} catch (AlipayApiException e) {
logger.error("支付宝交易查询异常:{}", e);
return null;
}
}
private static String getSign(SortedMap<String, String> paramMap, String key) {
StringBuilder signBuilder = new StringBuilder();
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
if (!"sign".equals(entry.getKey()) && !"sign_type".equals(entry.getKey()) && !StringUtil.isEmpty(entry.getValue())) {
signBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
}
return MD5.sign(signBuilder.substring(0, signBuilder.length() - 1), key, "UTF-8");
}
}
package com.liquidnet.service.dragon.channel.strategy;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
public interface IPayChannelStrategy {
ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto);
}
package com.liquidnet.service.dragon.channel.strategy;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
@Component
public class PayChannelStrategyContext {
private final Map<String, IPayChannelStrategy> handlerMap = new HashMap<>();
public IPayChannelStrategy getStrategy(String type) {
return handlerMap.get(type);
}
public void putStrategy(String code, IPayChannelStrategy strategy) {
handlerMap.put(code, strategy);
}
}
package com.liquidnet.service.dragon.channel.strategy;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: Test
* @Package com.liquidnet.service.dragon.channel.strategy
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/10 14:27
*/
@Component
public class PayChannelStrategyListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(StrategyPayChannelHandler.class);
PayChannelStrategyContext strategyContext = event.getApplicationContext().getBean(PayChannelStrategyContext.class);
beans.forEach((name, bean) -> {
StrategyPayChannelHandler typeHandler = bean.getClass().getAnnotation(StrategyPayChannelHandler.class);
strategyContext.putStrategy(typeHandler.value().getCode(), (IPayChannelStrategy) bean);
});
}
}
\ No newline at end of file
package com.liquidnet.service.dragon.channel.strategy.annotation;
import com.liquidnet.service.dragon.constant.DragonConstant;
import java.lang.annotation.*;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: TODO
* @class: StrategyGetFundDataHandler
* @Package com.liquidnet.service.reconciliation.strategy.annotation
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/10/27 15:29
*/
@Documented
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface StrategyPayChannelHandler {
DragonConstant.PayChannelEnum value();
}
package com.liquidnet.service.dragon.channel.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.strategy.IPayChannelStrategy;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: currencyCloud
* @class: CurrencyCloudGetFundDataStrategyImpl
* @Package com.liquidnet.service.reconciliation.strategy.transtype.impl
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/10/27 14:58
*/
@Component
@StrategyPayChannelHandler(DragonConstant.PayChannelEnum.ALIPAY)
public class PayChannelStrategyAlipayImpl implements IPayChannelStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.strategy.IPayChannelStrategy;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: liquidnet-wallet
* @class: LiquidnetWalletGetFundDataStrategyImpl
* @Package com.liquidnet.service.reconciliation.strategy.transtype.impl
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/10/27 14:58
*/
@Component
@StrategyPayChannelHandler(DragonConstant.PayChannelEnum.APPLEPAY)
public class PayChannelStrategyApplepayImpl implements IPayChannelStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.strategy.impl;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.dragon.channel.strategy.IPayChannelStrategy;
import com.liquidnet.service.dragon.channel.strategy.annotation.StrategyPayChannelHandler;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: liquidnet-wallet
* @class: LiquidnetWalletGetFundDataStrategyImpl
* @Package com.liquidnet.service.reconciliation.strategy.transtype.impl
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/10/27 14:58
*/
@Component
@StrategyPayChannelHandler(DragonConstant.PayChannelEnum.WEPAY)
public class PayChannelStrategyWepayImpl implements IPayChannelStrategy {
@Override
public ResponseDto<DragonPayBaseRespDto> dragonPay(DragonPayBaseReqDto dragonPayBaseReqDto) {
return null;
}
}
package com.liquidnet.service.dragon.channel.wepay.util;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: WepayUtil
* @Package com.liquidnet.service.dragon.channel.wepay.util
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/7/9 15:20
*/
public class WepayUtil {
}
package com.liquidnet.service.dragon.service.impl;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
......@@ -19,6 +17,7 @@ import com.liquidnet.service.dragon.service.IDragonOrderRefundsService;
import com.liquidnet.service.dragon.utils.PayAlipayUtils;
import com.liquidnet.service.dragon.utils.PayWepayUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
......@@ -32,8 +31,7 @@ import org.springframework.stereotype.Service;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.*;
@Slf4j
@Service
......@@ -45,33 +43,39 @@ public class DragonOrderRefundsServiceImpl implements IDragonOrderRefundsService
@Override
public void sendRedisQueue() {
try {
PayWepayUtils payWepayUtils = new PayWepayUtils();
HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi");
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json; charset=utf-8");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode rootNode = objectMapper.createObjectNode();
rootNode.put("mchid", "1551961491")
.put("appid", "wx3498304dda39c5a1")
.put("description", "Image形象店-深圳腾大-QQ公仔")
.put("notify_url", "https://www.weixin.qq.com/wxpay/pay.php")
.put("out_trade_no", "1217752501201407033233368018");
rootNode.putObject("amount")
.put("total", 1);
rootNode.putObject("payer")
.put("openid", "oUpkkuHUgiyTYE4ZU8Y5Sga-znWQ");
objectMapper.writeValue(bos, rootNode);
httpPost.setEntity(new StringEntity(bos.toString("UTF-8"), "UTF-8"));
CloseableHttpResponse response = payWepayUtils.getHttpClient().execute(httpPost);
String bodyAsString = EntityUtils.toString(response.getEntity());
System.out.println(bodyAsString);
// PayWepayUtils payWepayUtils = new PayWepayUtils();
String nonceStr = PayWepayUtils.getInstance().getNonceStr();
SortedMap<Object, Object> parameters = new TreeMap<>();
parameters.put("mch_id", PayWepayUtils.getInstance().getMerchantId());
parameters.put("appid", PayWepayUtils.getInstance().getAppId());
parameters.put("nonce_str", nonceStr);
parameters.put("out_refund_no", "20210710140233163870197466289T");
parameters.put("out_trade_no", "20210710140233163870197466289P");
parameters.put("refund_fee", "1");
parameters.put("total_fee", "1");
parameters.put("notify_url", "https://www.baidu.com");
parameters.put("refund_desc", "测试退款");
String sign = PayWepayUtils.getInstance().createSign(parameters);
parameters.put("sign", sign);
String data = PayWepayUtils.getInstance().getRequestXml(parameters);
try {
HttpPost httpost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = PayWepayUtils.getInstance().getHttpClient().execute(httpost);
try {
HttpEntity entity = response.getEntity();
//接受到返回信息
String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
System.out.println(jsonStr);
} finally {
response.close();
}
} finally {
PayWepayUtils.getInstance().getHttpClient().close();
}
} catch (Exception e) {
e.printStackTrace();
}
......@@ -127,12 +131,12 @@ public class DragonOrderRefundsServiceImpl implements IDragonOrderRefundsService
"\"out_request_no\":\"" + refundCode + "\"," +
"\"refund_reason\":\"" + reason + "\"," +
"\"refund_amount\":\"" + price.doubleValue() + "\"}"); //设置业务参数
AlipayTradeRefundResponse response = PayAlipayUtils.getHttpClient().execute(request);//通过alipayClient调用API,获得对应的response类
AlipayTradeRefundResponse response = PayAlipayUtils.getInstance().getHttpClient().execute(request);//通过alipayClient调用API,获得对应的response类
System.out.print(response.getBody());
if (response.getFundChange().equals("N") || response.getFundChange() == null) {
try {
String refundError = "";
refundStatus = DragonConstant.refundStatusEnum.STATUS_ERROR.getCode();
refundStatus = DragonConstant.RefundStatusEnum.STATUS_ERROR.getCode();
if (null == response.getSubMsg()) {
refundError = "退款失败,原因未知";
} else {
......@@ -170,10 +174,10 @@ public class DragonOrderRefundsServiceImpl implements IDragonOrderRefundsService
try {
String refundAt = "";
if (response.getFundChange().equals("Y")) {
refundStatus = DragonConstant.refundStatusEnum.STATUS_REFUNDED.getCode();
refundStatus = DragonConstant.RefundStatusEnum.STATUS_REFUNDED.getCode();
refundAt = DateUtil.format(response.getGmtRefundPay(), DateUtil.Formatter.yyyyMMddHHmmss);
} else {
refundStatus = DragonConstant.refundStatusEnum.STATUS_REFUNDING.getCode();
refundStatus = DragonConstant.RefundStatusEnum.STATUS_REFUNDING.getCode();
}
sendMySqlRedis(
SqlMapping.get("dragon_order_refund_success.update"),
......@@ -220,7 +224,7 @@ public class DragonOrderRefundsServiceImpl implements IDragonOrderRefundsService
HashMap<String, String> map = new HashMap<>();
map.put("message", sqlData);
MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(DragonConstant.mysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode());
MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(DragonConstant.MysqlRedisQueueEnum.DRAGON_REFUND_KEY.getCode());
stringRedisTemplate.opsForStream().add(record);
return true;
} catch (Exception e) {
......
package com.liquidnet.service.dragon.service.impl;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.dragon.channel.alipay.req.AlipayTradePayReq;
import com.liquidnet.service.dragon.channel.alipay.util.AlipayUtil;
import com.liquidnet.service.dragon.constant.DragonConstant;
import com.liquidnet.service.dragon.dto.DragonPayBaseReqDto;
import com.liquidnet.service.dragon.dto.DragonPayBaseRespDto;
import com.liquidnet.service.dragon.entity.DragonOrders;
import com.liquidnet.service.dragon.service.IDragonOrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
@Service
public class DragonOrdersServiceImpl implements IDragonOrdersService {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Value("liquidnet.dragon.alipay-gataway-url")
private String alipayGatewayUrl;
@Override
public void sendRedisQueue() {
......@@ -25,4 +40,83 @@ public class DragonOrdersServiceImpl implements IDragonOrdersService {
e.printStackTrace();
}
}
@Override
public ResponseDto<DragonPayBaseRespDto> alipay(DragonPayBaseReqDto dragonPayBaseReqDto) {
AlipayTradePayReq alipayTradePayReq = new AlipayTradePayReq();
alipayTradePayReq.setProductCode("QUICK_WAP_PAY");
alipayTradePayReq.setTotalAmount(dragonPayBaseReqDto.getPrice());
alipayTradePayReq.setSubject(dragonPayBaseReqDto.getName());
alipayTradePayReq.setBody(dragonPayBaseReqDto.getDetail());
//dragon中支付编号
alipayTradePayReq.setOutTradeNo(IDGenerator.payCode());
alipayTradePayReq.setTimeExpire(dragonPayBaseReqDto.getExpireTime());
Map<String, Object> result = AlipayUtil.tradeWapPay(alipayTradePayReq);
DragonPayBaseRespDto respDto = new DragonPayBaseRespDto();
respDto.setCode(alipayTradePayReq.getOutTradeNo());
respDto.setOrder_code(dragonPayBaseReqDto.getOrderCode());
DragonPayBaseRespDto.PayData payData = new DragonPayBaseRespDto.PayData();
payData.setRedirectUrl(alipayGatewayUrl + result.get("body"));
respDto.setPay_data(payData);
//支付订单持久化
this.buildPayOrders(dragonPayBaseReqDto,respDto);
return ResponseDto.success(respDto);
}
private DragonOrders buildPayOrders(DragonPayBaseReqDto dragonPayBaseReqDto,DragonPayBaseRespDto respDto){
DragonOrders orders = new DragonOrders();
// orders.setMid();
orders.setStatus(Integer.valueOf(DragonConstant.PayStatusEnum.STATUS_UNPAID.getCode()));
orders.setCode(respDto.getCode());
orders.setType(dragonPayBaseReqDto.getType());
orders.setPrice(dragonPayBaseReqDto.getPrice());
orders.setName(dragonPayBaseReqDto.getName());
orders.setDetail(dragonPayBaseReqDto.getDetail());
orders.setOrderCode(dragonPayBaseReqDto.getOrderCode());
orders.setClientIp(dragonPayBaseReqDto.getClientIp());
orders.setNotifyUrl(dragonPayBaseReqDto.getNotifyUrl());
orders.setPaymentType(DragonConstant.PayTypeEnum.PAYMENT_TYPE_APP_IAP.getCode());
// orders.setPaymentId();
orders.setPaymentAt(LocalDateTime.now());
// orders.setFinishedAt();
orders.setCreatedAt(LocalDateTime.now());
// orders.setUpdatedAt();
// 修改退款订单
boolean insertResult = sendMySqlRedis(
SqlMapping.get("dragon_orders.insert"),
new Object[]{orders.getStatus(), orders.getCode(), orders.getType()
, orders.getPrice(), orders.getName(), orders.getDetail()
, orders.getOrderCode(), orders.getClientIp()
, orders.getNotifyUrl(), orders.getPaymentType(),
orders.getPaymentId(), orders.getPaymentAt()
, orders.getFinishedAt(), orders.getCreatedAt()
, orders.getUpdatedAt()}
);
return orders;
}
/**
* 给 REDIS 队列发送消息 数据库相关
*
* @param sql sql语句
* @param data 需要操作的数据
* @return
*/
private boolean sendMySqlRedis(String sql, Object[] data) {
try {
LinkedList<String> sqls = new LinkedList<>();
sqls.add(sql);
LinkedList<Object[]> sqlsData = new LinkedList();
sqlsData.add(data);
String sqlData = SqlMapping.gets(sqls, sqlsData);
HashMap<String, String> map = new HashMap<>();
map.put("message", sqlData);
MapRecord<String, String, String> record = StreamRecords.mapBacked(map).withStreamKey(DragonConstant.MysqlRedisQueueEnum.DRAGON_PAY_KEY.getCode());
stringRedisTemplate.opsForStream().add(record);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
......@@ -21,25 +21,28 @@ import java.net.URL;
import java.security.PrivateKey;
public class PayAlipayUtils {
private static AlipayClient httpClient;
private static PayAlipayUtils instance = new PayAlipayUtils();
private String appId = "2019082866535131";
private String merchant_pub_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmePaETscydypY3rV4mXa8MtcQIL5zjP1KxdusNkHpePeU61hAZxKn0Z8pDB1wNaTK72wgEWaORXeRp4YTbf4usHlW562Pe5wdiSutb3iT6EMJ5eBD4HLI9wWDgYBtwfHwS5JJFhf0eptP4R1XluLiMhmMynLwJvHepgkVrS3mN+jmoPRmKFhZHGIYDoWypBMbUKiFHWiToHK1n0NYHHIi4WgK2wt4Wj7nexQGD69W7ofRCirYmz35c/cNFUA1lqzOEKu2z7PpjA6jQV2GJolnJ4xXPJ8Dpgp4g/dgsGqRydlmFqZD71i/pDDpF0RfRKHL+WhWVhI1hqe6jLtvJE+zQIDAQAB";
private String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCArhnBTpcAww8wSYBTwGp6oBvenzCCYFrugERgxJDZ7YnBZ3ZdiAaHjJ9PI0WymkpDr27FSg9czVbiH7G91zPq+8s9onrZi/l6cBZ2VjrwQ9BQPN2a8zHy8D6BfoKEV+PIicGz6hNPA7lgf04NgsXeWjeXnYD/IBTLZmnCxB2sPYo/0EN32mlSG9snO63HlPkoqn8ycw71a1cBrlQ+Y22fFnJAk/vrGoou8E0UHfL5zVE/up+ToOYW/eOKMFL/DSceCy32t9Za0RmpV3i2E9s8gBDewzT10Yf4+4mPUiTR6AhcLjqafAy2IaKPK57WZ6cGF9cGs9yq8bSTRpeNC4alAgMBAAECggEAH0Ms+qvPP94j6IVS6gYLWHNhkfp23JXwQZVkB2Z6EpgFKbmrJhoQDAp8Acv9+OBHPp52ePP/O3qfqxwsIIUSFfrKa9T3p7a8C6UDsAhPFWRETdobtLN05SK87NUBfImly2i8aKtruXycIveKzPmCfPzKGMmpN1Jh+vCMrUbcNqX8OUcxmhGvJwnQuBW4QEiepzl89Nl91iSwFmxaZoqLaB9lYUKke/z7FDHTpTWpZvtvxlZ0gvMVNLVp9NBNazolQ8eEjBG2PsQGD2cLUbM33mLTz+/VQjzZR3KXu5kQR9MloURILDsdxE1AyA4AkIXd4eMszEjA4Dv6CQK/jjrsgQKBgQDIiCt1OGmV2sqDBSn4nZNH7BzY3Hdnf+qsYUi+TXKhnQaT8XPKWZpKE/AcqsIKnANmO4sX0NL7ACBe7Rl1RcU9Mq5XuHhnkveFBVRRIHindzUfEN0WgdLy23qmJ2N+1i4FigelY0E5T2lojVb7wycAgAc6vflwE+eYf8W3968q0QKBgQCkRgsVCWWNMSLZeB0V9LV3Om2/UPWY/ovadTxAQtxg0Z75V6Wdu8u0hrYaPSeUK2ryaoE6HKgp7U8NiJGzgm2wpj7D2ysrPmhX5+CjiWkDMCuvWytVT7hLqhhLp7frZT39u8VhyfC8lE0xA67gAPsGSl1sBoZPwvvsmNAQ/h6rlQKBgQCtCtw9be2m88M3JnieYhOax8Po2u5qsLZoBBcKqLhXf7ISbhPWNFXwwJ29jxicoR5J1O3lIj09fVFxuLX0Pb3DXn2VksjLz8Wp0vx8eUHEeRis8xdleaf4C68du/WemOHjw8VvUWQSOVWjc/vwiumYA+K5LQAXWAXM0c1jP+e3UQKBgEWY/1z8TDATn0Yvo3MH6FIJSTIDJOqa/bmibdJ0AVZruUS+o4Y+aEGlyUU4n6og8wCdqv5p4b1Rs2pyb/hzy/FJndHw60s495A2x2/B6eHV6Mw0fhl42wYDnKOA/WUX0bnMcgXKPtpGoqWff9mb0L6LhyUbZpAodf95hr2MTIY5AoGBAIyPtYP6jRyR980h/Ud1MS0fBxymjQrR+kg3GWjnw0ZJJ8yFEXxDqLV8uLyXQKc89HGbI0cClWgZBTjfIPJ5U4Gl19Xlwx1SFrdgg5mGUqnMARTg7w1TG5QLSqNhZo2jgBM5FCJRbDUCO/MzLcFhTeGNva9yP7E7gW5/Dott9D7d";
private String sign_type = "RSA2";
private String charset = "utf-8";
private String gatewayUrl = "https://openapi.alipay.com/gateway.do";
private AlipayClient httpClient = null;
private final String appId = "2019082866535131";
private final String merchant_pub_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmePaETscydypY3rV4mXa8MtcQIL5zjP1KxdusNkHpePeU61hAZxKn0Z8pDB1wNaTK72wgEWaORXeRp4YTbf4usHlW562Pe5wdiSutb3iT6EMJ5eBD4HLI9wWDgYBtwfHwS5JJFhf0eptP4R1XluLiMhmMynLwJvHepgkVrS3mN+jmoPRmKFhZHGIYDoWypBMbUKiFHWiToHK1n0NYHHIi4WgK2wt4Wj7nexQGD69W7ofRCirYmz35c/cNFUA1lqzOEKu2z7PpjA6jQV2GJolnJ4xXPJ8Dpgp4g/dgsGqRydlmFqZD71i/pDDpF0RfRKHL+WhWVhI1hqe6jLtvJE+zQIDAQAB";
private final String merchant_private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCArhnBTpcAww8wSYBTwGp6oBvenzCCYFrugERgxJDZ7YnBZ3ZdiAaHjJ9PI0WymkpDr27FSg9czVbiH7G91zPq+8s9onrZi/l6cBZ2VjrwQ9BQPN2a8zHy8D6BfoKEV+PIicGz6hNPA7lgf04NgsXeWjeXnYD/IBTLZmnCxB2sPYo/0EN32mlSG9snO63HlPkoqn8ycw71a1cBrlQ+Y22fFnJAk/vrGoou8E0UHfL5zVE/up+ToOYW/eOKMFL/DSceCy32t9Za0RmpV3i2E9s8gBDewzT10Yf4+4mPUiTR6AhcLjqafAy2IaKPK57WZ6cGF9cGs9yq8bSTRpeNC4alAgMBAAECggEAH0Ms+qvPP94j6IVS6gYLWHNhkfp23JXwQZVkB2Z6EpgFKbmrJhoQDAp8Acv9+OBHPp52ePP/O3qfqxwsIIUSFfrKa9T3p7a8C6UDsAhPFWRETdobtLN05SK87NUBfImly2i8aKtruXycIveKzPmCfPzKGMmpN1Jh+vCMrUbcNqX8OUcxmhGvJwnQuBW4QEiepzl89Nl91iSwFmxaZoqLaB9lYUKke/z7FDHTpTWpZvtvxlZ0gvMVNLVp9NBNazolQ8eEjBG2PsQGD2cLUbM33mLTz+/VQjzZR3KXu5kQR9MloURILDsdxE1AyA4AkIXd4eMszEjA4Dv6CQK/jjrsgQKBgQDIiCt1OGmV2sqDBSn4nZNH7BzY3Hdnf+qsYUi+TXKhnQaT8XPKWZpKE/AcqsIKnANmO4sX0NL7ACBe7Rl1RcU9Mq5XuHhnkveFBVRRIHindzUfEN0WgdLy23qmJ2N+1i4FigelY0E5T2lojVb7wycAgAc6vflwE+eYf8W3968q0QKBgQCkRgsVCWWNMSLZeB0V9LV3Om2/UPWY/ovadTxAQtxg0Z75V6Wdu8u0hrYaPSeUK2ryaoE6HKgp7U8NiJGzgm2wpj7D2ysrPmhX5+CjiWkDMCuvWytVT7hLqhhLp7frZT39u8VhyfC8lE0xA67gAPsGSl1sBoZPwvvsmNAQ/h6rlQKBgQCtCtw9be2m88M3JnieYhOax8Po2u5qsLZoBBcKqLhXf7ISbhPWNFXwwJ29jxicoR5J1O3lIj09fVFxuLX0Pb3DXn2VksjLz8Wp0vx8eUHEeRis8xdleaf4C68du/WemOHjw8VvUWQSOVWjc/vwiumYA+K5LQAXWAXM0c1jP+e3UQKBgEWY/1z8TDATn0Yvo3MH6FIJSTIDJOqa/bmibdJ0AVZruUS+o4Y+aEGlyUU4n6og8wCdqv5p4b1Rs2pyb/hzy/FJndHw60s495A2x2/B6eHV6Mw0fhl42wYDnKOA/WUX0bnMcgXKPtpGoqWff9mb0L6LhyUbZpAodf95hr2MTIY5AoGBAIyPtYP6jRyR980h/Ud1MS0fBxymjQrR+kg3GWjnw0ZJJ8yFEXxDqLV8uLyXQKc89HGbI0cClWgZBTjfIPJ5U4Gl19Xlwx1SFrdgg5mGUqnMARTg7w1TG5QLSqNhZo2jgBM5FCJRbDUCO/MzLcFhTeGNva9yP7E7gW5/Dott9D7d";
private final String sign_type = "RSA2";
private final String charset = "utf-8";
private final String gatewayUrl = "https://openapi.alipay.com/gateway.do";
public PayAlipayUtils() {
httpClient = new DefaultAlipayClient(gatewayUrl, appId, merchant_private_key, "json", charset,
merchant_pub_key, sign_type);
}
private static PayAlipayUtils getInstance() {
public static PayAlipayUtils getInstance() {
return instance;
}
public static AlipayClient getHttpClient() {
public AlipayClient getHttpClient() {
if(httpClient == null){
httpClient = new DefaultAlipayClient(gatewayUrl, appId, merchant_private_key, "json", charset,
merchant_pub_key, sign_type);
}
return httpClient;
}
}
package com.liquidnet.service.dragon.utils;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import com.alipay.api.internal.util.file.IOUtils;
import com.liquidnet.commons.lang.util.MD5Utils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import java.io.FileInputStream;
import java.net.URL;
import java.security.PrivateKey;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.*;
public class PayWepayUtils {
private CloseableHttpClient httpClient;
// private static PayUtils instance = new PayUtils();
private static PayWepayUtils instance = new PayWepayUtils();
private final String merchantId = "1551961491";
private final String appId = "wx3498304dda39c5a1";
private final String parentKey = "itIuO65O9yKmemOu3S8g1S4orqvCGwXK";
private String merchantId = "1551961491";
private String merchantSerialNumber = "6D25ECC819EAE0BCEA7DB18F143F0752431D9295";
private String appId = "wx3498304dda39c5a1";
public PayWepayUtils() {
System.out.println("1");
try {
URL path = PayWepayUtils.class.getClassLoader().getResource("payCert/wepay/wepay_apiclient_key.pem");
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
new FileInputStream(path.getPath())
);
}
CloseableHttpClient httpClientTemp = WechatPayHttpClientBuilder.create()
.withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
.withValidator(response -> true) // NOTE: 设置一个空的应答签名验证器,**不要**用在业务请求
.build();
public static PayWepayUtils getInstance() {
return instance;
}
URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
HttpGet httpGet = new HttpGet(uriBuilder.build());
httpGet.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClientTemp.execute(httpGet);
String bodyAsString = EntityUtils.toString(response.getEntity());
AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
bodyAsString.getBytes("utf-8"));
public String getAppId() {
return appId;
}
WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
.withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier));
public String getMerchantId() {
return merchantId;
}
public CloseableHttpClient getHttpClient() {
try {
if (httpClient == null) {
InputStream certStream = PayWepayUtils.class.getClassLoader().getResourceAsStream("payCert/wepay/wepay_apiclient_cert.p12");
byte[] certData = IOUtils.toByteArray(certStream);
certStream.read(certData);
certStream.close();
httpClient = builder.build();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
ByteArrayInputStream inputStream = new ByteArrayInputStream(certData);
try {
keyStore.load(inputStream, merchantId.toCharArray());
} finally {
inputStream.close();
}
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, merchantId.toCharArray())
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.build();
}
} catch (Exception e) {
e.printStackTrace();
}
return httpClient;
}
// private static PayUtils getInstance() {
// return instance;
// }
//生成随机字符串nonce_str
public String getNonceStr() {
String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 32; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
public String createSign(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序)
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + parentKey);
return MD5Utils.md5(sb.toString()).toUpperCase();
}
public CloseableHttpClient getHttpClient() {
return httpClient;
public String getRequestXml(SortedMap<Object, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {
sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
} else {
sb.append("<" + k + ">" + v + "</" + k + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
}
......@@ -5,3 +5,8 @@ dragon_order_refund_error.update=UPDATE `dragon_order_refunds` SET updated_at =
dragon_order_refund_success.update=UPDATE `dragon_order_refunds` SET updated_at = ? , refund_at=? , status=? WHERE order_refund_id = ?
# ------------------------创建退款订单日志----------------------------
dragon_order_refund_log.insert=INSERT INTO `dragon_order_refunds`(`order_refund_id` ,`refund_type` ,`content`,`created_at`,`updated_at`)VALUES(?,?,?,?,?);
dragon_orders.insert=INSERT INTO DRAGON_ORDERS (ID, STATUS, CODE, TYPE, PRICE, NAME, DETAIL, ORDER_CODE, CLIENT_IP, NOTIFY_URL, PAYMENT_TYPE,PAYMENT_ID, PAYMENT_AT, FINISHED_AT, CREATED_AT, UPDATED_AT, DELETED_AT)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
dragon_order_logs.insert=INSERT INTO DRAGON_ORDER_LOGS (ID, ORDER_ID, PAYMENT_TYPE, CONTENT, CREATED_AT, UPDATED_AT, DELETED_AT) VALUES(?,?,?,?,?,?,?)
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