본문 바로가기

API/JAVA

[API] 전화번호 인증 API

사전 준비

  • 사이트에 가입 필요
  • API key 발급 필요

예제 프로젝트 다운

https://github.com/coolsms/coolsms-java-examples

 

GitHub - coolsms/coolsms-java-examples: CoolSMS Java/Kotlin SDK 예제 목록

CoolSMS Java/Kotlin SDK 예제 목록. Contribute to coolsms/coolsms-java-examples development by creating an account on GitHub.

github.com


maven-spring-demo를 import


pom.xml 설정

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>nutritional-shopping-mall</groupId>
  <artifactId>nutritional-shopping-mall</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>pom.xml</name>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <dependencies>
            <dependency>
                   <groupId>net.nurigo</groupId>
                <artifactId>sdk</artifactId>
                <version>4.3.0</version>
            </dependency>    
        </dependencies>
        <version>3.8.1</version>
        <configuration>
          <release>17</release>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.2.3</version>
      </plugin>
    </plugins>
  </build>
  <dependencies>
      <dependency>
          <groupId>net.nurigo</groupId>
          <artifactId>maven-spring-demo</artifactId>
          <version>0.0.1-SNAPSHOT</version>
      </dependency>
  </dependencies>
</project>

HTML

<div class="col-lg-2">
	<input class="form-control p-3 border-secondary" 
    	type="number" name="phoneNum1" id="phoneNum1" value="010" readonly required>
</div>
<div class="col-lg-3">
	<input class="form-control p-3 border-secondary" 
    	type="number" name="phoneNum2" id="phoneNum2" placeholder="0000" required>
</div>
<div class="col-lg-3">
	<input class="form-control p-3 border-secondary" 
    	type="number" name="phoneNum3" id="phoneNum3" placeholder="0000" required>
</div>
<div class="col-lg-4">
	<button class="btn border border-secondary 
    	text-primary rounded-pill px-4 py-3" type="button" onclick="checkTel()">
        인증번호 발송</button>	
</div>
<div class="col-lg-8">
	<input class="form-control p-3 border-secondary" 
    	type="text" name="authNum" id="authNum" placeholder="인증번호" required>
</div>
<div class="col-lg-4">
	<button class="btn border border-secondary 
    	text-primary rounded-pill px-4 py-3" type="button" onclick="checkAuthNum()">인증번호 확인</button>	
</div>

jquery

  • 인증번호 발송 요청
<script type="text/javascript">
	
		var telResult;
	
		function checkTel() {
			var phoneNum1 = $("#phoneNum1").val();
			var phoneNum2 = $("#phoneNum2").val();
			var phoneNum3 = $("#phoneNum3").val();
			$.ajax({
	        	type: "POST",
	        	url: "CheckTel",
	        	data: { 'phoneNum1':phoneNum1, 'phoneNum2':phoneNum2, 'phoneNum3':phoneNum3},
	        	success: function(data) {
	        		telResult = data;
	        	}
	    	});
		}
	</script>

Servlet

  • 인증번호 발송 및 view에 값을 돌려줌
@WebServlet("/CheckTel")
public class CheckTel extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CheckTel() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
		/* Servlet CheckTel
        * 
        * 번호가 3개 합치기
        * 인증번호 만들어서 문자 쏘고 세션에 저장
        * 
        * 번호 인증 버튼 눌렀어
        * 뷰 -- 전화번호 3개로 --> 컨트롤러
        * 컨트롤러 -- 인증번호(요청 파라미터) --> 뷰 (인증번호 확인은 뷰가)
		*/
		
		String phoneNumber1=(String)request.getParameter("phoneNum1");
		String phoneNumber2=(String)request.getParameter("phoneNum2");
		String phoneNumber3=(String)request.getParameter("phoneNum3");
		
		String combinedPhoneNumber=phoneNumber1+phoneNumber2+phoneNumber3;
		
		//인증번호 랜덤으로 생성
		Random random  = new Random();
        String numStr = "";
        for(int i=0; i<5; i++) {
            String ranNum = Integer.toString(random.nextInt(10));   // 0부터 9까지 랜덤으로 숫자생성
            numStr += ranNum;   // 랜덤으로 나온 숫자를 누적 => 5자리
        }
        
		//sms api를 사용하여 sms 발송
		DefaultMessageService messageService =  NurigoApp.INSTANCE.initialize("", "", "https://api.coolsms.co.kr");
		// Message 패키지가 중복될 경우 net.nurigo.sdk.message.model.Message로 치환하여 주세요
		Message message = new Message();
		message.setFrom("");
		message.setTo(combinedPhoneNumber);
		message.setText("내또코 영양제 쇼핑몰 인증번호 ["+numStr+"]을 입력해주세요. (•ө•)♡");

		try {
		  messageService.send(message);
		} catch (NurigoMessageNotReceivedException exception) {
		  // 발송에 실패한 메시지 목록을 확인할 수 있습니다!
		  System.out.println(exception.getFailedMessageList());
		  System.out.println(exception.getMessage());
		} catch (Exception exception) {
		  System.out.println(exception.getMessage());
		}
		
		//V에 인증번호 전달
		PrintWriter out = response.getWriter();
		out.print(numStr);	
	}

}

jquery

  • 휴대폰 인증번호 확인
<script type="text/javascript">
			function checkAuthNum(){
				var authNum = $("#authNum").val();
				if(telResult === authNum){
					Swal.fire({
	        			icon: 'success',
	        			title: '휴대폰 인증',
	        			text: '인증이 완료되었습니다.',
	   	 			})
				} else {
					Swal.fire({
	        			icon: 'error',
	        			title: '휴대폰 인증',
	        			text: '인증이 실패하였습니다.',
	   	 			})
				}
			}
		</script>

'API > JAVA' 카테고리의 다른 글

[API] 카카오 로그인 레거시  (0) 2024.02.23
[API] 우편번호 API  (0) 2024.01.16