쿠팡 api spring boot java
스프링 부트 프로젝트를 생성하고 그 프로젝트에서 쿠팡 api를 사용해 만들 응용프로그램이 있어서 쿠팡 api 연동 테스트를 해봤다.
1. coupang_api 폴더(패키지)를 만들고 안에 쿠팡 api문서에서 제공하는 테스트 코드를 그대로 java파일로 만들어 준다.
HmacGenerator.java
package com.coupang_api.Coupang_api;
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class HmacGenerator {
private static final String ALGORITHM = "HmacSHA256";
// private static final Charset STANDARD_CHARSET = Charset.forName("UTF-8");
private static final Charset STANDARD_CHARSET = StandardCharsets.UTF_8;
/**
* Generate HMAC signature
* @param method
* @param uri http request uri
* @param secretKey secret key that Coupang partner granted for calling open api
* @param accessKey access key that Coupang partner granted for calling open api
* @return HMAC signature
*/
public static String generate(String method, String uri, String secretKey, String accessKey) {
String[] parts = uri.split("\\?");
if (parts.length > 2) {
throw new RuntimeException("incorrect uri format");
} else {
String path = parts[0];
String query = "";
if (parts.length == 2) {
query = parts[1];
}
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyMMdd'T'HHmmss'Z'");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String datetime = dateFormatGmt.format(new Date());
String message = datetime + method + path + query;
String signature;
try {
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(STANDARD_CHARSET), ALGORITHM);
Mac mac = Mac.getInstance(ALGORITHM);
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes(STANDARD_CHARSET));
signature = Hex.encodeHexString(rawHmac);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException("Unexpected error while creating hash: " + e.getMessage(), e);
}
return String.format("CEA algorithm=%s, access-key=%s, signed-date=%s, signature=%s", "HmacSHA256", accessKey, datetime, signature);
}
}
}
OpenApiTestApplication.java
package com.coupang_api.Coupang_api;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
public class OpenApiTestApplication { private final static String REQUEST_METHOD = "POST";
private final static String DOMAIN = "https://api-gateway.coupang.com";
private final static String URL = "/v2/providers/affiliate_open_api/apis/openapi/deeplink";
// Replace with your own ACCESS_KEY and SECRET_KEY
private final static String ACCESS_KEY = "YOUR_ACCESS_KEY";
private final static String SECRET_KEY = "YOUR_SECRET_KEY";
private final static String REQUEST_JSON = "{\"coupangUrls\": [\"https://www.coupang.com/np/search?component=&q=good&channel=user\",\"https://www.coupang.com/np/coupangglobal\"]}";
public static void main(String[] args) throws IOException {
// Generate HMAC string
String authorization = HmacGenerator.generate(REQUEST_METHOD, URL, SECRET_KEY, ACCESS_KEY);
// Send request
StringEntity entity = new StringEntity(REQUEST_JSON, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
org.apache.http.HttpHost host = org.apache.http.HttpHost.create(DOMAIN);
org.apache.http.HttpRequest request = org.apache.http.client.methods.RequestBuilder
.post(URL).setEntity(entity)
.addHeader("Authorization", authorization)
.build();
org.apache.http.HttpResponse httpResponse = org.apache.http.impl.client.HttpClientBuilder.create().build().execute(host, request);
// verify
System.out.println(EntityUtils.toString(httpResponse.getEntity()));
}
}
두 java 파일 모두 테스트 코드 그대로이다.
2. gradle 의존성 추가
(maven을 사용하는 사람은 구글링으로 찾아보시고)
gradle에 apache commons-codec 라이브러리와 httpclient 라이브러리를 추가해줘야 한다.
build.gradle 의존성 추가해준다.
implementation 'commons-codec:commons-codec:1.14'
implementation 'org.apache.httpcomponents:httpclient:4.5.11'
3. OpenApiTestApplication 클래스 메인 메소드 실행.
클래스 옆 실행 버튼으로 실행해준다.
EntityUtils.toString(httpResponse.getEntity()) 값이 json으로 잘 도착하면, 잘 실행이 된것이다.
결과 값 :
{"rCode":"0","rMessage":"","data":[{"originalUrl":"https://www.coupang.com/np/search?component=&q=good&channel=user","shortenUrl":"https://coupa.ng/bnSB0O","landingUrl":"https://link.coupang.com/re/AFFSRP?lptag=AF5139617&pageKey=good&traceid=V0-183-c890f6fb18804fe8"},{"originalUrl":"https://www.coupang.com/np/coupangglobal","shortenUrl":"https://coupa.ng/bnSB0P","landingUrl":"https://link.coupang.com/re/AFFJIKGU?lptag=AF5139617&traceid=V0-183-50c6c2b97fba9aee"}]}
결과값이 잘안나온다면 쿠팡 api에 에러 코드에 대한 설명이 있으니 참고 해보는게 좋겠다.