카폐24 문자 보내기

카폐24 문자 보내기

QA

카폐24 문자 보내기

본문

카페24 sms api 를 이용해 문자를 보내려고 합니다. 

 

write_update_skin.php 에 함수를 넣어서

 

글이 작성되면 알림문자가 되게 하려고 합니다. 

일단 아래와 같이 작성하였고



<?php

function sendSMS($message) {
    // SMS API 연동을 위한 설정
    $smsUrl = "https://sslsms.cafe24.com/sms_sender.php"; // SMS API 엔드포인트
    $userId = "aaa"; // SMS 아이디
    $secureKey = "sss"; // 보안키
    $phoneNumber = '*** 개인정보보호를 위한 휴대폰번호 노출방지 ***';

    // 전화번호 설정
    $rphone = base64_encode($phoneNumber); // 받는 사람 전화번호

    // SMS 내용 설정
    $msg = base64_encode($message); // 메시지를 base64로 인코딩

    $headers = [];
    $headers[] = "cache-control : no-cache";
    $headers[] = "content-type : application/json; charset=utf-8";

    $host_info = explode("/", $smsUrl);
    $host = $host_info[2];
    $path = $host_info[3]."/".$host_info[4];

    $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);

    $header = [];
    $header[] = "POST /".$path ." HTTP/1.0\r\n";
    $header[] = "Host: ".$host."\r\n";
    $header[] = "Content-type: multipart/form-data, boundary=".$boundary."\r\n";

//    $header = "POST /".$path ." HTTP/1.0\r\n";
//    $header .= "Host: ".$host."\r\n";
//    $header .= "Content-type: multipart/form-data, boundary=".$boundary."\r\n";

    //echo $header; exit;

    // SMS API 요청 데이터 설정
    $postData = array(
        'user_id' => $userId,
        'secure' => $secureKey,
        'msg' => $msg,
        'rphone' => $rphone,
    );

    // cURL을 사용하여 SMS API에 요청을 보냄
    $ch = curl_init();
    curl_setopt($CH, CURLOPT_URL, $smsUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    $response = curl_exec($ch);
    
    curl_close($ch);

    // 결과 확인 및 처리
    if ($response === false) {
        // 오류 처리
        return "Failed to send SMS notification.";
    } else {
        // 성공적으로 SMS를 보낸 경우
        return "SMS notification sent successfully.";
    }
}





아래는 cafe24 참고 소스입니다.

