CI 묻고 답하기

제목 sms 연동 문의
카테고리 CI 4 관련
글쓴이 우연 작성시각 2021/06/23 16:48:45
댓글 : 2 추천 : 0 스크랩 : 0 조회수 : 9401   RSS

sms 모듈을 연동중입니다.

 

샘플소스

https://github.com/innosms/innosms.example.php

 

문자가 발송되는 models 페이지 소스

--------------------------------------------------------------------------------------------------------------------------

//발급받은 API 아이디
$client_id = "api_id";

//발급받은 API키
$api_key = "api_key";

$contents = array(
	"msg_type" => "sms", //메세지 형식
	"phone" => "01000000000", //수신번호, 동보전송일 경우 쉼표로 구분 ex)0111111111,0111111111
	"callback" => "0111111111", //회신번호
	"msg" => "SMS 전송 테스트\n가나다", //전송메세지
);

$MessagingService = new \App\Libraries\MessagingService($client_id, $api_key);
$result = $MessagingService->sendMessage($contents);

/******************************************************************************
- 결과값(배열)
$result['msg_serial'] : 전송 메세지 고유키(전송내역 조회 및 예약 취소를 위해 DB에 저장해서 보관하세요)
$result['total_count'] : 총 전송건수
$result['cost'] : 전송 차감 금액
******************************************************************************/
echo $result['msg_serial'];

 

Libraries/MessagingService.php 페이지

 

<?php
namespace App\Libraries;
class MessagingService 
{
/**
* @file MessagingService.php
* @brief REST API Messaging module (utf-8)
* @author INNOPOST (tech@innopost.com)
*/

	private $ServiceURL = "https://api.innosms.com";
	private $Version = "1";

	private $UserID;
	private $APIKey;
	private $Token;

	public function __construct($UserID, $APIKey){
		$this->UserID = $UserID;
		$this->APIKey = $APIKey;

		$this->Token = $this->getToken();
	}

	public function __destruct(){
		$this->deleteToken();
	}

	private function executeCURL($uri, $method = null, $header = array(), $postdata = null, $isMultiPart = false){
		$http = curl_init($this->ServiceURL."/".$this->Version."/".$uri);

		if($isMultiPart) {
			$header[] = "Content-Type:multipart/form-data";
		}else{
			$header[] = "Content-Type:application/x-www-form-urlencoded;charset=utf-8;";

			if($postdata){
				foreach($postdata as $k => $v){
					if ($k == "msg" || $k == "subject")
						$v = urlencode($v);

					$temp[] = $k."=".$v;
				}
				$postdata = implode($temp,"&");
			}
		}

		$isPost = ($method == "POST")?true:false;


		$options = array(
			CURLOPT_POST => $isPost,
			CURLOPT_SSL_VERIFYPEER => FALSE,
			CURLOPT_HEADER => 0,
			CURLOPT_CUSTOMREQUEST => $method,
			CURLOPT_TIMEOUT => 10,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_HTTPHEADER => $header,
			CURLOPT_POSTFIELDS => $postdata,
		);

		@curl_setopt_array($http, $options);

		$responseJson = curl_exec($http);

		$http_status = curl_getinfo($http, CURLINFO_HTTP_CODE);

		curl_close($http);

		if($http_status != 200){
			throw new APIException($responseJson);
			//오류코드 배열로 수신
			$result = new APIException($responseJson);
			$returnResult = $result->toArray();
		}else{
			$returnResult = json_decode($responseJson ,true);
		}

		return $returnResult;
	}

	private function convertEuckrToUtf8($str) {
		if(is_array($str)){
			foreach($str as $key => $val){
				$returnResult[$key] = mb_convert_encoding($val,"UTF-8","EUC-KR");
			}
		}else{
			$returnResult = mb_convert_encoding($str,"UTF-8","EUC-KR");
		}

		return $returnResult;
	}

