AfDianRechargeServiceImpl.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package com.cyksj.service.recharge.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateTime;
  4. import cn.hutool.core.date.DateUtil;
  5. import cn.hutool.core.util.StrUtil;
  6. import cn.hutool.http.HttpRequest;
  7. import cn.hutool.http.HttpResponse;
  8. import cn.hutool.json.JSONObject;
  9. import cn.hutool.json.JSONUtil;
  10. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  11. import com.cyksj.common.exception.BusinessRuntimeException;
  12. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  13. import com.cyksj.common.util.Jsons;
  14. import com.cyksj.mapper.*;
  15. import com.cyksj.model.entity.*;
  16. import com.cyksj.model.response.AfDianCardKeySearchResp;
  17. import com.cyksj.model.response.recharge.AfDianCardKeyResp;
  18. import com.cyksj.model.response.recharge.AfDianTaskStatusResp;
  19. import com.cyksj.redis.RedisService;
  20. import com.cyksj.server.recharge.dto.TaskResult;
  21. import com.cyksj.server.recharge.dto.TokenParseResult;
  22. import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
  23. import com.cyksj.service.recharge.AfDianRechargeService;
  24. import com.cyksj.service.recharge.GptRechargeCardKeyChannelService;
  25. import lombok.RequiredArgsConstructor;
  26. import lombok.extern.slf4j.Slf4j;
  27. import org.springframework.stereotype.Service;
  28. import java.util.Date;
  29. import java.util.List;
  30. /**
  31. * 项目名: yhlxj11111111
  32. * 文件名: AfDianRechargeServiceImpl
  33. * 创建者: JavaZou
  34. * 创建时间:2026/1/26 18:16
  35. */
  36. @RequiredArgsConstructor
  37. @Service
  38. @Slf4j
  39. public class AfDianRechargeServiceImpl implements AfDianRechargeService {
  40. private final GptRechargeCardKeyChannelService gptRechargeCardKeyChannelService;
  41. private final GroupsRelationMapper relationMapper;
  42. private final GroupsMapper groupsMapper;
  43. private final GoodsDonSkuMapper skuMapper;
  44. private final RedisService redisService;
  45. private final OrderDonMapper orderDonMapper;
  46. private final GptRechargeCardKeyMapper gptRechargeCardKeyMapper;
  47. private final GptUserRechargeRecordService gptUserRechargeRecordService;
  48. private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();
  49. @Override
  50. public AfDianCardKeyResp afDianValidateCardKey(String cardKey) throws Exception {
  51. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
  52. String url = BASE_URL + "/cdks/public/check";
  53. JSONObject params = new JSONObject();
  54. params.putOpt("code", cardKey);
  55. HttpResponse response = HttpRequest.post(url)
  56. .body(params.toString())
  57. .execute();
  58. AfDianCardKeyResp afDianCardKeyResp = Jsons.parseObject(response.body(), AfDianCardKeyResp.class);
  59. return afDianCardKeyResp;
  60. }
  61. @Override
  62. public String confirmRecharge(GroupsRelation relation, String gptCardKey, CmsUser cmsUser) {
  63. Long relationId = relation.getId();
  64. //校验卡密是否可用
  65. AfDianCardKeyResp afDianCardKeyResp = null;
  66. try {
  67. afDianCardKeyResp = afDianValidateCardKey(gptCardKey);
  68. } catch (Exception e) {
  69. if (cmsUser == null) {
  70. throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
  71. }
  72. throw BusinessRuntimeException.getInstance("卡密:{0}错误", gptCardKey);
  73. }
  74. if (afDianCardKeyResp.getUsed()) {
  75. log.error("卡密:{}已被使用", gptCardKey);
  76. if (cmsUser == null) {
  77. throw BusinessRuntimeException.getInstance("系统繁忙,请重试");
  78. }
  79. throw BusinessRuntimeException.getInstance("卡密:{0}已被使用", gptCardKey);
  80. }
  81. String accessToken = relation.getGptToken();
  82. String rechargeAccount = relation.getAccount();
  83. //提交任务
  84. String taskId = null;
  85. try {
  86. taskId = submitTask(gptCardKey, accessToken);
  87. } catch (Exception e) {
  88. setRechargeRelationStatusAutoError(relation);
  89. if (cmsUser == null) {
  90. throw BusinessRuntimeException.getInstance("充值失败,请联系客服开通");
  91. }
  92. throw BusinessRuntimeException.getInstance("充值失败,{0}", e.getMessage());
  93. }
  94. String operator = null;
  95. if (cmsUser != null) {
  96. operator = cmsUser.getNickname();
  97. }
  98. String password = relation.getPassword();
  99. relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  100. //记录代充账号
  101. .set(GroupsRelation::getAccount, rechargeAccount)
  102. //记录操作人员
  103. .set(GroupsRelation::getOperator, operator)
  104. //密码
  105. .set(StrUtil.isNotBlank(password), GroupsRelation::getPassword, password)
  106. .set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharging)
  107. .set(GroupsRelation::getCardKey, gptCardKey)
  108. .set(GroupsRelation::getGptToken, accessToken)
  109. .set(GroupsRelation::getGptTaskId, taskId)
  110. .eq(GroupsRelation::getId, relationId));
  111. return taskId;
  112. }
  113. private String submitTask(String cardKey, String accessToken) {
  114. log.info("开始提交afdian任务 - 卡密: {}", cardKey);
  115. try {
  116. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
  117. String url = BASE_URL + "/stocks/public/outstock";
  118. JSONObject requestBody = new JSONObject();
  119. requestBody.put("cdk", cardKey);
  120. requestBody.put("user", accessToken);
  121. HttpRequest post = HttpRequest.post(url);
  122. //模拟浏览器请求
  123. post.header("accept", "*/*");
  124. post.header("accept-language", "zh-CN,zh;q=0.9,sq;q=0.8,zh-TW;q=0.7");
  125. post.header("Content-Type", "text/plain;charset=UTF-8");
  126. post.header("Origin", "https://receipt.nitro.xin");
  127. post.header("Referer", "https://receipt.nitro.xin/");
  128. post.header("User-Agent", "Mozilla/5.0");
  129. post.header("x-device-id", "web");
  130. HttpResponse response = post
  131. .setConnectionTimeout(60000)
  132. .body(requestBody.toString())
  133. .execute();
  134. String body = response.body();
  135. //虽然超时,但是任务已经提交
  136. if (body.contains("Gateway time-out")) {
  137. body = "Gateway time-out";
  138. }
  139. log.info("任务提交响应: {}", body);
  140. if (body.contains("Please try signing in again")) {
  141. throw BusinessRuntimeException.getInstance("token凭证已过期");
  142. }
  143. return body;
  144. } catch (Exception e) {
  145. log.error("提交任务失败: {}", e.getMessage(), e);
  146. throw new RuntimeException("提交任务失败: " + e.getMessage(), e);
  147. }
  148. }
  149. @Override
  150. public TaskResult getTaskResult(GroupsRelation relation) {
  151. try {
  152. String taskId = relation.getGptTaskId();
  153. String cardKey = relation.getCardKey();
  154. AfDianTaskStatusResp taskStatusResp;
  155. if (taskId.contains("Gateway time-out")) {
  156. taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
  157. } else {
  158. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
  159. String url = BASE_URL + "/stocks/public/outstock/" + taskId;
  160. HttpResponse response = null;
  161. try {
  162. response = HttpRequest.get(url).setConnectionTimeout(10000).execute();
  163. String body = response.body();
  164. log.info("任务查询响应: {}", body);
  165. taskStatusResp = Jsons.parseObject(body, AfDianTaskStatusResp.class);
  166. //任务不存在
  167. if (StrUtil.isEmpty(taskStatusResp.getTask_id())) {
  168. return null;
  169. }
  170. //任务对应的cdk为空时
  171. if (StrUtil.isEmpty(taskStatusResp.getCdk())) {
  172. return null;
  173. }
  174. } catch (Exception e) {
  175. //异常任务id
  176. //直接获取卡密的使用情况
  177. taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
  178. }
  179. }
  180. Boolean pending = taskStatusResp.getPending();
  181. Boolean status = taskStatusResp.getSuccess();
  182. //充值中
  183. TaskResult taskResult = new TaskResult();
  184. if (pending && status) {
  185. taskResult.setStatus("recharging");
  186. return taskResult;
  187. }
  188. String resultResult = taskStatusResp.getMessage();
  189. //更新代充状态
  190. resetGroupsRelationRechargeStatus(relation, pending, status, resultResult);
  191. if (status && !pending) {
  192. taskResult.setStatus("completed");
  193. } else taskResult.setStatus("failed");
  194. return taskResult;
  195. } catch (Exception e) {
  196. log.error("获取任务结果失败: {}", e.getMessage(), e);
  197. return null;
  198. }
  199. }
  200. /**
  201. * 设置代充自动充值异常
  202. */
  203. public void setRechargeRelationStatusAutoError(GroupsRelation relation) {
  204. TASK_EXECUTOR.execute(()->{
  205. relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  206. .set(GroupsRelation::getAccount, relation.getAccount())
  207. .set(GroupsRelation::getGptToken, relation.getGptToken())
  208. .set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharge_error)
  209. .eq(GroupsRelation::getId, relation.getId()));
  210. });
  211. }
  212. public TokenParseResult parseToken(String accessToken) {
  213. log.info("开始验证凭证: {}", accessToken.substring(0, Math.min(20, accessToken.length())) + "...");
  214. try {
  215. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(null);
  216. String url = BASE_URL + "/parse-token";
  217. JSONObject requestBody = new JSONObject();
  218. requestBody.put("access_token", accessToken);
  219. HttpResponse response = HttpRequest.post(url)
  220. .header("accept", "application/json, text/plain, */*")
  221. .header("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
  222. .header("content-type", "application/json")
  223. .header("origin", "https://www.ow520.com")
  224. .header("referer", "https://www.ow520.com/")
  225. .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")
  226. .body(requestBody.toString())
  227. .execute();
  228. String body = response.body();
  229. log.info("凭证验证响应: {}", body);
  230. JSONObject jsonResponse = JSONUtil.parseObj(body);
  231. TokenParseResult result = new TokenParseResult(
  232. jsonResponse.getStr("message"),
  233. jsonResponse.getBool("success")
  234. );
  235. log.info("凭证验证结果: {}", result);
  236. return result;
  237. } catch (Exception e) {
  238. log.error("验证凭证失败: {}", e.getMessage(), e);
  239. throw new RuntimeException("验证凭证失败: " + e.getMessage(), e);
  240. }
  241. }
  242. /**
  243. * 更新代充状态
  244. */
  245. private void resetGroupsRelationRechargeStatus(GroupsRelation relation, Boolean pending, Boolean status, String result) {
  246. GroupsRelation.RechargeStatus rechargeStatus;
  247. if (status && !pending) {
  248. rechargeStatus = GroupsRelation.RechargeStatus.complete;
  249. } else {
  250. rechargeStatus = GroupsRelation.RechargeStatus.recharge_error;
  251. }
  252. String taskId = relation.getGptTaskId();
  253. if (relation != null && relation.getRechargeStatus() == GroupsRelation.RechargeStatus.recharging) {
  254. Integer rechargeRemainNum = relation.getRechargeRemainNum();
  255. String cardKey = relation.getCardKey();
  256. GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectOne(Wrappers.lambdaQuery(GptRechargeCardKey.class).eq(GptRechargeCardKey::getCardKey, cardKey).last("limit 1"));
  257. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  258. if (gptRechargeCardKey != null) {
  259. if ("stock not found.".equals(result)) {
  260. gptRechargeCardKeyMapper.update(null, Wrappers.lambdaUpdate(GptRechargeCardKey.class).set(GptRechargeCardKey::getOrderNo, "卡密异常").eq(GptRechargeCardKey::getId, gptRechargeCardKey.getId()).eq(GptRechargeCardKey::getStatus, Boolean.TRUE));
  261. } else {
  262. 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));
  263. }
  264. }
  265. }
  266. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  267. if (!redisService.setNx(RedisService.key.GPT_RECHARGE_RECOVER_KEY.getName() + taskId, taskId, RedisService.key.GPT_RECHARGE_RECOVER_KEY.getTimeout())) {
  268. return;
  269. }
  270. }
  271. Date startTime = relation.getStartTime();
  272. DateTime expiryTime = null;
  273. if (rechargeStatus == GroupsRelation.RechargeStatus.complete && startTime == null) {
  274. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  275. if (groupsTrips != null) {
  276. startTime = DateTime.now();
  277. GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
  278. if (sku.getDays() != null && sku.getDays() > 0) {
  279. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  280. } else {
  281. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  282. }
  283. }
  284. }
  285. String rechargeErrorInfo = null;
  286. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  287. rechargeErrorInfo = result;
  288. }
  289. 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));
  290. //记录代充记录
  291. if (rechargeStatus == GroupsRelation.RechargeStatus.complete) {
  292. String remark = "自动代充";
  293. if (StrUtil.isNotBlank(relation.getOperator())) {
  294. remark = "后台自动代充";
  295. }
  296. gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getCardKey(), relation.getUserId(), relation.getId(), relation.getAccount(), -1, relation.getOperator(), remark);
  297. //修改对应订单状态
  298. if (gptRechargeCardKey != null) {
  299. Long orderId = gptRechargeCardKey.getOrderId();
  300. OrderDon orderDon = orderDonMapper.selectById(orderId);
  301. if (orderDon != null && orderDon.getStatus() == OrderDon.Status.hasPayment) {
  302. orderDon.setStatus(OrderDon.Status.complete);
  303. orderDonMapper.updateById(orderDon);
  304. }
  305. }
  306. }
  307. }
  308. }
  309. public AfDianTaskStatusResp getCardKeyUseStatus(String cardKey, String rechargeAccount) throws Exception {
  310. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
  311. String searchStatusByCardKeyUrl = BASE_URL + "/cdks/public/check-usage/" + cardKey;
  312. HttpResponse searchResp = HttpRequest.get(searchStatusByCardKeyUrl).setConnectionTimeout(10000).execute();
  313. List<AfDianCardKeySearchResp> afDianCardKeySearchResps = Jsons.parseList(searchResp.body(), AfDianCardKeySearchResp.class);
  314. if (CollUtil.isNotEmpty(afDianCardKeySearchResps)) {
  315. AfDianCardKeySearchResp afDianCardKeySearchResp = afDianCardKeySearchResps.get(0);
  316. AfDianTaskStatusResp taskStatusResp = new AfDianTaskStatusResp();
  317. if (afDianCardKeySearchResp.getUsed() && (afDianCardKeySearchResp.getUser() == null || afDianCardKeySearchResp.getUser().equals(rechargeAccount))) {
  318. taskStatusResp.setSuccess(true);
  319. taskStatusResp.setPending(false);
  320. } else {
  321. //失败
  322. taskStatusResp.setSuccess(false);
  323. taskStatusResp.setPending(false);
  324. }
  325. return taskStatusResp;
  326. }
  327. return null;
  328. }
  329. }