Commit 6d435a63 authored by xuxin's avatar xuxin

添加代码注释

parent 28818ddf
...@@ -248,13 +248,16 @@ public class AccountController { ...@@ -248,13 +248,16 @@ public class AccountController {
} }
/** /**
* 账户充值 * 使用微信进行账户充值
*/ */
@RequestMapping(path = "/0xwxpayputorder/{amount}", method = RequestMethod.GET) @RequestMapping(path = "/0xwxpayputorder/{amount}", method = RequestMethod.GET)
public UserPaymentDto wechatPayCallback(Principal principal, @PathVariable int amount) { public UserPaymentDto wechatPayCallback(Principal principal, @PathVariable int amount) {
return paymentService.wxPutPayOrder(principal.getName(), amount); return paymentService.wxPutPayOrder(principal.getName(), amount);
} }
/**
* 使用微信进行账户充值成功后,微信会调用该接口
*/
@RequestMapping(path = "/0xwxpaycallback/{tradno}", method = RequestMethod.GET) @RequestMapping(path = "/0xwxpaycallback/{tradno}", method = RequestMethod.GET)
public String wechatPayCallback(@PathVariable String tradno) { public String wechatPayCallback(@PathVariable String tradno) {
return paymentService.wechatPayCallback(tradno); return paymentService.wechatPayCallback(tradno);
......
...@@ -67,8 +67,14 @@ public class Account { ...@@ -67,8 +67,14 @@ public class Account {
*/ */
private int permission = -1; private int permission = -1;
/**
* 注册成功后,当前用户的邀请码,用于邀请别人获取佣金
*/
private Promotion promotion; private Promotion promotion;
/**
* 注册时,其他用户给当前用户的邀请码
*/
private String promotionCode; private String promotionCode;
private String comment; private String comment;
......
...@@ -59,8 +59,6 @@ public class AccountRepositoryCustomImpl implements AccountRepositoryCustom { ...@@ -59,8 +59,6 @@ public class AccountRepositoryCustomImpl implements AccountRepositoryCustom {
basicQuery.addCriteria(where("promotion.code").is(code).and("parent").exists(false)); basicQuery.addCriteria(where("promotion.code").is(code).and("parent").exists(false));
Account account = mongoTemplate.findOne(basicQuery, Account.class); Account account = mongoTemplate.findOne(basicQuery, Account.class);
if (account == null)
return null;
return account; return account;
} }
} }
...@@ -24,10 +24,7 @@ public class UserPaymentRepositoryCustomImpl implements UserPaymentRepositoryCus ...@@ -24,10 +24,7 @@ public class UserPaymentRepositoryCustomImpl implements UserPaymentRepositoryCus
update.set("succeed", result); update.set("succeed", result);
UpdateResult operation = mongoTemplate.updateFirst(basicQuery, update, UserPayment.class); UpdateResult operation = mongoTemplate.updateFirst(basicQuery, update, UserPayment.class);
if (operation.getModifiedCount() < 1) return operation.getModifiedCount() >= 1;
return false;
else
return true;
} }
} }
...@@ -67,9 +67,8 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -67,9 +67,8 @@ public class PaymentServiceImpl implements PaymentService {
@Override @Override
public String wechatPayCallback(String tradno) { public String wechatPayCallback(String tradno) {
// 当微信回调该接口时,说明微信那边已经充值成功,这个时候需要更新系统中 userpayment 充值状态
UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradno); UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradno);
if (byTradeNo != null && !byTradeNo.isSucceed()) { if (byTradeNo != null && !byTradeNo.isSucceed()) {
wxCheckOrderStatus(byTradeNo.getTradeNo(), 0); wxCheckOrderStatus(byTradeNo.getTradeNo(), 0);
} }
...@@ -91,118 +90,81 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -91,118 +90,81 @@ public class PaymentServiceImpl implements PaymentService {
@Override @Override
public UserPaymentDto wxCheckOrderStatus(String tradeno, int chargeType) { public UserPaymentDto wxCheckOrderStatus(String tradeno, int chargeType) {
// 校验数据
UserPaymentDto result = new UserPaymentDto(); UserPaymentDto result = new UserPaymentDto();
result.setPaid(false); result.setPaid(false);
if (StringUtils.isBlank(tradeno)) if (StringUtils.isBlank(tradeno)) {
return result; return result;
try { }
UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradeno); UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradeno);
if (byTradeNo == null) if (byTradeNo == null) {
return result; return result;
}
if (byTradeNo.isSucceed()) {
result.setPaid(true);
return result;
}
Account byName = accountService.findByName(byTradeNo.getUsername());
if (PaymentMethod.ALIPAY.equals(byTradeNo.getPaymentMethod())) // 如果订单是用支付宝支付的,则调用支付宝相关的代码
return aliCheckOrderStatus(tradeno, chargeType); if (PaymentMethod.ALIPAY.equals(byTradeNo.getPaymentMethod())) {
return aliCheckOrderStatus(tradeno, chargeType);
}
try {
UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null); UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null);
if (balance != null) {
if (balance != null)
result.setBalance(Math.round(balance.getBalanced())); result.setBalance(Math.round(balance.getBalanced()));
}
if (byTradeNo == null) if (balance == null) {
return result; balance = new UserBalance();
if (byTradeNo.isSucceed()) { balance.setUsername(byTradeNo.getUsername());
result.setPaid(true);
return result;
} }
Account byName = accountService.findByName(byTradeNo.getUsername()); // 1. 构建微信支付订单查询数据,并获取微信支付订单信息
if (byName == null) // 获取微信支付订单存在失败的情况,所以针对失败情况去使用定时任务获取
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + byTradeNo.getUsername());
boolean isVpsClient = true; boolean isVpsClient = true;
WXPayConfig ourWxPayConfig = isVpsClient ? new FGLWxConfig() : new CloudamWxConfig(); WXPayConfig ourWxPayConfig = isVpsClient ? new FGLWxConfig() : new CloudamWxConfig();
WXPay wxPay = new WXPay(ourWxPayConfig); WXPay wxPay = new WXPay(ourWxPayConfig);
Map<String, String> data = encapsulateWxOrderDataMap(tradeno, ourWxPayConfig);
Map<String, String> data = new HashMap<>();
data.put("appid", ourWxPayConfig.getAppID());
data.put("mch_id", ourWxPayConfig.getMchID()); //商户号
data.put("out_trade_no", tradeno); //交易号
data.put("nonce_str", SmsUtils.createRandom(false, 24)); // 随机字符串小于32位
String s = WXPayUtil.generateSignature(data, ourWxPayConfig.getKey()); //签名
data.put("sign", s);
Map<String, String> respData = wxPay.orderQuery(data); Map<String, String> respData = wxPay.orderQuery(data);
if (respData.get("return_code").equals("SUCCESS") && respData.get("return_msg").equals("OK") && "SUCCESS".equals(respData.get("result_code"))) { if (respData.get("return_code").equals("SUCCESS") && respData.get("return_msg").equals("OK") && "SUCCESS".equals(respData.get("result_code"))) {
/*
/** * SUCCESS—支付成功
* * REFUND—转入退款
SUCCESS—支付成功 * NOTPAY—未支付
* CLOSED—已关闭
REFUND—转入退款 * REVOKED—已撤销(付款码支付)
* USERPAYING--用户支付中(付款码支付)
NOTPAY—未支付 * PAYERROR--支付失败(其他原因,如银行返回失败)
CLOSED—已关闭
REVOKED—已撤销(付款码支付)
USERPAYING--用户支付中(付款码支付)
PAYERROR--支付失败(其他原因,如银行返回失败) *
*/ */
result.setStatus(respData.get("trade_state")); result.setStatus(respData.get("trade_state"));
// 2. 如果订单支付成功
if ("SUCCESS".equals(respData.get("trade_state"))) { if ("SUCCESS".equals(respData.get("trade_state"))) {
byTradeNo.setSucceed(true); byTradeNo.setSucceed(true);
// 2.1 更新 userPayment 的支付状态为成功
boolean b = userPaymentRepository.updatePaymentResult(byTradeNo, true); boolean b = userPaymentRepository.updatePaymentResult(byTradeNo, true);
if (b) { if (b) {
if (balance == null) { // 2.2 获取充值优惠赠送
balance = new UserBalance();
balance.setUsername(byTradeNo.getUsername());
}
PayBack payBack = payBackRepository.findByPay(byTradeNo.getAmount()); PayBack payBack = payBackRepository.findByPay(byTradeNo.getAmount());
if (payBack == null) if (payBack == null) {
payBack = new PayBack(); payBack = new PayBack();
}
// chargeType 为 0 代表 充值
if (chargeType == 0) { if (chargeType == 0) {
UserPrePaidBilling bill = new UserPrePaidBilling(); // 2.3 构建用户充值信息并保存
Account account = accountRepository.findByName(byTradeNo.getUsername()).get(); UserPrePaidBilling bill = getUserPrePaidBilling(byTradeNo, byName, balance, payBack);
if (account != null && account.getParent() != null)
bill.setAdministrator(account.getParent());
else
bill.setAdministrator(account.getName());
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(0);
bill.setAmount(0);
bill.setUnit(null);
bill.setPeriod(0);
bill.setPayMethod(2);
bill.setUsername(byTradeNo.getUsername());
bill.setTotal((float) byTradeNo.getAmount());
bill.setStatus(BillStatus.PAID);
bill.setPrepaid(true);
bill.setTimestamp(Instant.now().toEpochMilli());
bill.setBalanced(balance.getBalanced() + byTradeNo.getAmount() + payBack.getBack());
final YearMonth lastmonth = YearMonth.now();
int monthValue = lastmonth.getMonthValue();
int year = lastmonth.getYear();
bill.setYear(year);
bill.setMonth(monthValue);
userPrePaidBillingRepository.save(bill); userPrePaidBillingRepository.save(bill);
} }
// 2.4 更新账户余额 userBalance
balance.setBalanced(balance.getBalanced() + byTradeNo.getAmount() + payBack.getBack()); balance.setBalanced(balance.getBalanced() + byTradeNo.getAmount() + payBack.getBack());
userBalanceRepository.save(balance); userBalanceRepository.save(balance);
// 2.5 如果当前用户通过邀请码注册的,则更新邀请人的佣金
if (byName.getPromotionCode() != null) { if (byName.getPromotionCode() != null) {
Account account = accountRepository.findByPromotion(byName.getPromotionCode()); Account account = accountRepository.findByPromotion(byName.getPromotionCode());
if (account != null) { if (account != null) {
...@@ -226,6 +188,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -226,6 +188,7 @@ public class PaymentServiceImpl implements PaymentService {
return result; return result;
} }
private String convertAlipayStatus(String src) { private String convertAlipayStatus(String src) {
switch (src) { switch (src) {
case "WAIT_BUYER_PAY": case "WAIT_BUYER_PAY":
...@@ -419,7 +382,6 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -419,7 +382,6 @@ public class PaymentServiceImpl implements PaymentService {
} }
try { try {
// 创建并封装 UserPayment 信息 // 创建并封装 UserPayment 信息
UserPayment internalOrder = getUserPayment(username, amount); UserPayment internalOrder = getUserPayment(username, amount);
...@@ -433,12 +395,12 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -433,12 +395,12 @@ public class PaymentServiceImpl implements PaymentService {
// 封装请求 微信支付 的数据 // 封装请求 微信支付 的数据
Map<String, String> data = encapsulateDataMap(amount, internalOrder, notifyUrl, ourWxPayConfig); Map<String, String> data = encapsulateDataMap(amount, internalOrder, notifyUrl, ourWxPayConfig);
// 调用微信支付接口,并返回支付结果 // 调用微信支付接口,支付成功后会回调 notifyUrl, 并返回支付结果
WXPay wxPay = new WXPay(ourWxPayConfig); WXPay wxPay = new WXPay(ourWxPayConfig);
Map<String, String> respData = wxPay.unifiedOrder(data); Map<String, String> respData = wxPay.unifiedOrder(data);
if (respData.get("return_code").equals("SUCCESS") && respData.get("result_code").equals("SUCCESS")) { if (respData.get("return_code").equals("SUCCESS") && respData.get("result_code").equals("SUCCESS")) {
// 若微信支付成功,则将支付信息保存到 // 若微信支付成功,则将支付信息保存到 userPayment
userPaymentRepository.save(internalOrder); userPaymentRepository.save(internalOrder);
UserPaymentDto result = new UserPaymentDto(); UserPaymentDto result = new UserPaymentDto();
result.setTradeNo(internalOrder.getTradeNo()); result.setTradeNo(internalOrder.getTradeNo());
...@@ -676,64 +638,45 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -676,64 +638,45 @@ public class PaymentServiceImpl implements PaymentService {
@Override @Override
public UserPaymentDto wxCheckOrderStatus(String tradeno) { public UserPaymentDto wxCheckOrderStatus(String tradeno) {
UserPaymentDto result = new UserPaymentDto(); UserPaymentDto result = new UserPaymentDto();
result.setPaid(false); result.setPaid(false);
try {
UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradeno); UserPayment byTradeNo = userPaymentRepository.findByTradeNo(tradeno);
if (byTradeNo == null)
return result;
if (byTradeNo.isSucceed()) {
result.setPaid(true);
return result;
}
if (PaymentMethod.ALIPAY.equals(byTradeNo.getPaymentMethod())) Account byName = accountService.findByName(byTradeNo.getUsername());
return aliCheckOrderStatus(tradeno); if (PaymentMethod.ALIPAY.equals(byTradeNo.getPaymentMethod())) {
return aliCheckOrderStatus(tradeno);
}
try {
UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null); UserBalance balance = userBalanceRepository.findById(byTradeNo.getUsername()).orElse(null);
if (balance != null) if (balance != null) {
result.setBalance(Math.round(balance.getBalanced())); result.setBalance(Math.round(balance.getBalanced()));
if (byTradeNo == null)
return result;
if (byTradeNo.isSucceed()) {
result.setPaid(true);
return result;
} }
Account byName = accountService.findByName(byTradeNo.getUsername());
if (byName == null)
throw new ClientRequestException(AccountErrorCode.NAMENOTEXIST, "account does not exist: " + byTradeNo.getUsername());
boolean isVpsClient = true; boolean isVpsClient = true;
WXPayConfig ourWxPayConfig = isVpsClient ? new FGLWxConfig() : new CloudamWxConfig(); WXPayConfig ourWxPayConfig = isVpsClient ? new FGLWxConfig() : new CloudamWxConfig();
WXPay wxPay = new WXPay(ourWxPayConfig); WXPay wxPay = new WXPay(ourWxPayConfig);
Map<String, String> data = encapsulateWxOrderDataMap(tradeno, ourWxPayConfig);
Map<String, String> data = new HashMap<>();
data.put("appid", ourWxPayConfig.getAppID());
data.put("mch_id", ourWxPayConfig.getMchID()); //商户号
data.put("out_trade_no", tradeno); //交易号
data.put("nonce_str", SmsUtils.createRandom(false, 24)); // 随机字符串小于32位
String s = WXPayUtil.generateSignature(data, ourWxPayConfig.getKey()); //签名
data.put("sign", s);
Map<String, String> respData = wxPay.orderQuery(data); Map<String, String> respData = wxPay.orderQuery(data);
if (respData.get("return_code").equals("SUCCESS") && respData.get("return_msg").equals("OK") && "SUCCESS".equals(respData.get("result_code"))) { if (respData.get("return_code").equals("SUCCESS") && respData.get("return_msg").equals("OK") && "SUCCESS".equals(respData.get("result_code"))) {
/*
/** * SUCCESS—支付成功
* * REFUND—转入退款
SUCCESS—支付成功 * NOTPAY—未支付
* CLOSED—已关闭
REFUND—转入退款 * REVOKED—已撤销(付款码支付)
* USERPAYING--用户支付中(付款码支付)
NOTPAY—未支付 * PAYERROR--支付失败(其他原因,如银行返回失败)
CLOSED—已关闭
REVOKED—已撤销(付款码支付)
USERPAYING--用户支付中(付款码支付)
PAYERROR--支付失败(其他原因,如银行返回失败) *
*/ */
result.setStatus(respData.get("trade_state")); result.setStatus(respData.get("trade_state"));
if ("SUCCESS".equals(respData.get("trade_state"))) { if ("SUCCESS".equals(respData.get("trade_state"))) {
...@@ -837,6 +780,7 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -837,6 +780,7 @@ public class PaymentServiceImpl implements PaymentService {
UserPayment internalOrder = new UserPayment(); UserPayment internalOrder = new UserPayment();
internalOrder.setAmount(amount); internalOrder.setAmount(amount);
internalOrder.setPaymentMethod(PaymentMethod.WECHAT); internalOrder.setPaymentMethod(PaymentMethod.WECHAT);
// 此时充值尚未成功,需要等微信回调才能确认是否成功
internalOrder.setSucceed(false); internalOrder.setSucceed(false);
internalOrder.setUsername(username); internalOrder.setUsername(username);
return internalOrder; return internalOrder;
...@@ -860,4 +804,46 @@ public class PaymentServiceImpl implements PaymentService { ...@@ -860,4 +804,46 @@ public class PaymentServiceImpl implements PaymentService {
return data; return data;
} }
@NotNull
private Map<String, String> encapsulateWxOrderDataMap(String tradeno, WXPayConfig ourWxPayConfig) throws Exception {
Map<String, String> data = new HashMap<>();
data.put("appid", ourWxPayConfig.getAppID());
data.put("mch_id", ourWxPayConfig.getMchID()); //商户号
data.put("out_trade_no", tradeno); //交易号
data.put("nonce_str", SmsUtils.createRandom(false, 24)); // 随机字符串小于32位
String s = WXPayUtil.generateSignature(data, ourWxPayConfig.getKey()); //签名
data.put("sign", s);
return data;
}
@NotNull
private UserPrePaidBilling getUserPrePaidBilling(UserPayment byTradeNo, Account byName, UserBalance balance, PayBack payBack) {
UserPrePaidBilling bill = new UserPrePaidBilling();
if (byName != null && byName.getParent() != null) {
bill.setAdministrator(byName.getParent());
} else {
bill.setAdministrator(byName.getName());
}
bill.setTradeNo(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + SmsUtils.createRandom(true, 4));
bill.setChargeType(0);
bill.setAmount(0);
bill.setUnit(null);
bill.setPeriod(0);
bill.setPayMethod(2);
bill.setUsername(byTradeNo.getUsername());
bill.setTotal((float) byTradeNo.getAmount());
bill.setStatus(BillStatus.PAID);
bill.setPrepaid(true);
bill.setTimestamp(Instant.now().toEpochMilli());
// 设置到账金额为 账户余额 + 充值金额 + 充值优惠赠送
bill.setBalanced(balance.getBalanced() + byTradeNo.getAmount() + payBack.getBack());
final YearMonth lastmonth = YearMonth.now();
int monthValue = lastmonth.getMonthValue();
int year = lastmonth.getYear();
bill.setYear(year);
bill.setMonth(monthValue);
return bill;
}
} }
...@@ -32,6 +32,7 @@ public class PaymentTask { ...@@ -32,6 +32,7 @@ public class PaymentTask {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Date date_5min = new Date(now - 5 * 60 * 1000); Date date_5min = new Date(now - 5 * 60 * 1000);
Date date_10min = new Date(now - 10 * 60 * 1000); Date date_10min = new Date(now - 10 * 60 * 1000);
// 查找 5-10 分钟内 支付状态为 false 的订单
List<UserPayment> unfinishedPayments = userPaymentRepository.findAllByPaymentDateBetweenAndSucceed( List<UserPayment> unfinishedPayments = userPaymentRepository.findAllByPaymentDateBetweenAndSucceed(
ZonedDateTime.ofInstant(date_10min.toInstant(), ZoneId.systemDefault()), ZonedDateTime.ofInstant(date_10min.toInstant(), ZoneId.systemDefault()),
ZonedDateTime.ofInstant(date_5min.toInstant(), ZoneId.systemDefault()), ZonedDateTime.ofInstant(date_5min.toInstant(), ZoneId.systemDefault()),
...@@ -41,8 +42,8 @@ public class PaymentTask { ...@@ -41,8 +42,8 @@ public class PaymentTask {
unfinishedPayments.forEach( unfinishedPayments.forEach(
payment -> { payment -> {
PaymentMethod paymentMethod = payment.getPaymentMethod(); PaymentMethod paymentMethod = payment.getPaymentMethod();
try { try {
// 自动调用 微信或者支付宝的支付接口来确认 支付状态
if (PaymentMethod.WECHAT.equals(paymentMethod)) { if (PaymentMethod.WECHAT.equals(paymentMethod)) {
paymentService.wxCheckOrderStatus(payment.getTradeNo()); paymentService.wxCheckOrderStatus(payment.getTradeNo());
} }
......
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