KuaishouMediaClient.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.nuojing.media.auth.client;
  2. import com.fasterxml.jackson.databind.JsonNode;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.nuojing.admin.common.BusinessException;
  5. import com.nuojing.media.auth.domain.entity.MediaAuthConfig;
  6. import lombok.RequiredArgsConstructor;
  7. import org.springframework.http.HttpEntity;
  8. import org.springframework.http.HttpHeaders;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.stereotype.Component;
  11. import org.springframework.util.StringUtils;
  12. import org.springframework.web.client.RestTemplate;
  13. import java.util.HashMap;
  14. import java.util.Map;
  15. @Component
  16. @RequiredArgsConstructor
  17. public class KuaishouMediaClient {
  18. private static final String TOKEN_URL = "https://open.e.kuaishou.com/rest/openapi/oauth2/authorize/access_token";
  19. private final ObjectMapper objectMapper;
  20. private final RestTemplate restTemplate = new RestTemplate();
  21. public JsonNode exchangeToken(MediaAuthConfig config, String authCode) {
  22. Map<String, Object> body = new HashMap<>();
  23. body.put("app_id", config.getAppId());
  24. body.put("app_secret", config.getAppSecret());
  25. body.put("auth_code", authCode);
  26. return postJson(TOKEN_URL, body);
  27. }
  28. public JsonNode requireSuccess(JsonNode response, String action) {
  29. if (response == null || response.isMissingNode() || response.isNull()) {
  30. throw new BusinessException(500, action + "返回信息为空");
  31. }
  32. int code = response.path("code").asInt(-1);
  33. if (code != 0) {
  34. String message = response.path("message").asText(action + "失败");
  35. throw new BusinessException(500, message);
  36. }
  37. JsonNode data = response.path("data");
  38. if (data.isMissingNode() || data.isNull()) {
  39. throw new BusinessException(500, action + "data信息为空");
  40. }
  41. return data;
  42. }
  43. private JsonNode postJson(String url, Map<String, Object> body) {
  44. HttpHeaders headers = new HttpHeaders();
  45. headers.setContentType(MediaType.APPLICATION_JSON);
  46. return parse(restTemplate.postForObject(url, new HttpEntity<>(body, headers), String.class));
  47. }
  48. private JsonNode parse(String response) {
  49. if (!StringUtils.hasText(response)) {
  50. return objectMapper.missingNode();
  51. }
  52. try {
  53. return objectMapper.readTree(response);
  54. } catch (Exception ex) {
  55. throw new BusinessException(500, "媒体响应解析失败");
  56. }
  57. }
  58. }