| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339 |
- package com.cyksj.service.recharge.impl;
- import cn.hutool.core.collection.CollUtil;
- import cn.hutool.core.date.DateTime;
- import cn.hutool.core.date.DateUtil;
- import cn.hutool.core.util.StrUtil;
- import cn.hutool.http.HttpRequest;
- import cn.hutool.http.HttpResponse;
- import cn.hutool.json.JSONObject;
- import cn.hutool.json.JSONUtil;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.cyksj.common.exception.BusinessRuntimeException;
- import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
- import com.cyksj.common.util.Jsons;
- import com.cyksj.mapper.*;
- import com.cyksj.model.entity.*;
- import com.cyksj.model.response.AfDianCardKeySearchResp;
- import com.cyksj.model.response.recharge.AfDianCardKeyResp;
- import com.cyksj.model.response.recharge.AfDianTaskStatusResp;
- import com.cyksj.redis.RedisService;
- import com.cyksj.server.recharge.dto.TaskResult;
- import com.cyksj.server.recharge.dto.TokenParseResult;
- import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
- import com.cyksj.service.recharge.AfDianRechargeService;
- import com.cyksj.service.recharge.GptRechargeCardKeyChannelService;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.stereotype.Service;
- import java.util.Date;
- import java.util.List;
- /**
- * 项目名: yhlxj11111111
- * 文件名: AfDianRechargeServiceImpl
- * 创建者: JavaZou
- * 创建时间:2026/1/26 18:16
- */
- @RequiredArgsConstructor
- @Service
- @Slf4j
- public class AfDianRechargeServiceImpl implements AfDianRechargeService {
- private final GptRechargeCardKeyChannelService gptRechargeCardKeyChannelService;
- private final GroupsRelationMapper relationMapper;
- private final GroupsMapper groupsMapper;
- private final GoodsDonSkuMapper skuMapper;
- private final RedisService redisService;
- private final OrderDonMapper orderDonMapper;
- private final GptRechargeCardKeyMapper gptRechargeCardKeyMapper;
- private final GptUserRechargeRecordService gptUserRechargeRecordService;
- private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
- @Override
- public AfDianCardKeyResp afDianValidateCardKey(String cardKey) throws Exception {
- String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
- String url = BASE_URL + "/cdks/public/check";
- JSONObject params = new JSONObject();
- params.putOpt("code", cardKey);
- HttpResponse response = HttpRequest.post(url)
- .body(params.toString())
- .execute();
- AfDianCardKeyResp afDianCardKeyResp = Jsons.parseObject(response.body(), AfDianCardKeyResp.class);
- return afDianCardKeyResp;
- }
- @Override
- public String confirmRecharge(GroupsRelation relation, String gptCardKey, CmsUser cmsUser) {
- Long relationId = relation.getId();
- //校验卡密是否可用
- AfDianCardKeyResp afDianCardKeyResp = null;
- try {
- afDianCardKeyResp = afDianValidateCardKey(gptCardKey);
- } catch (Exception e) {
- if (cmsUser == null) {
- throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
- }
- throw BusinessRuntimeException.getInstance("卡密:{0}错误", gptCardKey);
- }
- if (afDianCardKeyResp.getUsed()) {
- log.error("卡密:{}已被使用", gptCardKey);
- if (cmsUser == null) {
- throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
- }
- throw BusinessRuntimeException.getInstance("卡密:{0}已被使用", gptCardKey);
- }
- String accessToken = relation.getGptToken();
- String rechargeAccount = relation.getAccount();
- //提交任务
- String taskId = null;
- try {
- taskId = submitTask(gptCardKey, accessToken);
- } catch (Exception e) {
- setRechargeRelationStatusAutoError(relation);
- if (cmsUser == null) {
- throw BusinessRuntimeException.getInstance("充值失败,请联系客服开通");
- }
- throw BusinessRuntimeException.getInstance("充值失败,{0}", e.getMessage());
- }
- String operator = null;
- if (cmsUser != null) {
- operator = cmsUser.getNickname();
- }
- String password = relation.getPassword();
- relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
- //记录代充账号
- .set(GroupsRelation::getAccount, rechargeAccount)
- //记录操作人员
- .set(GroupsRelation::getOperator, operator)
- //密码
- .set(StrUtil.isNotBlank(password), GroupsRelation::getPassword, password)
- .set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharging)
- .set(GroupsRelation::getCardKey, gptCardKey)
- .set(GroupsRelation::getGptToken, accessToken)
- .set(GroupsRelation::getGptTaskId, taskId)
- .eq(GroupsRelation::getId, relationId));
- return taskId;
- }
- private String submitTask(String cardKey, String accessToken) {
- log.info("开始提交afdian任务 - 卡密: {}", cardKey);
- try {
- String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
- String url = BASE_URL + "/stocks/public/outstock";
- JSONObject requestBody = new JSONObject();
- requestBody.put("cdk", cardKey);
- requestBody.put("user", accessToken);
- HttpResponse response = HttpRequest.post(url)
- .setConnectionTimeout(60000)
- .body(requestBody.toString())
- .execute();
- String body = response.body();
- //虽然超时,但是任务已经提交
- if (body.contains("Gateway time-out")) {
- body = "Gateway time-out";
- }
- log.info("任务提交响应: {}", body);
- if (body.contains("Please try signing in again")) {
- throw BusinessRuntimeException.getInstance("token凭证已过期");
- }
- return body;
- } catch (Exception e) {
- log.error("提交任务失败: {}", e.getMessage(), e);
- throw new RuntimeException("提交任务失败: " + e.getMessage(), e);
- }
- }
- @Override
- public TaskResult getTaskResult(GroupsRelation relation) {
- try {
- String taskId = relation.getGptTaskId();
- String cardKey = relation.getCardKey();
- AfDianTaskStatusResp taskStatusResp;
- if (taskId.contains("Gateway time-out")) {
- taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
- } else {
- String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
- String url = BASE_URL + "/stocks/public/outstock/" + taskId;
- HttpResponse response = null;
- try {
- response = HttpRequest.get(url).setConnectionTimeout(10000).execute();
- String body = response.body();
- log.info("任务查询响应: {}", body);
- taskStatusResp = Jsons.parseObject(body, AfDianTaskStatusResp.class);
- //任务不存在
- if (StrUtil.isEmpty(taskStatusResp.getTask_id())) {
- return null;
- }
- } catch (Exception e) {
- //异常任务id
- //直接获取卡密的使用情况
- taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
- }
- }
- Boolean pending = taskStatusResp.getPending();
- Boolean status = taskStatusResp.getSuccess();
- //充值中
- TaskResult taskResult = new TaskResult();
- if (pending && status) {
- taskResult.setStatus("recharging");
- return taskResult;
- }
- String resultResult = taskStatusResp.getMessage();
- //更新代充状态
- resetGroupsRelationRechargeStatus(relation, pending, status, resultResult);
- if (status && !pending) {
- taskResult.setStatus("completed");
- } else taskResult.setStatus("failed");
- return taskResult;
- } catch (Exception e) {
- log.error("获取任务结果失败: {}", e.getMessage(), e);
- return null;
- }
- }
- /**
- * 设置代充自动充值异常
- */
- public void setRechargeRelationStatusAutoError(GroupsRelation relation) {
- TASK_EXECUTOR.execute(()->{
- relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
- .set(GroupsRelation::getAccount, relation.getAccount())
- .set(GroupsRelation::getGptToken, relation.getGptToken())
- .set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharge_error)
- .eq(GroupsRelation::getId, relation.getId()));
- });
- }
- public TokenParseResult parseToken(String accessToken) {
- log.info("开始验证凭证: {}", accessToken.substring(0, Math.min(20, accessToken.length())) + "...");
- try {
- String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(null);
- String url = BASE_URL + "/parse-token";
- JSONObject requestBody = new JSONObject();
- requestBody.put("access_token", accessToken);
- HttpResponse response = HttpRequest.post(url)
- .header("accept", "application/json, text/plain, */*")
- .header("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
- .header("content-type", "application/json")
- .header("origin", "https://www.ow520.com")
- .header("referer", "https://www.ow520.com/")
- .header("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36")
- .body(requestBody.toString())
- .execute();
- String body = response.body();
- log.info("凭证验证响应: {}", body);
- JSONObject jsonResponse = JSONUtil.parseObj(body);
- TokenParseResult result = new TokenParseResult(
- jsonResponse.getStr("message"),
- jsonResponse.getBool("success")
- );
- log.info("凭证验证结果: {}", result);
- return result;
- } catch (Exception e) {
- log.error("验证凭证失败: {}", e.getMessage(), e);
- throw new RuntimeException("验证凭证失败: " + e.getMessage(), e);
- }
- }
- /**
- * 更新代充状态
- */
- private void resetGroupsRelationRechargeStatus(GroupsRelation relation, Boolean pending, Boolean status, String result) {
- GroupsRelation.RechargeStatus rechargeStatus;
- if (status && !pending) {
- rechargeStatus = GroupsRelation.RechargeStatus.complete;
- } else {
- rechargeStatus = GroupsRelation.RechargeStatus.recharge_error;
- }
- String taskId = relation.getGptTaskId();
- if (relation != null && relation.getRechargeStatus() == GroupsRelation.RechargeStatus.recharging) {
- Integer rechargeRemainNum = relation.getRechargeRemainNum();
- String cardKey = relation.getCardKey();
- GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectOne(Wrappers.lambdaQuery(GptRechargeCardKey.class).eq(GptRechargeCardKey::getCardKey, cardKey).last("limit 1"));
- if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
- if (gptRechargeCardKey != null) {
- gptRechargeCardKeyMapper.update(null, Wrappers.lambdaUpdate(GptRechargeCardKey.class).set(GptRechargeCardKey::getStatus, Boolean.FALSE).set(GptRechargeCardKey::getOrderId, null).set(GptRechargeCardKey::getOrderNo, null).eq(GptRechargeCardKey::getId, gptRechargeCardKey.getId()).eq(GptRechargeCardKey::getStatus, Boolean.TRUE));
- }
- }
- if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
- if (!redisService.setNx(RedisService.key.GPT_RECHARGE_RECOVER_KEY.getName() + taskId, taskId, RedisService.key.GPT_RECHARGE_RECOVER_KEY.getTimeout())) {
- return;
- }
- }
- Date startTime = relation.getStartTime();
- DateTime expiryTime = null;
- if (rechargeStatus == GroupsRelation.RechargeStatus.complete && startTime == null) {
- GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
- if (groupsTrips != null) {
- startTime = DateTime.now();
- GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
- if (sku.getDays() != null && sku.getDays() > 0) {
- expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
- } else {
- expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
- }
- }
- }
- String rechargeErrorInfo = null;
- if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
- rechargeErrorInfo = result;
- }
- relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class).set(rechargeStatus == GroupsRelation.RechargeStatus.recharge_error, GroupsRelation::getRechargeRemainNum, rechargeRemainNum + 1).set(GroupsRelation::getRechargeStatus, rechargeStatus).set(expiryTime != null, GroupsRelation::getStartTime, startTime).set(expiryTime != null, GroupsRelation::getExpiryTime, expiryTime).set(StrUtil.isNotEmpty(rechargeErrorInfo), GroupsRelation::getRechargeErrorInfo, rechargeErrorInfo).eq(GroupsRelation::getId, relation.getId()).le(GroupsRelation::getRechargeRemainNum, relation.getRechargeNum()).eq(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharging));
- //记录代充记录
- if (rechargeStatus == GroupsRelation.RechargeStatus.complete) {
- String remark = "自动代充";
- if (StrUtil.isNotBlank(relation.getOperator())) {
- remark = "后台自动代充";
- }
- gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), -1, relation.getOperator(), remark);
- //修改对应订单状态
- if (gptRechargeCardKey != null) {
- Long orderId = gptRechargeCardKey.getOrderId();
- OrderDon orderDon = orderDonMapper.selectById(orderId);
- if (orderDon != null && orderDon.getStatus() == OrderDon.Status.hasPayment) {
- orderDon.setStatus(OrderDon.Status.complete);
- orderDonMapper.updateById(orderDon);
- }
- }
- }
- }
- }
- public AfDianTaskStatusResp getCardKeyUseStatus(String cardKey, String rechargeAccount) throws Exception {
- String searchStatusByCardKeyUrl = "https://cz.afdian.org/api/cdks/public/check-usage/" + cardKey;
- HttpResponse searchResp = HttpRequest.get(searchStatusByCardKeyUrl).setConnectionTimeout(10000).execute();
- List<AfDianCardKeySearchResp> afDianCardKeySearchResps = Jsons.parseList(searchResp.body(), AfDianCardKeySearchResp.class);
- if (CollUtil.isNotEmpty(afDianCardKeySearchResps)) {
- AfDianCardKeySearchResp afDianCardKeySearchResp = afDianCardKeySearchResps.get(0);
- AfDianTaskStatusResp taskStatusResp = new AfDianTaskStatusResp();
- if (afDianCardKeySearchResp.getUsed() && (afDianCardKeySearchResp.getUser() == null || afDianCardKeySearchResp.getUser().equals(rechargeAccount))) {
- taskStatusResp.setSuccess(true);
- taskStatusResp.setPending(false);
- } else {
- //失败
- taskStatusResp.setSuccess(false);
- taskStatusResp.setPending(false);
- }
- return taskStatusResp;
- }
- return null;
- }
- }
|