휴대전화 문자인증(2) - Naver Sms API

신동훈·2022년 9월 15일
0
#SmsService

public class SmsService {
	//시그니처 생성
    private 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;    
    }
	//요청 Body
    public void sendSMS(CertiReq phoneNumber, String rand) {
        String hostNameUrl = "https://sens.apigw.ntruss.com";
        String requestUrl = "/sms/v2/services/";
        String ServiceId = "ServiceId(발급)";
      	String requestUrlType = "/messages";
        String accessKey = "accessKey(발급)";
        String secretKey = "secretKey(발급)";
        String method = "POST";
        String timeStamp = Long.toString(System.currentTimeMillis());
        requestUrl += ServiceId + requestUrlType;
        String apiUrl = hostNameUrl + requestUrl;
		
      	//JSON 객체로 만들기
        JSONObject bodyJson = new JSONObject();
        JSONObject toJson = new JSONObject();
        JSONArray toArr = new JSONArray();
		
      	//요청 Body의 messages에 입력
        toJson.put("to", phoneNumber.getPhoneNumber());
        toArr.add(toJson);
        
        bodyJson.put("type", "SMS");    
        bodyJson.put("from", "07086566630");
        bodyJson.put("content", "인증번호 ["+ rand +"]를 입력해주세요.");
        bodyJson.put("messages", toArr);
    
        String body = bodyJson.toString();

        System.out.println(body);
		
      	//HTTP 통신으로 API Request
        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);
        }
    }
}
#CertiService 
//추가
<...>
  Random random = new Random();
  SmsService message = new SmsService();
<...>
  message.sendSMS(req, numStr);
profile
독학 정리

0개의 댓글