[Spring Boot] 문자인증 구현 coolSMS

2022. 5. 24. 15:24 Spring Framework/Spring boot3

회원가입 또는 가입 후 휴대폰인증 구현을 위한 API  'coolSMS' 사용방법

: 다날과같은 서비스를 이용하여 문자인증을 구현하기위해서는 실제로 업체와 계약을 통해 진행해야하기때문에 학부 프로젝트에서는 적용할수가 없다. 그래서 비슷하게 흉내내기위해 coolSMS라는 문자메시지 전송 API를 이용해서 구현해보았다.

 

 

1. coolSMS 사용 준비 

- coolsms 회원가입 하기

- coolsms 개발자센터에 접속합니다.

 

쿨에스엠에스 - 우주에서 가장 빠르고 안정적이고 쉬운 문자메시지(SMS) 서비스를 제공합니다.

알림톡, 문자메시지를 쉽고 빠르게 전달해 드립니다.

developer.coolsms.co.kr

-JAVA 클릭

coolsms 사용준비 

-아래 화면에 보이는 step1과 step2를 차례대로 실행

 => API KEY와 API SECRET  생성 후 ,  git에서 SDK 다운로드

coolsms 사용준비 

-git에서 다운받은 SDK의 압축을 풀고 lib 폴더안에있는 두개의 파일을 라이브러리에 추가

 => 인텔리제이 기준 (File - Projects Structure - Libraries   -   + 버튼 클릭 후 추가)

 

- build.gradle 의존성 추가

compile group: 'net.nurigo', name: 'javaSDK', version: '2.2'

 


2. 코딩

 

-번호를 입력 후 [번호확인] 버튼을 누르면 ajax로 input 에 입력된 번호가 controller로 전송된다.

-Random 메소드를 통해 인증번호 4자리를 랜덤으로 생성

 

-controller

@GetMapping("/check/sendSMS")
    public @ResponseBody
    String sendSMS(String phoneNumber) {

        Random rand  = new Random();
        String numStr = "";
        for(int i=0; i<4; i++) {
            String ran = Integer.toString(rand.nextInt(10));
            numStr+=ran;
        }

        System.out.println("수신자 번호 : " + phoneNumber);
        System.out.println("인증번호 : " + numStr);
        certificationService.certifiedPhoneNumber(phoneNumber,numStr);
        return numStr;
    }

-service (coolSMS)

 public void certifiedPhoneNumber(String phoneNumber, String cerNum) {

        String api_key = "본인의 API KEY";
        String api_secret = "본인의 API SECRET";
        Message coolsms = new Message(api_key, api_secret);

        // 4 params(to, from, type, text) are mandatory. must be filled
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("to", phoneNumber);    // 수신전화번호
        params.put("from", "발송할 번호 입력");    // 발신전화번호. 테스트시에는 발신,수신 둘다 본인 번호로 하면 됨
        params.put("type", "SMS");
        params.put("text", "핫띵크 휴대폰인증 테스트 메시지 : 인증번호는" + "["+cerNum+"]" + "입니다.");
        params.put("app_version", "test app 1.2"); // application name and version

        try {
            JSONObject obj = (JSONObject) coolsms.send(params);
            System.out.println(obj.toString());
        } catch (CoolsmsException e) {
            System.out.println(e.getMessage());
            System.out.println(e.getCode());
        }

    }

 

 

- ajax를 이용해서 랜덤으로 생성된 4자리의 인증번호와  [인증번호입력] input에 입력된 번호가 일치할 경우 인증성공

<script>
        $('#sendPhoneNumber').click(function(){
            let phoneNumber = $('#inputPhoneNumber').val();
            Swal.fire('인증번호 발송 완료!')


            $.ajax({
                type: "GET",
                url: "/check/sendSMS",
                data: {
                    "phoneNumber" : phoneNumber
                },
                success: function(res){
                    $('#checkBtn').click(function(){
                        if($.trim(res) ==$('#inputCertifiedNumber').val()){
                            Swal.fire(
                                '인증성공!',
                                '휴대폰 인증이 정상적으로 완료되었습니다.',
                                'success'
                            )

                            $.ajax({
                                type: "GET",
                                url: "/update/phone",
                                data: {
                                    "phoneNumber" : $('#inputPhoneNumber').val()
                                }
                            })
                            document.location.href="/home";
                        }else{
                            Swal.fire({
                                icon: 'error',
                                title: '인증오류',
                                text: '인증번호가 올바르지 않습니다!',
                                footer: '<a href="/home">다음에 인증하기</a>'
                            })
                        }
                    })


                }
            })
        });
</script>

2021-03-15 

Redis회원가입시 사용되는 인증번호 Redis로 관리하기

1-7171771.tistory.com/141

 

[Spring] 회원가입시 필요한 인증번호 관리

프로젝트의 전체 소스 코드는 이곳에서 확인하실 수 있습니다. 이전에 진행했었던 프로젝트에서도 휴대폰 인증을 통한 회원가입 인증번호를 구현했었는데 당시에는 인증번호의 일치 불일치 여

1-7171771.tistory.com

 

출처 : https://1-7171771.tistory.com/84?category=885255