1.
아래의 링크를 들어 가기.
NAVER CLOUD PLATFORM
cloud computing services for corporations, IaaS, PaaS, SaaS, with Global region and Security Technology Certification
www.ncloud.com
2.
우측 상단의 콘솔 버튼을 클릭 하기.
3.
로그인 진행 하기.
없으면 회원가입 후 진행 하기.
4.
로그인을 하고 나면, 새로운 창이 열리고, 좌측 Dashboard 를 확인 하기.
5.
Services 를 클릭 하고, 검색창에 SENS 를 검색 하기.
Simple & Easy Notification Service (SENS) 클릭 하기.
6.
프로젝트 생성하기 클릭 하기.
서비스 Type : SMS
이름 : 원하는 프로젝트 이름 기입 하기.
설명 : 원하는 설명 기입 하기.
하고, 생성하기를 클릭 하기.
저는 이름과 설명에 test 라고 적고, 생성 하기를 눌러보겠습니다.
7.
그러면 아래와 같이 새로운 프로젝트가 생성 된다.
8.
서비스의 SMS 버튼을 클릭 하기.
새로운 창이 뜨고, 발송 하기 버튼을 클릭 하기.
아래와 같이 새로운 창이 뜨고, 발신 번호 등록 바로가기 버튼을 클릭 하기.
9.
발신번호 등록 버튼을 클릭 하기.
아래로 스크롤을 내려서, 핸드폰 인증을 진행 하기. 본인인증 (SMS) 클릭.
10.
본인인증 완료 후, 아래와 같이 처리상태에 등록 완료가 뜨면 성공.
11.
좌측 Dashboard 에 SENS 목록에서, Project를 클릭 하기.
방금 생성한 프로젝트의 서비스 ID 클릭 하기.
복사 버튼을 눌러서 SMS ID API Key 를 복사 하기.
알아 볼 수 있도록 복사해서 저장해두면 된다.
12.
우측 상단에 이름을 클릭하고, 포털 바로가기를 클릭 하기.
마이페이지를 클릭 하기.
인증키 관리를 클릭 하기.
비밀번호를 입력 하고 새로운 페이지로 들어 오기.
13.
신규 API 인증키 생성 클릭 하기.
그러면, 새로운 Access Key ID와 Secret Key 가 생성 된다.
각각, 알아 볼 수 있도록 복사하기.
14.
SMS 전송을 위한 헤더 구성 하기.
SMS API 요청을 하기 위해서는 NAVER 에서 지정해놓은 포맷에 따라 헤더를 구현 해야 한다.
아래의 링크에서 정확히 확인 할 수 있다.
https://api.ncloud-docs.com/docs/common-ncpapi
Ncloud API
api.ncloud-docs.com
각 헤더의 의미는 다음과 같다.
1. 현재 시간.
JAVA 에서는 System.currentTime.Millis() 메서드로 간단히 구현 가능 하다.
2. 발급받은 AccessKey 값.
3. 발급받은 SecretKey 값.
시그니처 생성을 해주면 된다.
makeSignature() 메서드를 거의 그대로 사용 하면 된다.
public String makeSignature() {
String space = " "; // one space
String newLine = "\n"; // new line
String method = "GET"; // method
String url = "/photos/puppy.jpg?query1=&query2"; // url (include query string)
String timestamp = "{timestamp}"; // current timestamp (epoch)
String accessKey = "{accessKey}"; // access key id (from portal or Sub Account)
String secretKey = "{secretKey}";
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
return encodeBase64String;
}
15.
헤더 구성이 끝나면, 메세지 요청을 위한 요청 및 응답 에 관한 설정을 해야 한다.
아래의 링크를 참고 하면 된다.
SMS API
api.ncloud-docs.com
요청 Body
{
"type":"(SMS | LMS | MMS)",
"contentType":"(COMM | AD)",
"countryCode":"string",
"from":"string",
"subject":"string",
"content":"string",
"messages":[
{
"to":"string",
"subject":"string",
"content":"string"
}
],
"files":[
{
"fileId": "string"
}
],
"reserveTime": "yyyy-MM-dd HH:mm",
"reserveTimeZone": "string"
}
메세지 요청에 필요한 요청 값이 위의 이미지를 보면 많아 보이지만,
실제로는 필수 값이 아닌 요청 값도 많다.
SMS 전송을 하기 위해서, 해당 API 를 사용하려고 하니까,
LMS, MMS 등에 필요한 요청 관련 코드는 모두 제외 하면 된다.
응답 Body
{
"requestId":"string",
"requestTime":"string",
"statusCode":"string",
"statusName":"string"
}
16. 실제 코드 작성 하기.
Spring 프레임워크를 사용해서, M-V-C 패턴으로 프로젝트 구현.
예시 코드 01
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Naver_Sens_V2 {
@SuppressWarnings("unchecked")
public void send_msg(String tel, String rand) {
// 호스트 URL
String hostNameUrl = "https://sens.apigw.ntruss.com";
// 요청 URL
String requestUrl= "/sms/v2/services/";
// 요청 URL Type
String requestUrlType = "/messages";
// 개인 인증키
String accessKey = "";
// 2차 인증을 위해 서비스마다 할당되는 service secret
String secretKey = "";
// 프로젝트에 할당된 SMS 서비스 ID
String serviceId = "";
// 요청 method
String method = "POST";
// current timestamp (epoch)
String timestamp = Long.toString(System.currentTimeMillis());
requestUrl += serviceId + requestUrlType;
String apiUrl = hostNameUrl + requestUrl;
// JSON 을 활용한 body data 생성
JSONObject bodyJson = new JSONObject();
JSONObject toJson = new JSONObject();
JSONArray toArr = new JSONArray();
// 난수와 함께 전송
toJson.put("content","Going 본인인증 ["+rand+"]");
toJson.put("to",tel);
toArr.add(toJson);
// 메시지 Type (sms | lms)
bodyJson.put("type","sms");
bodyJson.put("contentType","COMM");
bodyJson.put("countryCode","82");
// 발신번호 * 사전에 인증/등록된 번호만 사용할 수 있습니다.
bodyJson.put("from","");
bodyJson.put("messages", toArr);
String body = bodyJson.toJSONString();
System.out.println(body);
try {
URL url = new URL(apiUrl);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("content-type", "application/json");
con.setRequestProperty("x-ncp-apigw-timestamp", timestamp);
con.setRequestProperty("x-ncp-iam-access-key", accessKey);
con.setRequestProperty("x-ncp-apigw-signature-v2", makeSignature(requestUrl, timestamp, method, accessKey, secretKey));
con.setRequestMethod(method);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(body.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader br;
System.out.println("responseCode" +" " + responseCode);
if(responseCode==202) { // 정상 호출
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else { // 에러 발생
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e);
}
}
public static String makeSignature(
String url,
String timestamp,
String method,
String accessKey,
String secretKey
) throws NoSuchAlgorithmException, InvalidKeyException {
String space = " ";
String newLine = "\n";
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey;
String encodeBase64String;
try {
signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
} catch (UnsupportedEncodingException e) {
encodeBase64String = e.toString();
}
return encodeBase64String;
}
}
public String sendRandomMessage(String tel) {
Naver_Sens_V2 message = new Naver_Sens_V2();
Random rand = new Random();
String numStr = "";
for (int i = 0; i < 6; i++) {
String ran = Integer.toString(rand.nextInt(10));
numStr += ran;
}
System.out.println("회원가입 문자 인증 => " + numStr);
message.send_msg(tel, numStr);
return numStr;
}
@PostMapping("phoneAuth")
@ResponseBody
public Boolean phoneAuth(String tel) {
try { // 이미 가입된 전화번호가 있으면
if(memberService.memberTelCount(tel) > 0)
return true;
} catch (Exception e) {
e.printStackTrace();
}
String code = memberService.sendRandomMessage(tel);
session.setAttribute("rand", code);
return false;
}
@PostMapping("phoneAuthOk")
@ResponseBody
public Boolean phoneAuthOk() {
String rand = (String) session.getAttribute("rand");
String code = (String) request.getParameter("code");
System.out.println(rand + " : " + code);
if (rand.equals(code)) {
session.removeAttribute("rand");
return false;
}
return true;
}
예시 링크 :
예시 코드 02
import org.json.*;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import okhttp3.*;
public class smsMessage{
private static String projectId = "서비스 아이디";
private static String accessKey = "Access Key ID";
private static String secretKey = "Secret Key";
private static String url = "/sms/v2/services/"+projectId+"/messages";
private static String requestUrl = "https://sens.apigw.ntruss.com"+url;
private static String timestamp = Long.toString(System.currentTimeMillis());
private static String method = "POST";
public static void main(String[] args) throws Exception {
JSONObject bodytJson = new JSONObject();
JSONObject toJson = new JSONObject();
JSONArray toArr = new JSONArray();
toJson.put("subject" , "제목");
toJson.put("content" , "내용");
toJson.put("to" , "등록된 발신번호");
toArr.put(toJson);
bodytJson.put("type" , "SMS");
bodytJson.put("contentType" , "COMM");
bodytJson.put("countryCode" , "82");
bodytJson.put("from" , "01012345678");
bodytJson.put("subject" , "제목");
bodytJson.put("content" , "내용");
bodytJson.put("messages" , toArr );
String body = bodytJson.toString();
String result2 = doPost(requestUrl , body);
System.out.println(result2);
}
// OkHttp 통신
public static String doPost(String requestURL , String jsonMessage) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("x-ncp-apigw-timestamp", timestamp )
.addHeader("x-ncp-iam-access-key", accessKey )
.addHeader("x-ncp-apigw-signature-v2", makeSignature() )
.url(requestURL)
.post(RequestBody.create(MediaType.parse("application/json"), jsonMessage))
.build();
Response response = client.newCall(request).execute();
//출력
String message = response.body().string();
return message;
};
// Signature생성
public static String makeSignature() throws Exception {
String space = " "; // one space
String newLine = "\n"; // new line
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(accessKey)
.toString();
String encodeBase64String = null;
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
return encodeBase64String;
};
}
예시 링크 :
https://chung10.tistory.com/129
예시 코드 03
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
// https://api.ncloud-docs.com/docs/common-ncpapi
private String makeSignature(String url, String timestamp, String method, String accessKey, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
String space = " "; // one space
String newLine = "\n"; // new line
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timestamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey;
String encodeBase64String;
try {
signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
encodeBase64String = Base64.getEncoder().encodeToString(rawHmac);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
encodeBase64String = e.toString();
}
return encodeBase64String;
}
/*
* https://api.ncloud-docs.com/docs/ko/ai-application-service-sens-smsv2
{
"type":"(SMS | LMS | MMS)",
"contentType":"(COMM | AD)",
"countryCode":"string",
"from":"string",
"subject":"string",
"content":"string",
"messages":[
{
"to":"string",
"subject":"string",
"content":"string"
}
],
"files":[
{
"name":"string",
"body":"string"
}
],
"reserveTime": "yyyy-MM-dd HH:mm",
"reserveTimeZone": "string",
"scheduleCode": "string"
}
*/
private void sendSMS() {
String hostNameUrl = "https://sens.apigw.ntruss.com"; // 호스트 URL
String requestUrl= "/sms/v2/services/"; // 요청 URL
String requestUrlType = "/messages"; // 요청 URL
String accessKey = "QWALu3XgiCxABC2aynAf"; // 네이버 클라우드 플랫폼 회원에게 발급되는 개인 인증키 // Access Key : https://www.ncloud.com/mypage/manage/info > 인증키 관리 > Access Key ID
String secretKey = "bXGAcyQw1FG9Zjq6f1U8SD5CHMFVsvumivXoP194"; // 2차 인증을 위해 서비스마다 할당되는 service secret key // Service Key : https://www.ncloud.com/mypage/manage/info > 인증키 관리 > Access Key ID
String serviceId = "ncp:sms:kr:178053617394:projectname"; // 프로젝트에 할당된 SMS 서비스 ID // service ID : https://console.ncloud.com/sens/project > Simple & ... > Project > 서비스 ID
String method = "POST"; // 요청 method
String timestamp = Long.toString(System.currentTimeMillis()); // current timestamp (epoch)
requestUrl += serviceId + requestUrlType;
String apiUrl = hostNameUrl + requestUrl;
// JSON 을 활용한 body data 생성
JSONObject bodyJson = new JSONObject();
JSONObject toJson = new JSONObject();
JSONArray toArr = new JSONArray();
//toJson.put("subject",""); // Optional, messages.subject 개별 메시지 제목, LMS, MMS에서만 사용 가능
//toJson.put("content","sms test in spring 111"); // Optional, messages.content 개별 메시지 내용, SMS: 최대 80byte, LMS, MMS: 최대 2000byte
toJson.put("to","01012345678"); // Mandatory(필수), messages.to 수신번호, -를 제외한 숫자만 입력 가능
toArr.put(toJson);
bodyJson.put("type","SMS"); // Madantory, 메시지 Type (SMS | LMS | MMS), (소문자 가능)
//bodyJson.put("contentType",""); // Optional, 메시지 내용 Type (AD | COMM) * AD: 광고용, COMM: 일반용 (default: COMM) * 광고용 메시지 발송 시 불법 스팸 방지를 위한 정보통신망법 (제 50조)가 적용됩니다.
//bodyJson.put("countryCode","82"); // Optional, 국가 전화번호, (default: 82)
bodyJson.put("from","01012345678"); // Mandatory, 발신번호, 사전 등록된 발신번호만 사용 가능
//bodyJson.put("subject",""); // Optional, 기본 메시지 제목, LMS, MMS에서만 사용 가능
bodyJson.put("content","sms test in spring 222"); // Mandatory(필수), 기본 메시지 내용, SMS: 최대 80byte, LMS, MMS: 최대 2000byte
bodyJson.put("messages", toArr); // Mandatory(필수), 아래 항목들 참조 (messages.XXX), 최대 1,000개
//String body = bodyJson.toJSONString();
String body = bodyJson.toString();
System.out.println(body);
try {
URL url = new URL(apiUrl);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("content-type", "application/json");
con.setRequestProperty("x-ncp-apigw-timestamp", timestamp);
con.setRequestProperty("x-ncp-iam-access-key", accessKey);
con.setRequestProperty("x-ncp-apigw-signature-v2", makeSignature(requestUrl, timestamp, method, accessKey, secretKey));
con.setRequestMethod(method);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(body.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
BufferedReader br;
System.out.println("responseCode" +" " + responseCode);
if(responseCode == 202) { // 정상 호출
br = new BufferedReader(new InputStreamReader(con.getInputStream()));
} else { // 에러 발생
br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
}
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
System.out.println(response.toString());
} catch (Exception e) {
System.out.println(e);
}
}
예시 링크 :
https://m.blog.naver.com/saka/222558249112
예시 코드 04
application.yml
===============
naver-cloud-sms:
accessKey: "secretKey? accessKey"
secretKey: "secretKey"
serviceId: "serviceId"
senderPhone: "?"
SmsController.java
==================
@RestController
@RequiredArgsConstructor
public class SmsController {
private final SmsService smsService;
@PostMapping("/sms/send")
public SmsResponseDto sendSms(@RequestBody MessageDto messageDto) throws UnsupportedEncodingException, URISyntaxException, NoSuchAlgorithmException, InvalidKeyException, JsonProcessingException {
SmsResponseDto responseDto = smsService.sendSms(messageDto);
return responseDto;
}
}
SmsService.java
===============
// application.yml의 값을 @Value로 전달받는다.
@PropertySource("classpath:application.yml")
@Service
@Slf4j
@RequiredArgsConstructor
public class SmsService {
private final String smsConfirmNum = createSmsKey();
private final SmsRepository smsRepository;
@Value("${naver-cloud-sms.accessKey}")
private String accessKey;
@Value("${naver-cloud-sms.secretKey}")
private String secretKey;
@Value("${naver-cloud-sms.serviceId}")
private String serviceId;
@Value("${naver-cloud-sms.senderPhone}")
private String phone;
public SmsResponseDto sendSms(MessageDto messageDto) throws JsonProcessingException, RestClientException, URISyntaxException, InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
// 현재시간
String time = Long.toString(System.currentTimeMillis());
// 헤더세팅
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("x-ncp-apigw-timestamp", time);
headers.set("x-ncp-iam-access-key", accessKey);
headers.set("x-ncp-apigw-signature-v2", getSignature(time)); // signature 서명
List<MessageDto> messages = new ArrayList<>();
messages.add(messageDto);
// api 요청 양식에 맞춰 세팅
SmsRequestDto request = SmsRequestDto.builder()
.type("SMS")
.contentType("COMM")
.countryCode("82")
.from(phone)
.content("[sms test] 인증번호 [" + smsConfirmNum + "]를 입력해주세요")
.messages(messages)
.build();
//request를 json형태로 body로 변환
ObjectMapper objectMapper = new ObjectMapper();
String body = objectMapper.writeValueAsString(request);
// body와 header을 합친다
HttpEntity<String> httpBody = new HttpEntity<>(body, headers);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
//restTemplate를 통해 외부 api와 통신
SmsResponseDto smsResponseDto = restTemplate.postForObject(new URI("https://sens.apigw.ntruss.com/sms/v2/services/"+ serviceId +"/messages"), httpBody, SmsResponseDto.class);
SmsResponseDto responseDto = new SmsResponseDto(smsConfirmNum);
Sms sms = new Sms(messageDto.getTo(), responseDto.getSmsConfirmNum());
smsRepository.save(sms);
return smsResponseDto;
}
// 전달하고자 하는 데이터를 암호화해주는 작업
public String getSignature(String time) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
String space = " ";
String newLine = "\n";
String method = "POST";
String url = "/sms/v2/services/"+ this.serviceId+"/messages";
String accessKey = this.accessKey;
String secretKey = this.secretKey;
String message = new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(time)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
return encodeBase64String;
}
// 5자리의 난수를 조합을 통해 인증코드 만들기
public static String createSmsKey() {
StringBuffer key = new StringBuffer();
Random rnd = new Random();
for (int i = 0; i < 5; i++) { // 인증코드 5자리
key.append((rnd.nextInt(10)));
}
return key.toString();
}
예시 링크 :
예시 코드 05
package band.gosrock.infrastructure.config.AlilmTalk;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@Configuration
public class AlimTalk {
private final String serviceID;
private final String ncpAccessKey;
private final String ncpSecretKey;
private final String plusFriendId;
public AlimTalk(
@Value("${ncp.service-id}") String serviceID,
@Value("${ncp.access-key}") String ncpAccessKey,
@Value("${ncp.secret-key}") String ncpSecretKey,
@Value("${ncp.plus-friend-id}") String plusFriendId) {
this.serviceID = serviceID;
this.ncpAccessKey = ncpAccessKey;
this.ncpSecretKey = ncpSecretKey;
this.plusFriendId = plusFriendId;
}
public void sendAlimTalk(String to, String templateCode, String content) {
String alimTalkSendRequestUrl =
"https://sens.apigw.ntruss.com/alimtalk/v2/services/" + serviceID + "/messages";
String alimTalkSignatureRequestUrl = "/alimtalk/v2/services/" + serviceID + "/messages";
CloseableHttpClient httpClient = null;
try {
// signature 생성
String[] signatureArray =
makePostSignature(ncpAccessKey, ncpSecretKey, alimTalkSignatureRequestUrl);
// http 통신 객체 생성
httpClient = HttpClients.createDefault(); // http client 생성
HttpPost httpPost = new HttpPost(alimTalkSendRequestUrl); // post 메서드와 URL 설정
// 헤더 설정
httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
httpPost.setHeader("x-ncp-iam-access-key", ncpAccessKey);
httpPost.setHeader("x-ncp-apigw-timestamp", signatureArray[0]);
httpPost.setHeader("x-ncp-apigw-signature-v2", signatureArray[1]);
// body 설정
JSONObject msgObj = new JSONObject();
msgObj.put("plusFriendId", plusFriendId);
msgObj.put("templateCode", templateCode);
JSONObject messages = new JSONObject();
messages.put("to", to);
messages.put("content", content);
JSONArray messageArray = new JSONArray();
messageArray.put(messages);
msgObj.put("messages", messageArray);
// api 전송 값 http 객체에 담기
httpPost.setEntity(new StringEntity(msgObj.toString(), "UTF-8"));
// api 호출
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
// 응답 결과
String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
System.out.println(result);
} catch (Exception ex) {
// TODO: 에러 처리
ex.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String[] makePostSignature(String accessKey, String secretKey, String url) {
String[] result = new String[2];
try {
String timeStamp = String.valueOf(Instant.now().toEpochMilli()); // current timestamp (epoch)
String space = " "; // space
String newLine = "\n"; // new line
String method = "POST"; // method
String message =
new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timeStamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
result[0] = timeStamp;
result[1] = encodeBase64String;
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
public String[] makeGetSignature(String accessKey, String secretKey, String url) {
String[] result = new String[2];
try {
String timeStamp = String.valueOf(Instant.now().toEpochMilli()); // current timestamp (epoch)
String space = " "; // space
String newLine = "\n"; // new line
String method = "GET"; // method
String message =
new StringBuilder()
.append(method)
.append(space)
.append(url)
.append(newLine)
.append(timeStamp)
.append(newLine)
.append(accessKey)
.toString();
SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
String encodeBase64String = Base64.encodeBase64String(rawHmac);
result[0] = timeStamp;
result[1] = encodeBase64String;
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
예시 링크 :
https://cofls6581.tistory.com/270
'Team Project (국비) > Team Project 메모' 카테고리의 다른 글
최종프로젝트 Controller, View 파트 진행도 (0) | 2023.09.06 |
---|---|
Spring 프레임워크로 비동기 처리 구현 하기 (1) | 2023.09.04 |
오류 페이지 설정 태그 (XML 설정 파일) (0) | 2023.09.03 |
최종 프로젝트 Controller 설계 (0) | 2023.08.29 |
인텔리제이 학생 라이센스 인증 방법 (0) | 2023.08.06 |