//입력폽
    <html>
    <head>
        <title>sms - php </title>
        <script type = "text/javascript">
            function setPhoneNumber(val){
                var numList = val.split("-");
                document.smsForm.sphone1.value=numList[0];
                document.smsForm.sphone2.value=numList[1];
                if(numList[2] != undefined){
                    document.smsForm.sphone3.value=numList[2];
                }
            }
            function loadJSON(){
                var data_file = "/calljson.php";
                var http_request = new XMLHttpRequest();
                try{
                    // Opera 8.0+, Firefox, Chrome, Safari
                    http_request = new XMLHttpRequest();
                }catch (e){
                    // Internet Explorer Browsers
                    try{
                        http_request = new ActiveXObject("Msxml2.XMLHTTP");
                    }catch (e) {
                        try{
                            http_request = new ActiveXObject("Microsoft.XMLHTTP");
                        }catch (e){
                            // Eror
                            alert("지원하지 않는브라우저!");
                            return false;
                        }
                    }
                }
                http_request.onreadystatechange = function(){
                    if (http_request.readyState == 4  ){
                        // Javascript function JSON.parse to parse JSON data
                        var jsonObj = JSON.parse(http_request.responseText);
                        if(jsonObj['result'] == "Success"){
                            var aList = jsonObj['list'];
                            var selectHtml = "<select name=\"sendPhone\" onchange=\"setPhoneNumber(this.value)\">";
                            selectHtml += "<option value='' selected>발신번호를 선택해주세요</option>";
                            for(var i=0; i < aList.length; i++){
                                selectHtml += "<option value=\"" + aList[i] + "\">";
                                selectHtml += aList[i];
                                selectHtml += "</option>";
                            }
                            selectHtml += "</select>";
                            document.getElementById("sendPhoneList").innerHTML = selectHtml;
                        }
                    }
                }
                http_request.open("GET", data_file, true);
                http_request.send();
            }
        </script>
    </head>
    <body onload="loadJSON()">
    <form method="post" name="smsForm" action="발송처리URL">
        <input type="hidden" name="action" value="go">
        발송타입 <span><input type="radio" name="smsType" value="S">단문(SMS)</span><span><input type="radio" name="smsType" value="L">장문(LMS)</span> <br />
        제목 : <input type="text" name="subject" value="제목"> 장문(LMS)인 경우(한글30자이내)<br />
        전송메세지 <textarea name="msg" cols="30" rows="10" style="width:455px;">내용입력</textarea>
        <br /><br /><p>단문(SMS) : 최대 90byte까지 전송할 수 있으며, 잔여건수 1건이 차감됩니다. <br />
            장문(LMS) : 한번에 최대 2,000byte까지 전송할 수 있으며 1회 발송당 잔여건수 3건이 차감됩니다.
        </p>
        <br />받는 번호 <input type="text" name="rphone" value="*** 개인정보보호를 위한 휴대폰번호 노출방지 ***"> 예) 011-011-111 , '-' 포함해서 입력.
        <br />이름삽입번호 <input type="text" name="destination" value="" size=80> 예) *** 개인정보보호를 위한 휴대폰번호 노출방지 ***|홍길동
        <br />
        보내는 번호  <input type="hidden" name="sphone1" >
        <input type="hidden" name="sphone2" >
        <input type="hidden" name="sphone3">
        <span id="sendPhoneList"></span>
        <br />예약 날짜 <input type="text" name="rdate" maxlength="8"> 예)20090909
        <br />예약 시간 <input type="text" name="rtime" maxlength="6"> 예)173000 ,오후 5시 30분,예약시간은 최소 10분 이상으로 설정.
        <br />return url <input type="text" name="returnurl" maxlength="64" value="" >
        <br /> test flag <input type="text" name="testflag" maxlength="1"> 예) 테스트시: Y
        <br />nointeractive <input type="text" name="nointeractive" maxlength="1"> 예) 사용할 경우 : 1, 성공시 대화상자(alert)를 생략.
        <br />반복설정 <input type="checkbox" name="repeatFlag" value="Y">
        <br /> 반복횟수 <select name="repeatNum">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select> 예) 1~10회 가능.
        <br />전송간격<select name="repeatTime"> 예)15분 이상부터 가능.
            <option value="15">15</option>
            <option value="20">20</option>
            <option value="25">25</option>
        </select>분마다
        <br>
        <input type="submit" value="전송">
        <br/>이통사 정책에 따라 발신번호와 수신번호가 같은 경우 발송되지 않습니다.
    </form>
    </body>
    </html>

 


    if($_POST['action']=='go'){
       /******************** 인증정보 ********************/
        $sms_url = "https://sslsms.cafe24.com/sms_sender.php"; // HTTPS 전송요청 URL
        // $sms_url = "http://sslsms.cafe24.com/sms_sender.php"; // 전송요청 URL
        $sms['user_id'] = base64_encode("bareunsms"); //SMS 아이디.
        $sms['secure'] = base64_encode("인증후 사용하세요") ;//인증키
        $sms['msg'] = base64_encode(stripslashes($_POST['msg']));
        if( $_POST['smsType'] == "L"){
              $sms['subject'] =  base64_encode($_POST['subject']);
        }
        $sms['rphone'] = base64_encode($_POST['rphone']);
        $sms['sphone1'] = base64_encode($_POST['sphone1']);
        $sms['sphone2'] = base64_encode($_POST['sphone2']);
        $sms['sphone3'] = base64_encode($_POST['sphone3']);
        $sms['rdate'] = base64_encode($_POST['rdate']);
        $sms['rtime'] = base64_encode($_POST['rtime']);
        $sms['mode'] = base64_encode("1"); // base64 사용시 반드시 모드값을 1로 주셔야 합니다.
        $sms['returnurl'] = base64_encode($_POST['returnurl']);
        $sms['testflag'] = base64_encode($_POST['testflag']);
        $sms['destination'] = strtr(base64_encode($_POST['destination']), '+/=', '-,');
        $returnurl = $_POST['returnurl'];
        $sms['repeatFlag'] = base64_encode($_POST['repeatFlag']);
        $sms['repeatNum'] = base64_encode($_POST['repeatNum']);
        $sms['repeatTime'] = base64_encode($_POST['repeatTime']);
        $sms['smsType'] = base64_encode($_POST['smsType']); // LMS일경우 L
        $nointeractive = $_POST['nointeractive']; //사용할 경우 : 1, 성공시 대화상자(alert)를 생략
        $host_info = explode("/", $sms_url);
        $host = $host_info[2];
        $path = $host_info[3]."/".$host_info[4];
        srand((double)microtime()*1000000);
        $boundary = "---------------------".substr(md5(rand(0,32000)),0,10);
        //print_r($sms);
        // 헤더 생성
        $header = "POST /".$path ." HTTP/1.0\r\n";
        $header .= "Host: ".$host."\r\n";
        $header .= "Content-type: multipart/form-data, boundary=".$boundary."\r\n";
        // 본문 생성
        foreach($sms AS $index => $value){
            $data .="--$boundary\r\n";
            $data .= "Content-Disposition: form-data; name=\"".$index."\"\r\n";
            $data .= "\r\n".$value."\r\n";
            $data .="--$boundary\r\n";
        }
        $header .= "Content-length: " . strlen($data) . "\r\n\r\n";
        $fp = fsockopen($host, 80);
        if ($fp) {
            fputs($fp, $header.$data);
            $rsp = '';
            while(!feof($fp)) {
                $rsp .= fgets($fp,8192);
            }
            fclose($fp);
            $msg = explode("\r\n\r\n",trim($rsp));
            $rMsg = explode(",", $msg[1]);
            $Result= $rMsg[0]; //발송결과
            $Count= $rMsg[1]; //잔여건수
            //발송결과 알림
            if($Result=="success") {
                $alert = "성공";
                $alert .= " 잔여건수는 ".$Count."건 입니다.";
            }
            else if($Result=="reserved") {
                $alert = "성공적으로 예약되었습니다.";
                $alert .= " 잔여건수는 ".$Count."건 입니다.";
            }
            else if($Result=="3205") {
                $alert = "잘못된 번호형식입니다.";
            }
            else if($Result=="0044") {
                $alert = "스팸문자는발송되지 않습니다.";
            }
            else {
                $alert = "[Error]".$Result;
            }
        }
        else {
            $alert = "Connection Failed";
        }
         if($nointeractive=="1" && ($Result!="success" && $Result!="Test Success!" && $Result!="reserved") ) {
            echo "<script>alert('".$alert ."')</script>";
        }
        else if($nointeractive!="1") {
            echo "<script>alert('".$alert ."')</script>";
        }
        echo "<script>location.href='".$returnurl."';</script>";
    }
            

 


    $oCurl = curl_init();
    $url =  "https://sslsms.cafe24.com/smsSenderPhone.php";
    $aPostData['userId'] = "bareunsms"; // SMS 아이디
    $aPostData['passwd'] = "인증후 사용하세요"; // 인증키
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_POST, 1);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $aPostData);
    curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, 0);
    $ret = curl_exec($oCurl);
    echo $ret;
    curl_close($oCurl);
            

예제소스를 넣으니 소스가 기네요. 조언 부탁드립니다.

이 질문에 댓글 쓰기 :

답변 1

예를 들어, write_update_skin.php 파일에 글이 작성되는 부분에 알림 문자를 보내는 코드를 추가하면, 글이 작성될 때마다 알림 문자가 전송되지 않을까 생각합니다.

 

예를 들어 아래와 같이 하면 되지 않을까요?


// 글이 작성되는 부분
// 여기서 알림 문자를 보내고 싶다면
$message = "새로운 글이 작성되었습니다."; // 보낼 메시지 설정
sendSMS($message); // 알림 문자 보내기
답변을 작성하시기 전에 로그인 해주세요.
전체 205
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT