From 7d967ed41eead94fc37acd916296c5e8a31efb01 Mon Sep 17 00:00:00 2001 From: xupei Date: Thu, 28 Mar 2024 14:43:36 +0800 Subject: [PATCH 1/5] =?UTF-8?q?1=E3=80=81=E5=AE=8C=E5=96=84=E7=A7=AF?= =?UTF-8?q?=E5=88=86=E5=85=85=E5=80=BC=202=E3=80=81=E5=8D=87=E7=BA=A7?= =?UTF-8?q?=E7=A7=AF=E5=88=86=E6=89=A3=E9=99=A4=E6=9C=BA=E5=88=B6=203?= =?UTF-8?q?=E3=80=81=E4=BC=98=E5=8C=96=E9=83=A8=E5=88=86=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ai/da/common/RabbitMQ/MQConfig.java | 12 +-- .../ai/da/common/constant/CommonConstant.java | 10 +++ .../constant/PayPalCheckoutConstant.java | 9 --- .../ai/da/common/enums/CreditsEventsEnum.java | 2 +- .../com/ai/da/common/utils/RedisUtil.java | 8 ++ .../controller/PayPalCheckoutController.java | 5 -- .../ai/da/mapper/primary/entity/Product.java | 2 + .../com/ai/da/service/CreditsService.java | 4 + .../da/service/impl/CreditsServiceImpl.java | 78 +++++++++++++++++-- .../impl/PayPalCheckoutServiceImpl.java | 30 ++++--- .../impl/SuperResolutionServiceImpl.java | 30 +++---- .../da/service/impl/TaskListServiceImpl.java | 11 +-- 12 files changed, 142 insertions(+), 59 deletions(-) create mode 100644 src/main/java/com/ai/da/common/constant/CommonConstant.java diff --git a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java index 79ecda25..78e6fc25 100644 --- a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java +++ b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java @@ -10,14 +10,14 @@ public class MQConfig { public static final String GENERATE_EXCHANGE_FANOUT = "generate-exchange"; // public static final String GENERATE_QUEUE = "generate-queue-prod"; // public static final String GENERATE_QUEUE = "generate-queue-test"; - public static final String GENERATE_QUEUE = "generate-queue-dev"; -// public static final String GENERATE_QUEUE = "generate-queue"; +// public static final String GENERATE_QUEUE = "generate-queue-dev"; + public static final String GENERATE_QUEUE = "generate-queue-local"; - public static final String SR_QUEUE = "SR-queue-dev"; -// public static final String SR_QUEUE = "SR-queue-local"; +// public static final String SR_QUEUE = "SR-queue-dev"; + public static final String SR_QUEUE = "SR-queue-local"; - // public static final String SR_RESULT_QUEUE = "SuperResolution-local"; - public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; + public static final String SR_RESULT_QUEUE = "SuperResolution-local"; +// public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; public MQConfig() { } diff --git a/src/main/java/com/ai/da/common/constant/CommonConstant.java b/src/main/java/com/ai/da/common/constant/CommonConstant.java new file mode 100644 index 00000000..f7ad3b1c --- /dev/null +++ b/src/main/java/com/ai/da/common/constant/CommonConstant.java @@ -0,0 +1,10 @@ +package com.ai.da.common.constant; + +public class CommonConstant { + // 单位 秒 一天过期 + public static final Long TASK_EXPIRE_TIME = 24 * 60 * 60L; + // 单位 秒 两天过期 + public static final Long CREDITS_EXPIRE_TIME = 2 * 24 * 60 * 60L; + // 单位 分钟 + public static final Integer MINIO_IMAGE_EXPIRE_TIME = 24 * 60; +} diff --git a/src/main/java/com/ai/da/common/constant/PayPalCheckoutConstant.java b/src/main/java/com/ai/da/common/constant/PayPalCheckoutConstant.java index 31cc4adf..21b3694b 100644 --- a/src/main/java/com/ai/da/common/constant/PayPalCheckoutConstant.java +++ b/src/main/java/com/ai/da/common/constant/PayPalCheckoutConstant.java @@ -2,9 +2,6 @@ package com.ai.da.common.constant; public class PayPalCheckoutConstant { -// public static String MODE = "sandbox"; - public static String MODE = "live"; - public static final String CAPTURE = "CAPTURE"; /** * 该标签将覆盖PayPal网站上PayPal帐户中的公司名称 @@ -168,12 +165,6 @@ public class PayPalCheckoutConstant { public final static String CMD_NOTIFY_VALIDATE = "_notify-validate"; -// public final static String WEBHOOK_ID = "31797347YC028794L"; - // kim-sandbox -// public final static String WEBHOOK_ID = "1WH327112B602422N"; - // kim-live - public final static String WEBHOOK_ID = "41L14847MC833625B"; - public final static String PAYPAL_TOKEN_KEY = "PayPalAccessToken"; diff --git a/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java b/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java index 23566466..a244bead 100644 --- a/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java +++ b/src/main/java/com/ai/da/common/enums/CreditsEventsEnum.java @@ -9,7 +9,7 @@ public enum CreditsEventsEnum { PRICE("price","1"), // 6USD -> 1000 points ==> 10HKD -> 215 points ==> 2HKD -> 43points - BUY_CREDITS("Buy Credits","43"), + BUY_CREDITS("Buy Credits","50"), INIT("init", "1000"), diff --git a/src/main/java/com/ai/da/common/utils/RedisUtil.java b/src/main/java/com/ai/da/common/utils/RedisUtil.java index 9fa37738..ef67de8f 100644 --- a/src/main/java/com/ai/da/common/utils/RedisUtil.java +++ b/src/main/java/com/ai/da/common/utils/RedisUtil.java @@ -136,6 +136,10 @@ public class RedisUtil { } //- - - - - - - - - - - - - - - - - - - - - String类型 - - - - - - - - - - - - - - - - - - - - + public void addToString(String key, String value){ + redisTemplate.opsForValue().set(key,value); + } + public void addToString(String key, String value, Long expiresIn){ redisTemplate.opsForValue().set(key,value,expiresIn, TimeUnit.SECONDS); } @@ -156,4 +160,8 @@ public class RedisUtil { return redisTemplate.getExpire(key); } + public void removeFromString(String key){ + redisTemplate.delete(key); + } + } diff --git a/src/main/java/com/ai/da/controller/PayPalCheckoutController.java b/src/main/java/com/ai/da/controller/PayPalCheckoutController.java index 2ed119a7..d1ad9134 100644 --- a/src/main/java/com/ai/da/controller/PayPalCheckoutController.java +++ b/src/main/java/com/ai/da/controller/PayPalCheckoutController.java @@ -1,7 +1,6 @@ package com.ai.da.controller; import com.ai.da.common.response.Response; -import com.ai.da.service.CallBackService; import com.ai.da.service.PayPalCheckoutService; import com.paypal.http.HttpResponse; import com.paypal.http.exceptions.SerializeException; @@ -61,7 +60,6 @@ public class PayPalCheckoutController { }else { return Response.fail("Request for refund failed."); } - } @ApiOperation("执行扣款") @@ -70,8 +68,5 @@ public class PayPalCheckoutController { Order response = payPalCheckoutService.captureOrder(orderNo); return Response.success(response); } - - - } diff --git a/src/main/java/com/ai/da/mapper/primary/entity/Product.java b/src/main/java/com/ai/da/mapper/primary/entity/Product.java index de2df0cf..ddea327e 100644 --- a/src/main/java/com/ai/da/mapper/primary/entity/Product.java +++ b/src/main/java/com/ai/da/mapper/primary/entity/Product.java @@ -10,4 +10,6 @@ public class Product extends BaseEntity{ private String title; //商品名称 private Integer price; //价格(分) + + private Integer credits; // 积分 } diff --git a/src/main/java/com/ai/da/service/CreditsService.java b/src/main/java/com/ai/da/service/CreditsService.java index a2947b5b..a9d35d17 100644 --- a/src/main/java/com/ai/da/service/CreditsService.java +++ b/src/main/java/com/ai/da/service/CreditsService.java @@ -26,4 +26,8 @@ public interface CreditsService extends IService { PageBaseResponse queryCreditsDetailsPage(QueryIncomeOrExpenditureDTO queryPageByTimeDTO); Boolean checkCredits(Long accountId, CreditsEventsEnum event, Integer num); + + Boolean creditsPreDeduction(CreditsEventsEnum event, Integer num); + + void taskCreditsDeduction(Long accountId, String taskId); } diff --git a/src/main/java/com/ai/da/service/impl/CreditsServiceImpl.java b/src/main/java/com/ai/da/service/impl/CreditsServiceImpl.java index 10342ad0..c947ac97 100644 --- a/src/main/java/com/ai/da/service/impl/CreditsServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/CreditsServiceImpl.java @@ -4,6 +4,7 @@ import com.ai.da.common.config.exception.BusinessException; import com.ai.da.common.context.UserContext; import com.ai.da.common.enums.CreditsEventsEnum; import com.ai.da.common.response.PageBaseResponse; +import com.ai.da.common.utils.RedisUtil; import com.ai.da.mapper.primary.AccountMapper; import com.ai.da.mapper.primary.CreditsDetailMapper; import com.ai.da.mapper.primary.entity.Account; @@ -15,23 +16,31 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import io.netty.util.internal.StringUtil; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import javax.annotation.Resource; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.List; import java.util.Objects; +import java.util.Set; @Service public class CreditsServiceImpl extends ServiceImpl implements CreditsService { - @Resource - private AccountService accountService; + @Value("${redis.key.credits.pre-deduction}") + private String creditsDeduction; + @Resource + private AccountService accountService; @Resource private AccountMapper accountMapper; + @Resource + private RedisUtil redisUtil; @Override public void initCredits() { @@ -116,20 +125,20 @@ public class CreditsServiceImpl extends ServiceImpl keys = redisUtil.getKeysFromString(creditsDeduction + ":" + accountId + ":*"); + List multiValue = redisUtil.getMultiValue(keys); + int sum = multiValue.stream().mapToInt(Integer::parseInt).sum(); + sum += Integer.parseInt(event.getValue()) * num; + + // 2、获取当前积分 + BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits(); + BigDecimal subtract = existingCredits.subtract(new BigDecimal(sum)); + + // 3、判断剩余积分是否够本次操作 + if (subtract.compareTo(BigDecimal.ZERO) < 0){ + // 3.1 不够,直接返回余额不够,充值 + return Boolean.FALSE; + } + + return Boolean.TRUE; + } + + /** 执行扣除积分,更新数据库 */ + @Override + @Transactional(rollbackFor = Exception.class) + public void taskCreditsDeduction(Long accountId, String taskId){ + String key = creditsDeduction + ":" + accountId + ":" + taskId; + // 1、获取当前任务id对应的积分 + String value = redisUtil.getFromString(key); + + // 1.1 没有。返回,报错,未找到当前任务 + if (StringUtil.isNullOrEmpty(value)){ + throw new BusinessException("当前任务不存在,无法扣除积分"); + } + + // 2、操作数据库,扣除积分 + BigDecimal existingCredits = accountMapper.selectById(accountId).getCredits(); + BigDecimal subtract = existingCredits.subtract(new BigDecimal(value)); + accountService.updateCredits(accountId, subtract.toString()); + + // 3、从redis中移除当前待扣积分 + redisUtil.removeFromString(key); + } + } diff --git a/src/main/java/com/ai/da/service/impl/PayPalCheckoutServiceImpl.java b/src/main/java/com/ai/da/service/impl/PayPalCheckoutServiceImpl.java index bc7c7434..929cb3c5 100644 --- a/src/main/java/com/ai/da/service/impl/PayPalCheckoutServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/PayPalCheckoutServiceImpl.java @@ -62,6 +62,12 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { @Value("${paypal.client-secret}") private String clientSecret; + @Value("${paypal.mode}") + private String mode; + + @Value("${paypal.webhook_id}") + private String webhookId; + @Resource private PayPalClient payPalClient; @Resource @@ -90,7 +96,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { request.requestBody(buildRequestBody(String.valueOf(orderInfo.getTotalFee()), returnUrl)); HttpResponse response = null; try { - response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + response = payPalClient.client(mode, clientId, clientSecret).execute(request); } catch (Exception e) { log.error("调用paypal订单创建失败,失败原因 ===> {}", e.getMessage()); throw new BusinessException("Order creation failed"); @@ -136,21 +142,21 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { webhookRequest.put("transmission_id", SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-ID")); webhookRequest.put("transmission_sig", SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-SIG")); webhookRequest.put("transmission_time", SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-TIME")); - webhookRequest.put("webhook_id", PayPalCheckoutConstant.WEBHOOK_ID); + webhookRequest.put("webhook_id", webhookId); webhookRequest.put("webhook_event", webhookEvent); WebhookVerifyRequest webhookVerifyRequest = new WebhookVerifyRequest(); webhookVerifyRequest.authorization(getOAuth()); webhookVerifyRequest.requestBody(webhookRequest); // 验签 - HttpResponse verified = payPalClient.client(MODE, clientId, clientSecret).execute(webhookVerifyRequest); + HttpResponse verified = payPalClient.client(mode, clientId, clientSecret).execute(webhookVerifyRequest); boolean verifyResult = verified.result().get("verification_status").toString().equals("SUCCESS"); if (verifyResult) { // ### Api Context - APIContext apiContext = new APIContext(clientId, clientSecret, PayPalCheckoutConstant.MODE); + APIContext apiContext = new APIContext(clientId, clientSecret, mode); // Set the webhookId that you received when you created this webhook. - apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, PayPalCheckoutConstant.WEBHOOK_ID); + apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, webhookId); Boolean result = Event.validateReceivedEvent(apiContext, getHeadersInfo( req), body); log.info("Webhook Validated: " + result); @@ -328,7 +334,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { HttpResponse response = null; try { - response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + response = payPalClient.client(mode, clientId, clientSecret).execute(request); } catch (Exception e) { log.error("paypal订单查询失败,失败原因 ===> {}", e.getMessage()); } @@ -371,7 +377,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { HttpResponse response; try { - response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + response = payPalClient.client(mode, clientId, clientSecret).execute(request); } catch (Exception e) { log.error("调用paypal扣款失败,失败原因 ===> {}", e.getMessage()); throw new BusinessException("Order deduction failed."); @@ -421,7 +427,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { public String queryCapture(String orderNo) throws IOException { CapturesGetRequest request = new CapturesGetRequest("扣款id, CaptureOrder生成"); - HttpResponse response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + HttpResponse response = payPalClient.client(mode, clientId, clientSecret).execute(request); System.out.println("Status Code: " + response.statusCode()); System.out.println("Status: " + response.result().status()); System.out.println("Capture ids: " + response.result().id()); @@ -449,7 +455,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { ordersGetRequest.authorization("Bearer " + getOAuth()); boolean result; try { - ordersGetResponse = payPalClient.client(MODE, clientId, clientSecret).execute(ordersGetRequest); + ordersGetResponse = payPalClient.client(mode, clientId, clientSecret).execute(ordersGetRequest); } catch (Exception e) { log.error("调用paypal订单查询失败,失败原因 ===> {}", e.getMessage()); throw new BusinessException("Order query failed"); @@ -463,7 +469,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { request.requestBody(buildRefundRequestBody(String.valueOf(orderInfo.getTotalFee()), reason)); HttpResponse response = null; try { - response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + response = payPalClient.client(mode, clientId, clientSecret).execute(request); } catch (IOException e) { log.error("调用paypal退款申请失败,失败原因 {}", e.getMessage()); throw new BusinessException("Request for refund failed"); @@ -529,7 +535,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { */ public String queryRefund(String orderNo) throws IOException { RefundsGetRequest request = new RefundsGetRequest("退款id RefundOrder生成"); - HttpResponse response = payPalClient.client(MODE, clientId, clientSecret).execute(request); + HttpResponse response = payPalClient.client(mode, clientId, clientSecret).execute(request); System.out.println("Status Code: " + response.statusCode()); System.out.println("Status: " + response.result().status()); System.out.println("Refund Id: " + response.result().id()); @@ -554,7 +560,7 @@ public class PayPalCheckoutServiceImpl implements PayPalCheckoutService { AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.authorization(clientId, clientSecret); try { - HttpResponse authResult = payPalClient.client(MODE, clientId, clientSecret).execute(authenticationRequest); + HttpResponse authResult = payPalClient.client(mode, clientId, clientSecret).execute(authenticationRequest); String accessToken = authResult.result().get("access_token").toString(); long expiresIn = Long.parseLong(authResult.result().get("expires_in").toString()); // 3、存redis diff --git a/src/main/java/com/ai/da/service/impl/SuperResolutionServiceImpl.java b/src/main/java/com/ai/da/service/impl/SuperResolutionServiceImpl.java index c9ecdec7..eeb565e8 100644 --- a/src/main/java/com/ai/da/service/impl/SuperResolutionServiceImpl.java +++ b/src/main/java/com/ai/da/service/impl/SuperResolutionServiceImpl.java @@ -1,6 +1,7 @@ package com.ai.da.service.impl; import com.ai.da.common.config.exception.BusinessException; +import com.ai.da.common.constant.CommonConstant; import com.ai.da.common.context.UserContext; import com.ai.da.common.enums.CreditsEventsEnum; import com.ai.da.common.response.PageBaseResponse; @@ -65,25 +66,24 @@ public class SuperResolutionServiceImpl extends ServiceImpl prepareForSR(List superResolutionDTOList) { Long accountId = UserContext.getUserHolder().getId(); // 1、判断用户当前积分是否够本次超分消耗 - - Boolean credits = creditsService.checkCredits(accountId, CreditsEventsEnum.SUPER_RESOLUTION, superResolutionDTOList.size()); - // todo 积分扣除待升级 - if (credits) { - // 先扣除积分,后失败后再加上 - creditsService.creditsDecrease(accountId, CreditsEventsEnum.SUPER_RESOLUTION.getName()); - } else { + Boolean preDeduction = creditsService.creditsPreDeduction(CreditsEventsEnum.SUPER_RESOLUTION, superResolutionDTOList.size()); + if (!preDeduction) { throw new BusinessException("Not enough Credits"); } ArrayList uuidList = new ArrayList<>(); - for (SuperResolutionDTO superResolutionDTO : superResolutionDTOList) { + // todo 校验倍率是否是2的幂次(前端已做) + // 2、生成唯一id 使用uuid String uuid = UUID.randomUUID().toString(); int num = 1; @@ -119,17 +119,20 @@ public class SuperResolutionServiceImpl extends ServiceImpl(uuid, "SR", name.substring(name.lastIndexOf("/") + 1), superResolutionDTO, "Waiting", LocalDateTime.now().format(dateTimeFormatter))); - // 6、将消息发布到MQ消息队列 + // 7、将消息发布到MQ消息队列 log.info("发送消息到SR_QUEUE,参数 :{}", jsonString); rabbitMQService.publishMessageToSR(jsonString); } - // 6、返回唯一id列表 + // 8、返回唯一id列表 return uuidList; } @@ -156,9 +159,8 @@ public class SuperResolutionServiceImpl extends ServiceImpl i taskDTOS.add(new TaskDTO<>()); } else { SuperResolutionDTO inputParam = taskDTO.getInputParam(); - inputParam.setImages(minioUtil.getPresignedUrl(inputParam.getImages(), 24 * 60)); - taskDTO.setOutputImage(StringUtil.isNullOrEmpty(taskDTO.getOutputImage()) ? null : minioUtil.getPresignedUrl(taskDTO.getOutputImage(), 24 * 60)); + inputParam.setImages(minioUtil.getPresignedUrl(inputParam.getImages(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + taskDTO.setOutputImage(StringUtil.isNullOrEmpty(taskDTO.getOutputImage()) ? null : minioUtil.getPresignedUrl(taskDTO.getOutputImage(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); taskDTOS.add(taskDTO); } }); @@ -71,7 +72,7 @@ public class TaskListServiceImpl extends ServiceImpl i public void addToTaskListRedis(TaskDTO taskDTO) { String key = taskListKey + ":" + UserContext.getUserHolder().getId() + ":" + taskDTO.getTaskId(); - redisUtil.addToString(key, new Gson().toJson(taskDTO), 24L * 60 * 60 * 3); + redisUtil.addToString(key, new Gson().toJson(taskDTO), CommonConstant.TASK_EXPIRE_TIME); } // 3、更新任务状态 @@ -104,8 +105,8 @@ public class TaskListServiceImpl extends ServiceImpl i // 成功失败的都返回 TaskVO task = new TaskVO(); task.setImageName(s.getInputUrl().substring(s.getInputUrl().lastIndexOf("/") + 1)); - task.setInputImage(minioUtil.getPresignedUrl(s.getInputUrl(), 24 * 60)); - task.setOutputImage(StringUtil.isNullOrEmpty(s.getOutputUrl()) ? null : minioUtil.getPresignedUrl(s.getOutputUrl(), 24 * 60)); + task.setInputImage(minioUtil.getPresignedUrl(s.getInputUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); + task.setOutputImage(StringUtil.isNullOrEmpty(s.getOutputUrl()) ? null : minioUtil.getPresignedUrl(s.getOutputUrl(), CommonConstant.MINIO_IMAGE_EXPIRE_TIME)); task.setStatus(s.getStatus()); task.setTaskId(s.getTaskId()); task.setCreateDate(s.getCreateTime().format(dateTimeFormatter)); From 784f599e381b6c70af2633963b4124fe62c5a2cf Mon Sep 17 00:00:00 2001 From: xupei Date: Thu, 28 Mar 2024 15:04:31 +0800 Subject: [PATCH 2/5] paypal live-> sandbox --- src/main/resources/application-dev.properties | 3 ++- src/main/resources/paypal-sandbox.properties | 26 +++++++++---------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties index 5cbffad1..c5e8ddb4 100644 --- a/src/main/resources/application-dev.properties +++ b/src/main/resources/application-dev.properties @@ -82,4 +82,5 @@ redis.key.resultMap=ResultMap redis.key.orderForSR=OrderForSR redis.key.SRCancelSet=SRCancelSet redis.key.SRExceptionMap=SRExceptionMap -redis.key.taskList=TaskList \ No newline at end of file +redis.key.taskList=TaskList +redis.key.credits.pre-deduction=Credits:PreDeduction \ No newline at end of file diff --git a/src/main/resources/paypal-sandbox.properties b/src/main/resources/paypal-sandbox.properties index aea3ac83..cb35664d 100644 --- a/src/main/resources/paypal-sandbox.properties +++ b/src/main/resources/paypal-sandbox.properties @@ -1,20 +1,20 @@ -# developer-sandbox -#paypal.client-id=ATbaebYi7-GXWRWJqwRLYMzKEbwjh4BFRqD4Y13i4lZq0rplWIM_IpPrtPKpdkAt_KrPXd6IJTwsDqa5 -#paypal.client-secret=EHWWJqGmmbfjLXqCUpGrvxRYBPPtWvA3hR5ZaAyHlGSVJiHoQPS8skbNaJ9h39VObnchUbgiY2pPu__s -#paypal.receiver.email=sb-ukxfk29608925@business.example.com -#paypal.mode=sandbox -#paypal.webhook_id=31797347YC028794L +# developer-sandbox-xp +paypal.client-id=ATbaebYi7-GXWRWJqwRLYMzKEbwjh4BFRqD4Y13i4lZq0rplWIM_IpPrtPKpdkAt_KrPXd6IJTwsDqa5 +paypal.client-secret=EHWWJqGmmbfjLXqCUpGrvxRYBPPtWvA3hR5ZaAyHlGSVJiHoQPS8skbNaJ9h39VObnchUbgiY2pPu__s +paypal.receiver.email=sb-ukxfk29608925@business.example.com +paypal.mode=sandbox +paypal.webhook_id=31797347YC028794L -# aida-sandbox +# aida-sandbox-kim #paypal.client-id=AbDDH8jnTrKqjnWLFgEu6LogYzVz2ZLuirE4W54t1M4lrofrP5OzXfhbxqktLLFB-rAO9KeYQVYFJ_tO #paypal.client-secret=EOOoiIAe_dyR2YhY7qCIqWipZvYXCDrmBlFYchphuvkPFms1spsBGTlStlrx580y4hN-EukWwF9m_LAs #paypal.receiver.email=sb-4xe8i29784722@business.example.com #paypal.mode=sandbox #paypal.webhook_id=1WH327112B602422N -# aida-live -paypal.client-id=ASWSIZ3MXJU5w5VOeOHeigWcSw6iinl30ZCipruziKpHclxP0ryf8-7VKG1Ba2VwZwa2DMvGEzTfCTgz -paypal.client-secret=EHQg_K5PSqmp4FJlzEcOEH_kFkmq4aBzaI7jridw53L6cOQRULBAnfv2KakRfrsqaU1PDSkO4Co9Vyxc -paypal.receiver.email=kimwong@code-create.com.hk -paypal.mode=live -paypal.webhook_id=41L14847MC833625B \ No newline at end of file +# aida-live-kim +#paypal.client-id=ASWSIZ3MXJU5w5VOeOHeigWcSw6iinl30ZCipruziKpHclxP0ryf8-7VKG1Ba2VwZwa2DMvGEzTfCTgz +#paypal.client-secret=EHQg_K5PSqmp4FJlzEcOEH_kFkmq4aBzaI7jridw53L6cOQRULBAnfv2KakRfrsqaU1PDSkO4Co9Vyxc +#paypal.receiver.email=kimwong@code-create.com.hk +#paypal.mode=live +#paypal.webhook_id=41L14847MC833625B \ No newline at end of file From 165f0301f0b8a6b3831255c504542f67c6ba090e Mon Sep 17 00:00:00 2001 From: xupei Date: Thu, 28 Mar 2024 15:07:33 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E5=88=A0=E9=99=A4callbackService?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/ai/da/service/CallBackService.java | 12 -- .../da/service/impl/CallBackServiceImpl.java | 159 ------------------ 2 files changed, 171 deletions(-) delete mode 100644 src/main/java/com/ai/da/service/CallBackService.java delete mode 100644 src/main/java/com/ai/da/service/impl/CallBackServiceImpl.java diff --git a/src/main/java/com/ai/da/service/CallBackService.java b/src/main/java/com/ai/da/service/CallBackService.java deleted file mode 100644 index 39efb1eb..00000000 --- a/src/main/java/com/ai/da/service/CallBackService.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.ai.da.service; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -public interface CallBackService { - - Boolean doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException; -} diff --git a/src/main/java/com/ai/da/service/impl/CallBackServiceImpl.java b/src/main/java/com/ai/da/service/impl/CallBackServiceImpl.java deleted file mode 100644 index 7c5fd42f..00000000 --- a/src/main/java/com/ai/da/service/impl/CallBackServiceImpl.java +++ /dev/null @@ -1,159 +0,0 @@ -package com.ai.da.service.impl; - -import com.ai.da.common.config.PayPalClient; -import com.ai.da.common.constant.PayPalCheckoutConstant; -import com.ai.da.common.utils.paypalRequest.WebhookVerifyRequest; -import com.ai.da.service.CallBackService; -import com.ai.da.service.PayPalCheckoutService; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.paypal.api.payments.Event; -import com.paypal.base.Constants; -import com.paypal.base.SDKUtil; -import com.paypal.base.rest.APIContext; -import com.paypal.base.rest.PayPalRESTException; -import com.paypal.http.HttpResponse; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Service; - -import javax.annotation.Resource; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Map; - -import static com.ai.da.common.constant.PayPalCheckoutConstant.MODE; - -// #Validate Webhook Sample -// -// This sample code demonstrates how to validate a webhook received on your -// web server. This sample assumes that you use the java servlet, which returns -// the HttpServletRequest object. However, you can modify this code to -// your specific case. -// - -@Slf4j -@Service -public class CallBackServiceImpl implements CallBackService { - - @Value("${paypal.client-id}") - private String clientId; - - @Value("${paypal.client-secret}") - private String clientSecret; - - @Resource - private PayPalClient payPalClient; - - @Resource - private PayPalCheckoutService payPalCheckoutService; - - @Override - public Boolean doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - return doPost(req, resp); - } - - // ##Validate Webhook - protected Boolean doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - try { - String body = getBody(req); - Map webhookEvent = new ObjectMapper().readValue(body, Map.class); - - HashMap webhookRequest = new HashMap<>(); - webhookRequest.put("auth_algo",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-AUTH-ALGO")); - webhookRequest.put("cert_url",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-CERT-URL")); - webhookRequest.put("transmission_id",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-ID")); - webhookRequest.put("transmission_sig",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-SIG")); - webhookRequest.put("transmission_time",SDKUtil.validateAndGet(getHeadersInfo(req), "PAYPAL-TRANSMISSION-TIME")); - webhookRequest.put("webhook_id",PayPalCheckoutConstant.WEBHOOK_ID); - webhookRequest.put("webhook_event",webhookEvent); - - WebhookVerifyRequest webhookVerifyRequest = new WebhookVerifyRequest(); - webhookVerifyRequest.authorization(payPalCheckoutService.getOAuth()); - webhookVerifyRequest.requestBody(webhookRequest); - // 验签 - HttpResponse verified = payPalClient.client(MODE, clientId, clientSecret).execute(webhookVerifyRequest); - boolean verifyResult = verified.result().get("verification_status").toString().equals("SUCCESS"); - if (verifyResult){ - // ### Api Context - APIContext apiContext = new APIContext(clientId, clientSecret, PayPalCheckoutConstant.MODE); - - // Set the webhookId that you received when you created this webhook. - apiContext.addConfiguration(Constants.PAYPAL_WEBHOOK_ID, PayPalCheckoutConstant.WEBHOOK_ID); - Boolean result = Event.validateReceivedEvent(apiContext, getHeadersInfo( - req), body); - log.info("Webhook Validated: " + result); - - if (result){ - // 处理订单数据 - LinkedHashMap> webhookEventMap = (LinkedHashMap>) webhookEvent; - String orderId = webhookEventMap.get("resource").get("id"); - payPalCheckoutService.processOrder(orderId); - return Boolean.TRUE; - } - - } - } catch (PayPalRESTException | InvalidKeyException | NoSuchAlgorithmException | SignatureException e) { - log.error(e.getMessage()); - } - return Boolean.FALSE; - } - - // Simple helper method to help you extract the headers from HttpServletRequest object. - private static Map getHeadersInfo(HttpServletRequest request) { - Map map = new HashMap(); - @SuppressWarnings("rawtypes") - Enumeration headerNames = request.getHeaderNames(); - while (headerNames.hasMoreElements()) { - String key = (String) headerNames.nextElement(); - String value = request.getHeader(key); - map.put(key, value); - } - return map; - } - - // Simple helper method to fetch request data as a string from HttpServletRequest object. - private static String getBody(HttpServletRequest request) throws IOException { - String body; - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader bufferedReader = null; - try { - InputStream inputStream = request.getInputStream(); - if (inputStream != null) { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - char[] charBuffer = new char[128]; - int bytesRead = -1; - while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { - stringBuilder.append(charBuffer, 0, bytesRead); - } - } else { - stringBuilder.append(""); - } - } catch (IOException ex) { - throw ex; - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (IOException ex) { - throw ex; - } - } - } - body = stringBuilder.toString(); - log.info("回调参数 ===> {}", body); - return body; - } -} From 8d77cd0be67da75143efc031f50972d71c1587e7 Mon Sep 17 00:00:00 2001 From: xupei Date: Thu, 28 Mar 2024 15:53:04 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E4=BF=AE=E6=94=B9dev=E7=8E=AF=E5=A2=83?= =?UTF-8?q?=E4=B8=8Bpaypal=20webhook=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/paypal-sandbox.properties | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/resources/paypal-sandbox.properties b/src/main/resources/paypal-sandbox.properties index cb35664d..1b48960c 100644 --- a/src/main/resources/paypal-sandbox.properties +++ b/src/main/resources/paypal-sandbox.properties @@ -3,7 +3,10 @@ paypal.client-id=ATbaebYi7-GXWRWJqwRLYMzKEbwjh4BFRqD4Y13i4lZq0rplWIM_IpPrtPKpdkA paypal.client-secret=EHWWJqGmmbfjLXqCUpGrvxRYBPPtWvA3hR5ZaAyHlGSVJiHoQPS8skbNaJ9h39VObnchUbgiY2pPu__s paypal.receiver.email=sb-ukxfk29608925@business.example.com paypal.mode=sandbox -paypal.webhook_id=31797347YC028794L +# local +#paypal.webhook_id=31797347YC028794L +# dev +paypal.webhook_id=51V87014T6406322F # aida-sandbox-kim #paypal.client-id=AbDDH8jnTrKqjnWLFgEu6LogYzVz2ZLuirE4W54t1M4lrofrP5OzXfhbxqktLLFB-rAO9KeYQVYFJ_tO From 5cd31215462fcccdcd2d421912d685a295c70a93 Mon Sep 17 00:00:00 2001 From: xupei Date: Thu, 28 Mar 2024 16:49:33 +0800 Subject: [PATCH 5/5] =?UTF-8?q?local=20->=20dev=20=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=90=8D=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/ai/da/common/RabbitMQ/MQConfig.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java index 78e6fc25..c5bd0821 100644 --- a/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java +++ b/src/main/java/com/ai/da/common/RabbitMQ/MQConfig.java @@ -10,14 +10,14 @@ public class MQConfig { public static final String GENERATE_EXCHANGE_FANOUT = "generate-exchange"; // public static final String GENERATE_QUEUE = "generate-queue-prod"; // public static final String GENERATE_QUEUE = "generate-queue-test"; -// public static final String GENERATE_QUEUE = "generate-queue-dev"; - public static final String GENERATE_QUEUE = "generate-queue-local"; + public static final String GENERATE_QUEUE = "generate-queue-dev"; +// public static final String GENERATE_QUEUE = "generate-queue-local"; -// public static final String SR_QUEUE = "SR-queue-dev"; - public static final String SR_QUEUE = "SR-queue-local"; + public static final String SR_QUEUE = "SR-queue-dev"; +// public static final String SR_QUEUE = "SR-queue-local"; - public static final String SR_RESULT_QUEUE = "SuperResolution-local"; -// public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; +// public static final String SR_RESULT_QUEUE = "SuperResolution-local"; + public static final String SR_RESULT_QUEUE = "SuperResolution-dev"; public MQConfig() { }