AfDianRechargeServiceImpl.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. HttpResponse response = HttpRequest.post(url)
  122. .setConnectionTimeout(60000)
  123. .body(requestBody.toString())
  124. .execute();
  125. String body = response.body();
  126. //虽然超时,但是任务已经提交
  127. if (body.contains("Gateway time-out")) {
  128. body = "Gateway time-out";
  129. }
  130. log.info("任务提交响应: {}", body);
  131. if (body.contains("Please try signing in again")) {
  132. throw BusinessRuntimeException.getInstance("token凭证已过期");
  133. }
  134. return body;
  135. } catch (Exception e) {
  136. log.error("提交任务失败: {}", e.getMessage(), e);
  137. throw new RuntimeException("提交任务失败: " + e.getMessage(), e);
  138. }
  139. }
  140. @Override
  141. public TaskResult getTaskResult(GroupsRelation relation) {
  142. try {
  143. String taskId = relation.getGptTaskId();
  144. String cardKey = relation.getCardKey();
  145. AfDianTaskStatusResp taskStatusResp;
  146. if (taskId.contains("Gateway time-out")) {
  147. taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
  148. } else {
  149. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(cardKey);
  150. String url = BASE_URL + "/stocks/public/outstock/" + taskId;
  151. HttpResponse response = null;
  152. try {
  153. response = HttpRequest.get(url).setConnectionTimeout(10000).execute();
  154. String body = response.body();
  155. log.info("任务查询响应: {}", body);
  156. taskStatusResp = Jsons.parseObject(body, AfDianTaskStatusResp.class);
  157. //任务不存在
  158. if (StrUtil.isEmpty(taskStatusResp.getTask_id())) {
  159. return null;
  160. }
  161. } catch (Exception e) {
  162. //异常任务id
  163. //直接获取卡密的使用情况
  164. taskStatusResp = getCardKeyUseStatus(cardKey, relation.getAccount());
  165. }
  166. }
  167. Boolean pending = taskStatusResp.getPending();
  168. Boolean status = taskStatusResp.getSuccess();
  169. //充值中
  170. TaskResult taskResult = new TaskResult();
  171. if (pending && status) {
  172. taskResult.setStatus("recharging");
  173. return taskResult;
  174. }
  175. String resultResult = taskStatusResp.getMessage();
  176. //更新代充状态
  177. resetGroupsRelationRechargeStatus(relation, pending, status, resultResult);
  178. if (status && !pending) {
  179. taskResult.setStatus("completed");
  180. } else taskResult.setStatus("failed");
  181. return taskResult;
  182. } catch (Exception e) {
  183. log.error("获取任务结果失败: {}", e.getMessage(), e);
  184. return null;
  185. }
  186. }
  187. /**
  188. * 设置代充自动充值异常
  189. */
  190. public void setRechargeRelationStatusAutoError(GroupsRelation relation) {
  191. TASK_EXECUTOR.execute(()->{
  192. relationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  193. .set(GroupsRelation::getAccount, relation.getAccount())
  194. .set(GroupsRelation::getGptToken, relation.getGptToken())
  195. .set(GroupsRelation::getRechargeStatus, GroupsRelation.RechargeStatus.recharge_error)
  196. .eq(GroupsRelation::getId, relation.getId()));
  197. });
  198. }
  199. public TokenParseResult parseToken(String accessToken) {
  200. log.info("开始验证凭证: {}", accessToken.substring(0, Math.min(20, accessToken.length())) + "...");
  201. try {
  202. String BASE_URL = gptRechargeCardKeyChannelService.getCardKeyDomain(null);
  203. String url = BASE_URL + "/parse-token";
  204. JSONObject requestBody = new JSONObject();
  205. requestBody.put("access_token", accessToken);
  206. HttpResponse response = HttpRequest.post(url)
  207. .header("accept", "application/json, text/plain, */*")
  208. .header("accept-language", "zh-CN,zh;q=0.9,en;q=0.8")
  209. .header("content-type", "application/json")
  210. .header("origin", "https://www.ow520.com")
  211. .header("referer", "https://www.ow520.com/")
  212. .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")
  213. .body(requestBody.toString())
  214. .execute();
  215. String body = response.body();
  216. log.info("凭证验证响应: {}", body);
  217. JSONObject jsonResponse = JSONUtil.parseObj(body);
  218. TokenParseResult result = new TokenParseResult(
  219. jsonResponse.getStr("message"),
  220. jsonResponse.getBool("success")
  221. );
  222. log.info("凭证验证结果: {}", result);
  223. return result;
  224. } catch (Exception e) {
  225. log.error("验证凭证失败: {}", e.getMessage(), e);
  226. throw new RuntimeException("验证凭证失败: " + e.getMessage(), e);
  227. }
  228. }
  229. /**
  230. * 更新代充状态
  231. */
  232. private void resetGroupsRelationRechargeStatus(GroupsRelation relation, Boolean pending, Boolean status, String result) {
  233. GroupsRelation.RechargeStatus rechargeStatus;
  234. if (status && !pending) {
  235. rechargeStatus = GroupsRelation.RechargeStatus.complete;
  236. } else {
  237. rechargeStatus = GroupsRelation.RechargeStatus.recharge_error;
  238. }
  239. String taskId = relation.getGptTaskId();
  240. if (relation != null && relation.getRechargeStatus() == GroupsRelation.RechargeStatus.recharging) {
  241. Integer rechargeRemainNum = relation.getRechargeRemainNum();
  242. String cardKey = relation.getCardKey();
  243. GptRechargeCardKey gptRechargeCardKey = gptRechargeCardKeyMapper.selectOne(Wrappers.lambdaQuery(GptRechargeCardKey.class).eq(GptRechargeCardKey::getCardKey, cardKey).last("limit 1"));
  244. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  245. if (gptRechargeCardKey != null) {
  246. 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));
  247. }
  248. }
  249. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  250. if (!redisService.setNx(RedisService.key.GPT_RECHARGE_RECOVER_KEY.getName() + taskId, taskId, RedisService.key.GPT_RECHARGE_RECOVER_KEY.getTimeout())) {
  251. return;
  252. }
  253. }
  254. Date startTime = relation.getStartTime();
  255. DateTime expiryTime = null;
  256. if (rechargeStatus == GroupsRelation.RechargeStatus.complete && startTime == null) {
  257. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  258. if (groupsTrips != null) {
  259. startTime = DateTime.now();
  260. GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
  261. if (sku.getDays() != null && sku.getDays() > 0) {
  262. expiryTime = DateUtil.offsetDay(startTime, sku.getDays());
  263. } else {
  264. expiryTime = DateUtil.offsetMonth(startTime, sku.getMonths());
  265. }
  266. }
  267. }
  268. String rechargeErrorInfo = null;
  269. if (rechargeStatus == GroupsRelation.RechargeStatus.recharge_error) {
  270. rechargeErrorInfo = result;
  271. }
  272. 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));
  273. //记录代充记录
  274. if (rechargeStatus == GroupsRelation.RechargeStatus.complete) {
  275. String remark = "自动代充";
  276. if (StrUtil.isNotBlank(relation.getOperator())) {
  277. remark = "后台自动代充";
  278. }
  279. gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), -1, relation.getOperator(), remark);
  280. //修改对应订单状态
  281. if (gptRechargeCardKey != null) {
  282. Long orderId = gptRechargeCardKey.getOrderId();
  283. OrderDon orderDon = orderDonMapper.selectById(orderId);
  284. if (orderDon != null && orderDon.getStatus() == OrderDon.Status.hasPayment) {
  285. orderDon.setStatus(OrderDon.Status.complete);
  286. orderDonMapper.updateById(orderDon);
  287. }
  288. }
  289. }
  290. }
  291. }
  292. public AfDianTaskStatusResp getCardKeyUseStatus(String cardKey, String rechargeAccount) throws Exception {
  293. String searchStatusByCardKeyUrl = "https://cz.afdian.org/api/cdks/public/check-usage/" + cardKey;
  294. HttpResponse searchResp = HttpRequest.get(searchStatusByCardKeyUrl).setConnectionTimeout(10000).execute();
  295. List<AfDianCardKeySearchResp> afDianCardKeySearchResps = Jsons.parseList(searchResp.body(), AfDianCardKeySearchResp.class);
  296. if (CollUtil.isNotEmpty(afDianCardKeySearchResps)) {
  297. AfDianCardKeySearchResp afDianCardKeySearchResp = afDianCardKeySearchResps.get(0);
  298. AfDianTaskStatusResp taskStatusResp = new AfDianTaskStatusResp();
  299. if (afDianCardKeySearchResp.getUsed() && (afDianCardKeySearchResp.getUser() == null || afDianCardKeySearchResp.getUser().equals(rechargeAccount))) {
  300. taskStatusResp.setSuccess(true);
  301. taskStatusResp.setPending(false);
  302. } else {
  303. //失败
  304. taskStatusResp.setSuccess(false);
  305. taskStatusResp.setPending(false);
  306. }
  307. return taskStatusResp;
  308. }
  309. return null;
  310. }
  311. }