	private function setContent($contents,$isPost=false){
		$result = null;

		if($isPost)
		{
			$result = array();
			foreach($contents as $key => $val)
			{
				if($key == "image")
               $result[$key] = (!empty($val))?new CURLFile(realpath($val)):"";
				else{
					/*
					if(preg_match("/^(msg|msg_list|subject)$/", $key)){
						$val = $this->convertEuckrToUtf8($val);
					}
					*/

					if($key == "msg_list"){
						$val = json_encode($val);
					}

					$result[$key] = $val;
				}
			}
		}
		else
		{
			foreach($contents as $val){
				$result .= "/".urlencode($val);
			}
		}

		return $result;
	}

	private function getToken(){
		try{
			$header = array();
			$header[] = "Authorization: Basic ".base64_encode($this->UserID.":".$this->APIKey);
			$result = $this->executeCURL("token","POST",$header);
			return $result['token'];
		}catch(APIException $e){
			echo $e;
			exit;
		}
	}

	private function deleteToken(){
		$header = array();
		$header[] = "Authorization: Bearer ".$this->Token;
		$this->executeCURL("token","DELETE",$header);
	}

	public function getBalance(){
		try{
			$header = array();
			$header[] = "Authorization: Bearer ".$this->Token;
			return $this->executeCURL("balance","GET",$header);
		}catch(APIException $e){
			echo $e;
			exit;
		}
	}

	public function sendMessage($contents){
		try{
			$header = array();
			$header[] = "Authorization: Bearer ".$this->Token;
			$isMulitPart = ($contents['msg_type'] == "mms")?true:false;
			return $this->executeCURL("send","POST",$header,$this->setContent($contents,true),$isMulitPart);
		}catch(APIException $e){
			echo $e;
			exit;
		}
	}

	public function getMessage($contents){
		try{
			$header = array();
			$header[] = "Authorization: Bearer ".$this->Token;
			return $this->executeCURL("send".$this->setContent($contents),"GET",$header);
		}catch(APIException $e){
			echo $e;
			exit;
		}
	}

	public function cancelReservation($contents){
		try{
			$header = array();
			$header[] = "Authorization: Bearer ".$this->Token;
			return $this->executeCURL("reservation".$this->setContent($contents),"DELETE",$header);
		}catch(APIException $e){
			echo $e;
			exit;
		}
	}
}

class APIException extends Exception
{

	public function __construct($response, $code = 10000, Exception $previous = null) {
		$Err = json_decode($response);

		if(is_null($Err)) {
			parent::__construct($response, $code);
		}
		else {
			parent::__construct($Err->message, $Err->code);
		}
	}

	public function toArray(){
		$result = array(
			"code" => $this->code,
			"message" => mb_convert_encoding($this->message,"EUC-KR","UTF-8"),
		);
		return $result;
	}

	public function __toString() {
		return __CLASS__ . ": [{$this->code}]: ".$this->message."\n";
	}
}
?>

SMS API 연동중입니다.

codeigniter으로 처음 개발중이라 삽질중이네요. 

models에서 문자 발송을 하는데 위와 같이 연결해주었습니다.

그리고 오류가 발생합니다. 

Class 'App\\Libraries\\Exception' not found

클래스명을 변경해도 계속 변경된 이름으로 제가 뭘 잘못하고 있는건가요? ㅠㅠ

models로 넣어도 라이브러리로 넣어도 똑같은 에러들만 반복이네요.

 

 

 

 다음글 index.php 죽이기 잘됩니다! 다만 https일때... (2)
 이전글 에러 로그를 그냥 아파치(php)로그에 쌓이도록 할 순... (3)

댓글

변종원(웅파) / 2021/06/23 17:06:22 / 추천 1
모델이 아니라 라이브러리로 작업하셔야 합니다.
한대승(불의회상) / 2021/06/24 09:33:53 / 추천 1
// 잘못된 예
class APIException extends Exception
{
}

// 바른 예
class APIException extends \Exception
{
}
namespace를 지정하셨으니 "Exception" 을 "\Exception" 으로 수정해 주세요.