// api/v1/token
define('BASE_URL', 'https://api.munja.co.kr');
/**
* API 서버에 토큰 발급을 요청합니다.
*
*/
function token($userId, $apiKey)
{
$url = BASE_URL . '/api/v1/token';
$data = array(
'userId' => $userId,
'sec_apiKey' => $apiKey
);
$headers = array(
'Content-Type: application/json'
);
// cURL 초기화
$ch = curl_init();
// cURL 옵션 설정
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// cURL 실행
$response = curl_exec($ch);
// cURL 에러 확인
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch) . "\n";
curl_close($ch);
return null;
}
// HTTP 상태 코드 확인
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
} else {
echo "Error: " . $httpCode . " - " . $response . "\n";
return null;
}
}
$testUserId = "test_user";
$testApiKey = "your_secret_api_key";
$tokenInfo = token($testUserId, $testApiKey);
if ($tokenInfo) {
echo json_encode($tokenInfo);
}
// api/v1/message
define('BASE_URL', 'https://api.munja.co.kr');
/**
* API 서버에 메시지 전송을 요청합니다.
*
* @param string $token 인증 토큰 (token.php 실행하여 얻은 accessToken)
* @param string $userId 사용자 아이디
* @param string $apiKey 사용자의 API 인증키
* @param string $sender 발신자 전화번호
* @param array $receiver 수신자 전화번호 배열
* @param string $title 메시지 제목 (LMS, MMS의 경우 필수)
* @param string $message 메시지 내용
* @param string $messageType 메시지 타입 (SMS, LMS, MMS)
* @param array|null $name 수신자 이름 배열 (선택 사항)
* @param string|null $rDate 예약 날짜 (YYYYMMDDHHMM 형식, 선택 사항)
* @param array|null $imagePaths 전송할 이미지 파일의 경로 배열 (MMS용, 선택 사항)
* @return array|null API 응답을 배열 형식으로 반환합니다. 실패 시 null을 반환합니다.
*/
function message($token, $userId, $apiKey, $sender, $receiver, $name, $r_date, $imgs, $title, $message, $messageType)
{
$url = BASE_URL . '/api/v1/message';
$data = array(
'userId' => $userId,
'sec_apiKey' => $apiKey,
'sender' => $sender,
'receiver' => $receiver,
'name' => $name, // 선택 사항
'r_date' => $r_date, // 선택 사항
'imgs' => $imgs, // 선택 사항
'title' => $title,
'message' => $message,
'messageType' => $messageType
);
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $token
);
// cURL 초기화
$ch = curl_init();
// cURL 옵션 설정
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// cURL 실행
$response = curl_exec($ch);
// cURL 에러 확인
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch) . "\n";
curl_close($ch);
return null;
}
// HTTP 상태 코드 확인
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
} else {
echo "Error: " . $httpCode . " - " . $response . "\n";
return null;
}
}
// --- 사용 예시 ---
$testToken = "your_access_token_here";
$testUserId = "test_user";
$testApiKey = "your_secret_api_key";
$testSender = "01012345678";
$testReceivers = array("01098765432");
$testName = array("홍길동");
$testRdate = "202310010000"; // YYYYMMDDHHMM
$testImgs = array(
array(
"name" => "test_image.jpg",
"data" => "base64 Encoded Image Data",
"size" => 100
)
);
$testMessageType = "sms"; // 메시지 타입 (sms, lms, mms)
$smsTitle = "SMS 테스트";
// 치환문자의 경우 "{이름} or {name} 님 안녕하세요." 로 작성가능합니다.
$smsMessage = "이것은 PHP 예제 코드를 통한 SMS 테스트 메시지입니다.";
$smsResponse = message(
$testToken,
$testUserId,
$testApiKey,
$testSender,
$testReceivers,
$testName,
$testRdate,
$testImgs,
$smsTitle,
$smsMessage,
$testMessageType
);
if ($smsResponse) {
echo json_encode($smsResponse);
}
// api/v1/cash
define('BASE_URL', 'https://api.munja.co.kr');
/**
* API 서버에 캐시(잔액) 정보 조회를 요청합니다.
*
*/
function cash($token, $userId, $apiKey)
{
$url = BASE_URL . '/api/v1/cash';
$data = array(
'userId' => $userId,
'sec_apiKey' => $apiKey
);
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $token
);
// cURL 초기화
$ch = curl_init();
// cURL 옵션 설정
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// cURL 실행
$response = curl_exec($ch);
// cURL 에러 확인
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch) . "\n";
curl_close($ch);
return null;
}
// HTTP 상태 코드 확인
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
} else {
echo "Error: " . $httpCode . " - " . $response . "\n";
return null;
}
}
// --- 사용 예시 --- //
$testToken = "your_access_token_here";
$testUserId = "test_user";
$testApiKey = "your_secret_api_key";
$cashInfo = cash($testToken, $testUserId, $testApiKey);
if ($cashInfo) {
echo json_encode($cashInfo);
}
// api/v1/cancel
define('BASE_URL', 'https://api.munja.co.kr');
/**
* API 서버에 메시지 예약 취소를 요청합니다.
*
*/
function cancel($token, $userId, $apiKey, $messageKey)
{
$url = BASE_URL . '/api/v1/cancel';
$data = array(
'userId' => $userId,
'sec_apiKey' => $apiKey,
'messageKey' => $messageKey
);
$headers = array(
'Content-Type: application/json',
'Authorization: Bearer ' . $token
);
// cURL 초기화
$ch = curl_init();
// cURL 옵션 설정
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// cURL 실행
$response = curl_exec($ch);
// cURL 에러 확인
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch) . "\n";
curl_close($ch);
return null;
}
// HTTP 상태 코드 확인
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
return json_decode($response, true);
} else {
echo "Error: " . $httpCode . " - " . $response . "\n";
return null;
}
}
// --- 사용 예시 --- //
$testToken = "your_access_token_here";
$testUserId = "test_user";
$testApiKey = "your_secret_api_key";
$testMessageKey = "your_message_key_to_cancel";
$cancelResponse = cancel($testToken, $testUserId, $testApiKey, $testMessageKey);
if ($cancelResponse) {
echo json_encode($cancelResponse);
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashMap;
import java.util.Map;
/**
* Java API 호출
* api/v1/token
* JDK 17+ 버전 사용
*/
public class ApiToken {
private static final String BASE_URL = "https://api.munja.co.kr";
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* API 서버에 토큰 발급을 요청합니다.
*/
public static JsonNode token(String userId, String apiKey) {
try {
String url = BASE_URL + "/api/v1/token";
// 요청 데이터 생성
Map data = new HashMap<>();
data.put("userId", userId);
data.put("sec_apiKey", apiKey);
String jsonData = objectMapper.writeValueAsString(data);
// HTTP 클라이언트 생성 (JDK 11+)
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
// HTTP 요청 생성
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
// 요청 실행
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return objectMapper.readTree(response.body());
} else {
System.err.println("Error: " + response.statusCode() + " - " + response.body());
return null;
}
} catch (IOException | InterruptedException e) {
System.err.println("An error occurred: " + e.getMessage());
return null;
}
}
public static void main(String[] args) {
String TEST_USER_ID = "USER_ID";
String TEST_API_KEY = "your_secret_api_key";
JsonNode tokenInfo = token(TEST_USER_ID, TEST_API_KEY);
if (tokenInfo != null) {
try {
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(tokenInfo));
} catch (IOException e) {
System.err.println("JSON formatting error: " + e.getMessage());
}
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Java API 호출
* api/v1/message
* JDK 17+ 버전 사용
*/
public class ApiMessage {
private static final String BASE_URL = "https://api.munja.co.kr";
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* API 서버에 메시지 전송을 요청합니다.
*/
public static JsonNode message(String token, String userId,
String sender, List receiver, List name,
String rDate, List
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashMap;
import java.util.Map;
/**
* Java API 호출
* api/v1/cash
* JDK 17+ 버전 사용
*/
public class ApiCash {
private static final String BASE_URL = "https://api.munja.co.kr";
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* API 서버에 캐시(잔액) 정보 조회를 요청합니다.
*/
public static JsonNode cash(String token, String userId) {
try {
String url = BASE_URL + "/api/v1/cash";
// 요청 데이터 생성
Map data = new HashMap<>();
data.put("userId", userId);
String jsonData = objectMapper.writeValueAsString(data);
// HTTP 클라이언트 생성 (JDK 11+)
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
// HTTP 요청 생성
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
// 요청 실행
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return objectMapper.readTree(response.body());
} else {
System.err.println("Error: " + response.statusCode() + " - " + response.body());
return null;
}
} catch (IOException | InterruptedException e) {
System.err.println("An error occurred: " + e.getMessage());
return null;
}
}
public static void main(String[] args) {
// String TEST_TOKEN = "your_access_token_here";
String TEST_TOKEN = "your_secret_api_key";
String TEST_USER_ID = "USER_ID";
JsonNode cashInfo = cash(TEST_TOKEN, TEST_USER_ID);
if (cashInfo != null) {
try {
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(cashInfo));
} catch (IOException e) {
System.err.println("JSON formatting error: " + e.getMessage());
}
}
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.HashMap;
import java.util.Map;
/**
* Java API 호출
* api/v1/cancel
* JDK 17+ 버전 사용
*/
public class ApiCancel {
private static final String BASE_URL = "https://api.munja.co.kr";
private static final ObjectMapper objectMapper = new ObjectMapper();
/**
* API 서버에 메시지 예약 취소를 요청합니다.
*/
public static JsonNode cancel(String token, String userId, String messageKey) {
try {
String url = BASE_URL + "/api/v1/cancel";
// 요청 데이터 생성
Map data = new HashMap<>();
data.put("userId", userId);
data.put("messageKey", messageKey);
String jsonData = objectMapper.writeValueAsString(data);
// HTTP 클라이언트 생성 (JDK 11+)
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
// HTTP 요청 생성
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + token)
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(jsonData))
.build();
// 요청 실행
HttpResponse response = client.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
return objectMapper.readTree(response.body());
} else {
System.err.println("Error: " + response.statusCode() + " - " + response.body());
return null;
}
} catch (IOException | InterruptedException e) {
System.err.println("An error occurred: " + e.getMessage());
return null;
}
}
public static void main(String[] args) {
// String TEST_TOKEN = "your_access_token_here";
String TEST_TOKEN = "your_secret_api_key";
String TEST_USER_ID = "USER_ID";
String TEST_MESSAGE_KEY = "202508051128_ip-ao";
JsonNode cancelResponse = cancel(TEST_TOKEN, TEST_USER_ID, TEST_MESSAGE_KEY);
if (cancelResponse != null) {
try {
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(cancelResponse));
} catch (IOException e) {
System.err.println("JSON formatting error: " + e.getMessage());
}
}
}
}
import requests
import json
# Python API 호출
# api/v1/token
BASE_URL = "https://api.munja.co.kr"
def token(user_id, api_key):
"""
API 서버에 토큰 발급을 요청합니다.
"""
url = f"{BASE_URL}/api/v1/token"
headers = {
"Content-Type": "application/json"
}
data = {
"userId": user_id,
"sec_apiKey": api_key
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
TEST_USER_ID = "USER_ID"
TEST_API_KEY = "your_secret_api_key"
token_info = token(TEST_USER_ID, TEST_API_KEY)
if token_info:
print(json.dumps(token_info, indent=4, ensure_ascii=False))
import requests
import json
# Python API 호출
# api/v1/message
BASE_URL = "https://api.munja.co.kr"
def message(token, user_id, sender, receiver, title, message, message_type, name=None, r_date=None, imgs=None):
"""
API 서버에 메시지 전송을 요청합니다.
"""
url = f"{BASE_URL}/api/v1/message"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
data = {
"userId": user_id,
"sender": sender,
"receiver": receiver,
"title": title,
"message": message,
"messageType": message_type, # (sms, lms, mms)
}
if name is not None:
data["name"] = name
if r_date is not None:
data["r_date"] = r_date
if imgs is not None:
data["imgs"] = imgs
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
# TEST_TOKEN = "your_access_token_here"
TEST_TOKEN = "your_secret_api_key"
TEST_USER_ID = "USER_ID"
TEST_SENDER = "SEND_NUMBER"
TEST_RECEIVERS = [""]
TEST_NAME = ['홍길동']
TEST_R_DATE = "20250805110600" # YYYYMMDDHHMMSS
TEST_IMGS = [
{
"name" : "image1.jpg",
"data": "data:image/jpeg;base64,...",
"size": 100
},
] # 이미지 파일 경로
sms_title = "문자 테스트"
// 치환문자의 경우 "{이름} or {name} 님 안녕하세요." 로 작성가능합니다.
sms_message = "이것은 파이썬 예제 코드를 통한 문자 테스트 메시지입니다."
message_type = "mms" # 메시지 타입 (sms, lms, mms)
sms_response = message(
TEST_TOKEN,
TEST_USER_ID,
TEST_SENDER,
TEST_RECEIVERS,
sms_title,
sms_message,
message_type,
globals().get('TEST_NAME'), # TEST_NAME if TEST_NAME else None,
globals().get('TEST_R_DATE'), # TEST_NAME if TEST_NAME else None,
globals().get('TEST_IMGS'), # TEST_NAME if TEST_NAME else None,
)
if sms_response:
print(json.dumps(sms_response, indent=4, ensure_ascii=False))
import requests
import json
# Python API 호출
# api/v1/cash
BASE_URL = "https://api.munja.co.kr"
def cash(token, user_id):
"""
API 서버에 캐시(잔액) 정보 조회를 요청합니다.
"""
url = f"{BASE_URL}/api/v1/cash"
# 인증 토큰을 헤더에 추가합니다.
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
data = {
"userId": user_id,
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
# TEST_TOKEN = "your_access_token_here"
TEST_TOKEN = "your_secret_api_key"
TEST_USER_ID = "USER_ID"
cash_info = cash(TEST_TOKEN, TEST_USER_ID)
if cash_info:
print(json.dumps(cash_info, indent=4, ensure_ascii=False))
import requests
import json
# Python API 호출
# api/v1/cancel
BASE_URL = "https://api.munja.co.kr"
def cancel(token, user_id, message_key):
"""
API 서버에 메시지 예약 취소를 요청합니다.
"""
url = f"{BASE_URL}/api/v1/cancel"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
}
data = {
"userId": user_id,
"messageKey": message_key
}
try:
response = requests.post(url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code} - {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == "__main__":
# TEST_TOKEN = "your_access_token_here"
TEST_TOKEN = "your_secret_api_key"
TEST_USER_ID = "USER_ID"
TEST_MESSAGE_KEY = "202508051101_iwyqB"
cancel_response = cancel(TEST_TOKEN, TEST_USER_ID, TEST_MESSAGE_KEY)
if cancel_response:
print(json.dumps(cancel_response, indent=4, ensure_ascii=False))
const BASE_URL = 'https://api.munja.co.kr';
const USER_ID = 'test_user';
const SEC_API_KEY = 'your_secret_api_key';
function testIssueToken() {
const response = UrlFetchApp.fetch(BASE_URL + '/api/v1/token', {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify({ userId: USER_ID, sec_apiKey: SEC_API_KEY }),
muteHttpExceptions: true
});
const bodyText = response.getContentText();
const body = JSON.parse(bodyText);
const accessToken = body.result.accessToken;
PropertiesService
.getScriptProperties()
.setProperty('ACCESS_TOKEN', accessToken);
Logger.log('status=' + response.getResponseCode());
Logger.log(bodyText);
Logger.log('ACCESS_TOKEN saved');
}
const SENDER = '01012345678';
const RECEIVER = ['01098765432'];
function testSendSms() {
sendMessage('SMS test', 'Google Apps Script SMS example.', 'sms');
}
function testSendMmsWithDriveImage() {
const file = DriveApp.getFileById('your_google_drive_file_id');
const blob = file.getBlob();
const bytes = blob.getBytes();
const base64 = Utilities.base64Encode(bytes);
sendMessage('MMS test', 'Google Apps Script MMS example.', 'mms', [{
name: file.getName(),
size: bytes.length,
data: 'data:image/jpeg;base64,' + base64
}]);
}
function sendMessage(title, message, messageType, imgs) {
const accessToken = PropertiesService
.getScriptProperties()
.getProperty('ACCESS_TOKEN');
const payload = {
userId: USER_ID,
sec_apiKey: SEC_API_KEY,
sender: SENDER,
receiver: RECEIVER,
title: title,
message: message,
messageType: messageType
};
if (imgs) payload.imgs = imgs;
const response = UrlFetchApp.fetch(BASE_URL + '/api/v1/message', {
method: 'post',
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + accessToken },
payload: JSON.stringify(payload),
muteHttpExceptions: true
});
Logger.log('status=' + response.getResponseCode());
Logger.log(response.getContentText());
}
function testCash() {
const accessToken = PropertiesService
.getScriptProperties()
.getProperty('ACCESS_TOKEN');
const response = UrlFetchApp.fetch(BASE_URL + '/api/v1/cash', {
method: 'post',
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + accessToken },
payload: JSON.stringify({ userId: USER_ID, sec_apiKey: SEC_API_KEY }),
muteHttpExceptions: true
});
Logger.log('status=' + response.getResponseCode());
Logger.log(response.getContentText());
}
function testCancel() {
const accessToken = PropertiesService
.getScriptProperties()
.getProperty('ACCESS_TOKEN');
const response = UrlFetchApp.fetch(BASE_URL + '/api/v1/cancel', {
method: 'post',
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + accessToken },
payload: JSON.stringify({
userId: USER_ID,
sec_apiKey: SEC_API_KEY,
messageKey: 'your_message_key_to_cancel'
}),
muteHttpExceptions: true
});
Logger.log('status=' + response.getResponseCode());
Logger.log(response.getContentText());
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#define BASE_URL "https://api.munja.co.kr"
struct APIResponse {
char *data;
size_t size;
};
// HTTP 응답 데이터를 저장하는 콜백 함수
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct APIResponse *response = (struct APIResponse *)userp;
char *ptr = realloc(response->data, response->size + realsize + 1);
if (ptr == NULL) {
printf("Memory allocation failed!\n");
return 0;
}
response->data = ptr;
memcpy(&(response->data[response->size]), contents, realsize);
response->size += realsize;
response->data[response->size] = 0;
return realsize;
}
/**
* API 서버에 토큰 발급을 요청합니다.
*/
cJSON* api_token(const char* user_id, const char* api_key) {
CURL *curl;
CURLcode res;
struct APIResponse response = {0};
cJSON *json_response = NULL;
curl = curl_easy_init();
if (!curl) {
printf("CURL initialization failed\n");
return NULL;
}
// URL 설정
char url[256];
snprintf(url, sizeof(url), "%s/api/v1/token", BASE_URL);
// JSON 데이터 생성
cJSON *json = cJSON_CreateObject();
cJSON *json_user_id = cJSON_CreateString(user_id);
cJSON *json_api_key = cJSON_CreateString(api_key);
cJSON_AddItemToObject(json, "userId", json_user_id);
cJSON_AddItemToObject(json, "sec_apiKey", json_api_key);
char *json_string = cJSON_Print(json);
// HTTP 헤더 설정
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
// CURL 옵션 설정
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
// 요청 실행
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("CURL request failed: %s\n", curl_easy_strerror(res));
} else {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == 200) {
json_response = cJSON_Parse(response.data);
if (!json_response) {
printf("JSON parsing failed\n");
}
} else {
printf("Error: %ld - %s\n", response_code, response.data ? response.data : "No response");
}
}
// 메모리 정리
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(json_string);
cJSON_Delete(json);
if (response.data) {
free(response.data);
}
return json_response;
}
int main() {
// 테스트 데이터
const char* TEST_USER_ID = "USER_ID";
const char* TEST_API_KEY = "your_secret_api_key";
// CURL 전역 초기화
curl_global_init(CURL_GLOBAL_DEFAULT);
// 토큰 요청
cJSON *token_info = api_token(TEST_USER_ID, TEST_API_KEY);
if (token_info) {
char *json_output = cJSON_Print(token_info);
printf("%s\n", json_output);
free(json_output);
cJSON_Delete(token_info);
}
// CURL 전역 정리
curl_global_cleanup();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#define BASE_URL "https://api.munja.co.kr"
struct APIResponse {
char *data;
size_t size;
};
// HTTP 응답 데이터를 저장하는 콜백 함수
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct APIResponse *response = (struct APIResponse *)userp;
char *ptr = realloc(response->data, response->size + realsize + 1);
if (ptr == NULL) {
printf("메모리 할당 실패!\n");
return 0;
}
response->data = ptr;
memcpy(&(response->data[response->size]), contents, realsize);
response->size += realsize;
response->data[response->size] = 0;
return realsize;
}
/**
* API 서버에 메시지 전송을 요청합니다.
*/
cJSON* api_message(const char* token, const char* user_id,
const char* sender, const char** receivers, int receiver_count,
const char* title, const char* message, const char* message_type,
const char** names, int name_count, const char* r_date,
const char** img_names, const char** img_data, int* img_sizes, int img_count) {
CURL *curl;
CURLcode res;
struct APIResponse response = {0};
cJSON *json_response = NULL;
curl = curl_easy_init();
if (!curl) {
printf("CURL 초기화 실패\n");
return NULL;
}
// URL 설정
char url[256];
snprintf(url, sizeof(url), "%s/api/v1/message", BASE_URL);
// JSON 데이터 생성
cJSON *json = cJSON_CreateObject();
cJSON *json_user_id = cJSON_CreateString(user_id);
cJSON *json_sender = cJSON_CreateString(sender);
cJSON *json_title = cJSON_CreateString(title);
cJSON *json_message = cJSON_CreateString(message);
cJSON *json_message_type = cJSON_CreateString(message_type);
// 수신자 배열
cJSON *json_receivers = cJSON_CreateArray();
for (int i = 0; i < receiver_count; i++) {
cJSON_AddItemToArray(json_receivers, cJSON_CreateString(receivers[i]));
}
cJSON_AddItemToObject(json, "userId", json_user_id);
cJSON_AddItemToObject(json, "sender", json_sender);
cJSON_AddItemToObject(json, "receiver", json_receivers);
cJSON_AddItemToObject(json, "title", json_title);
cJSON_AddItemToObject(json, "message", json_message);
cJSON_AddItemToObject(json, "messageType", json_message_type);
// 선택적 파라미터: 이름
if (names && name_count > 0) {
cJSON *json_names = cJSON_CreateArray();
for (int i = 0; i < name_count; i++) {
cJSON_AddItemToArray(json_names, cJSON_CreateString(names[i]));
}
cJSON_AddItemToObject(json, "name", json_names);
}
// 선택적 파라미터: 예약 날짜
if (r_date) {
cJSON_AddItemToObject(json, "r_date", cJSON_CreateString(r_date));
}
// 선택적 파라미터: 이미지
if (img_names && img_data && img_sizes && img_count > 0) {
cJSON *json_imgs = cJSON_CreateArray();
for (int i = 0; i < img_count; i++) {
cJSON *img_obj = cJSON_CreateObject();
cJSON_AddItemToObject(img_obj, "name", cJSON_CreateString(img_names[i]));
cJSON_AddItemToObject(img_obj, "data", cJSON_CreateString(img_data[i]));
cJSON_AddItemToObject(img_obj, "size", cJSON_CreateNumber(img_sizes[i]));
cJSON_AddItemToArray(json_imgs, img_obj);
}
cJSON_AddItemToObject(json, "imgs", json_imgs);
}
char *json_string = cJSON_Print(json);
// HTTP 헤더 설정
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
char auth_header[512];
snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", token);
headers = curl_slist_append(headers, auth_header);
// CURL 옵션 설정
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
// 요청 실행
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("CURL 요청 실패: %s\n", curl_easy_strerror(res));
} else {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == 200) {
json_response = cJSON_Parse(response.data);
if (!json_response) {
printf("JSON 파싱 실패\n");
}
} else {
printf("Error: %ld - %s\n", response_code, response.data ? response.data : "No response");
}
}
// 메모리 정리
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(json_string);
cJSON_Delete(json);
if (response.data) {
free(response.data);
}
return json_response;
}
int main() {
// 테스트 데이터
const char* TEST_TOKEN = "your_secret_api_key";
const char* TEST_USER_ID = "USER_ID";
const char* TEST_SENDER = "SEND_NUMBER";
const char* TEST_RECEIVERS[] = {""};
const char* TEST_R_DATE = "20250805135700"; // YYYYMMDDHHMMSS
// 선택적 파라미터 (주석 처리하여 테스트 가능)
const char* TEST_NAMES[] = {"홍길동"};
const char* TEST_IMG_NAMES[] = {"image1.jpg"};
const char* TEST_IMG_DATA[] = {"data:image/jpeg;base64,...}
int TEST_IMG_SIZES[] = {strlen(TEST_IMG_DATA[0])};
const char* sms_title = "문자 테스트";
// 치환문자의 경우 "{이름} or {name} 님 안녕하세요." 로 작성가능합니다.
const char* sms_message = "이것은 C 예제 코드를 통한 문자 테스트 메시지입니다.";
const char* message_type = "mms"; // 메시지 타입 (sms, lms, mms)
// CURL 전역 초기화
curl_global_init(CURL_GLOBAL_DEFAULT);
// 메시지 전송 (선택적 파라미터 없이)
cJSON *sms_response = api_message(
TEST_TOKEN,
TEST_USER_ID,
TEST_SENDER,
TEST_RECEIVERS,
1, // receiver_count
sms_title,
sms_message,
message_type,
TEST_NAMES, // names
1, // name_count
TEST_R_DATE,
TEST_IMG_NAMES, // img_names
TEST_IMG_DATA, // img_data
TEST_IMG_SIZES, // img_sizes
1 // img_count
);
if (sms_response) {
char *json_output = cJSON_Print(sms_response);
printf("%s\n", json_output);
free(json_output);
cJSON_Delete(sms_response);
}
// CURL 전역 정리
curl_global_cleanup();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#define BASE_URL "https://api.munja.co.kr"
struct APIResponse {
char *data;
size_t size;
};
// HTTP 응답 데이터를 저장하는 콜백 함수
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct APIResponse *response = (struct APIResponse *)userp;
char *ptr = realloc(response->data, response->size + realsize + 1);
if (ptr == NULL) {
printf("메모리 할당 실패!\n");
return 0;
}
response->data = ptr;
memcpy(&(response->data[response->size]), contents, realsize);
response->size += realsize;
response->data[response->size] = 0;
return realsize;
}
/**
* API 서버에 캐시(잔액) 정보 조회를 요청합니다.
*/
cJSON* api_cash(const char* token, const char* user_id) {
CURL *curl;
CURLcode res;
struct APIResponse response = {0};
cJSON *json_response = NULL;
curl = curl_easy_init();
if (!curl) {
printf("CURL 초기화 실패\n");
return NULL;
}
// URL 설정
char url[256];
snprintf(url, sizeof(url), "%s/api/v1/cash", BASE_URL);
// JSON 데이터 생성
cJSON *json = cJSON_CreateObject();
cJSON *json_user_id = cJSON_CreateString(user_id);
cJSON_AddItemToObject(json, "userId", json_user_id);
char *json_string = cJSON_Print(json);
// HTTP 헤더 설정
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
char auth_header[512];
snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", token);
headers = curl_slist_append(headers, auth_header);
// CURL 옵션 설정
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
// 요청 실행
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("CURL 요청 실패: %s\n", curl_easy_strerror(res));
} else {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == 200) {
json_response = cJSON_Parse(response.data);
if (!json_response) {
printf("JSON 파싱 실패\n");
}
} else {
printf("Error: %ld - %s\n", response_code, response.data ? response.data : "No response");
}
}
// 메모리 정리
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(json_string);
cJSON_Delete(json);
if (response.data) {
free(response.data);
}
return json_response;
}
int main() {
// 테스트 데이터
const char* TEST_TOKEN = "your_secret_api_key";
const char* TEST_USER_ID = "USER_ID";
// CURL 전역 초기화
curl_global_init(CURL_GLOBAL_DEFAULT);
// 캐시 정보 조회
cJSON *cash_info = api_cash(TEST_TOKEN, TEST_USER_ID);
if (cash_info) {
char *json_output = cJSON_Print(cash_info);
printf("%s\n", json_output);
free(json_output);
cJSON_Delete(cash_info);
}
// CURL 전역 정리
curl_global_cleanup();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>
#define BASE_URL "https://api.munja.co.kr"
struct APIResponse {
char *data;
size_t size;
};
// HTTP 응답 데이터를 저장하는 콜백 함수
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct APIResponse *response = (struct APIResponse *)userp;
char *ptr = realloc(response->data, response->size + realsize + 1);
if (ptr == NULL) {
printf("메모리 할당 실패!\n");
return 0;
}
response->data = ptr;
memcpy(&(response->data[response->size]), contents, realsize);
response->size += realsize;
response->data[response->size] = 0;
return realsize;
}
/**
* API 서버에 메시지 예약 취소를 요청합니다.
*/
cJSON* api_cancel(const char* token, const char* user_id, const char* message_key) {
CURL *curl;
CURLcode res;
struct APIResponse response = {0};
cJSON *json_response = NULL;
curl = curl_easy_init();
if (!curl) {
printf("CURL 초기화 실패\n");
return NULL;
}
// URL 설정
char url[256];
snprintf(url, sizeof(url), "%s/api/v1/cancel", BASE_URL);
// JSON 데이터 생성
cJSON *json = cJSON_CreateObject();
cJSON *json_user_id = cJSON_CreateString(user_id);
cJSON *json_message_key = cJSON_CreateString(message_key);
cJSON_AddItemToObject(json, "userId", json_user_id);
cJSON_AddItemToObject(json, "messageKey", json_message_key);
char *json_string = cJSON_Print(json);
// HTTP 헤더 설정
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
char auth_header[512];
snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", token);
headers = curl_slist_append(headers, auth_header);
// CURL 옵션 설정
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_string);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&response);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L);
// 요청 실행
res = curl_easy_perform(curl);
if (res != CURLE_OK) {
printf("CURL 요청 실패: %s\n", curl_easy_strerror(res));
} else {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
if (response_code == 200) {
json_response = cJSON_Parse(response.data);
if (!json_response) {
printf("JSON 파싱 실패\n");
}
} else {
printf("Error: %ld - %s\n", response_code, response.data ? response.data : "No response");
}
}
// 메모리 정리
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(json_string);
cJSON_Delete(json);
if (response.data) {
free(response.data);
}
return json_response;
}
int main() {
// 테스트 데이터
const char* TEST_TOKEN = "your_secret_api_key";
const char* TEST_USER_ID = "USER_ID";
const char* TEST_MESSAGE_KEY = "202508051349_yv7QI";
// CURL 전역 초기화
curl_global_init(CURL_GLOBAL_DEFAULT);
// 메시지 취소 요청
cJSON *cancel_response = api_cancel(TEST_TOKEN, TEST_USER_ID, TEST_MESSAGE_KEY);
if (cancel_response) {
char *json_output = cJSON_Print(cancel_response);
printf("%s\n", json_output);
free(json_output);
cJSON_Delete(cancel_response);
}
// CURL 전역 정리
curl_global_cleanup();
return 0;
}
Ctrl + D 키를 눌러 즐겨찾기에 등록하실 수 있습니다.
