Message API reference

Overview

Samsung Cloud Platform에서 제공하는 Message Hub는 Email, SMS, Mobile Application Push Notification 채널로 메시지를 발송할 수 있습니다.
본 가이드에서는 Message Hub의 메시지 전송 API에 대한 설명 및 호출하는 방법을 제공합니다.

참고
  • 메시지 전송 API를 호출하기 전에 발송에 사용할 리소스(Email, 전화번호, Push Application)를 Console에서 먼저 추가하고 인증을 완료해야 합니다. 리소스 추가 방법은 Message Hub How-to guides를 참고하세요.
  • 채널의 월별 발신 개수는 SMS 10,000 건, Email 100,000 건, Push 1,000,000 건으로 제한됩니다. 발신 제한 개수를 증설하려면 Support Center > 서비스 요청을 통하여 진행해 주세요.

Message Hub 호출 절차

Message Hub API URL 주소는 운영환경과 Region에 따라 변경되어야 하며, 호출 구간에 따라 Public URL과 Private URL로 구분됩니다. 아래의 표에서 해당 운영환경과 Region 정보를 확인하십시오.

운영 환경RegionPublic URLPrivate URL
For Enterprisekr-west1https://messagehub.service.kr-west1.e.samsungsdscloud.comhttps://messagehub.private.kr-west1.e.samsungsdscloud.com
For Enterprisekr-east1https://messagehub.service.kr-east1.e.samsungsdscloud.comhttps://messagehub.private.kr-east1.e.samsungsdscloud.com
참고
  • Public URL: 인터넷 구간에서 Message Hub를 호출할 때 사용합니다.
  • Private URL: VPC 내부 자원에서 Private Endpoint를 통해 Message Hub를 호출할 때 사용합니다. Private Endpoint 호출이 허용되지 않은 경우 400 AccessDeniedException 오류가 발생합니다.
  • 본 가이드의 호출 예시는 Public URL을 기준으로 작성되었습니다. Private 구간에서 호출하는 경우 URL만 Private URL로 변경하면 되며, 요청 헤더와 본문은 동일합니다.

API 호출하기

AUTH PARAMS

Header Description
X-Scp-Access-Key   : 삼성 클라우드 플랫폼 포털에서 발급받은 Access Key
X-Scp-Signature    : 호출 API 요청을 Access Key와 매핑되는 Access Secret Key로 암호화한 서명. HMAC 암호화 알고리즘은 HmacSHA256 사용
X-Scp-Timestamp    : 1970년 1월 1일 00:00:00 협정 세계시(UTC)부터의 경과 시간을 밀리초(Millisecond)로 정의합니다.
X-Scp-Client-Type  : Userapi 고정(대소문자 구분)
Content-Type       : application/json 명시
참고
메시지 전송 API는 위의 5개 헤더가 모두 필수입니다. X-Scp-Client-Type 헤더가 누락되면 400 InvalidParameterCombination 오류가 발생합니다.

Signature 생성하기

  • 메시지 전송 API를 통해 Message Hub를 호출하려면 “인증키” 인증 모드로 유효한 접근 허용 IP에서 “인증키"를 통해 인증해야 합니다.
  • 요청으로부터 서명할 문자열을 생성하고 Access, Secret Key로 HmacSHA256 알고리즘으로 암호화 후 Base64로 인코딩합니다.
  • 이 값을 X-Scp-Signature로 사용합니다.
  • 생성된 Signature는 15분간 유효합니다.
Signature 생성 Sample Code (Java)
public static String makeHmacSignature(String method,
                                       String url,
                                       String timestamp,
                                       String accessKey,
                                       String accessSecretKey,
                                       String clientType) {

    String body = method + url + timestamp + accessKey + clientType;

    String encodeBase64Str;

    try {
        byte[] message = body.getBytes("UTF-8");
        byte[] secretKey = accessSecretKey.getBytes("UTF-8");

        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "HmacSHA256");
        mac.init(secretKeySpec);
        byte[] hmacSha256 = mac.doFinal(message);
        encodeBase64Str = Base64.getEncoder().encodeToString(hmacSha256);
    } catch (Exception e) {
        throw new RuntimeException("Failed to calculate hmac-sha256", e);
    }

    return encodeBase64Str;
}
Signature 생성 Sample Code (JavaScript)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64-min.js"></script>
<script type="text/javascript">
function makeSignature() {
    var method = "POST"; // Method
    var url = "{url}"; // url (예: /v1/emails/{email_id}/send)
    var timestamp = Date.now(); // timestamp
    var accessKey = "{accessKey}"; // access key
    var secretKey = "{secretKey}"; // secret key
    var clientType = "Userapi"; // client type

    url = encodeURI(url); // 한글, 특수 문자 처리

    var message = method + url + timestamp + accessKey + clientType;

    var hash = CryptoJS.HmacSHA256(message, secretKey);
    return CryptoJS.enc.Base64.stringify(hash);
}
</script>

Message Hub API 호출 예시

Curl

curl -i -X POST
-H "X-Scp-Access-Key:2sd2gg=2agbdSD26svcD"
-H "X-Scp-Signature:fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef="
-H "X-Scp-Timestamp:1605290625682"
-H "X-Scp-Client-Type:Userapi"
-H "Content-Type:application/json"
--data '{"recipient_addresses": ["someone@example.com"], "title": "notification title", "body": "notification body"}'
'https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/emails/33ff0000a8a345d78cdf163673f3da11/send'

Python

import requests

url = "https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/emails/33ff0000a8a345d78cdf163673f3da11/send"
payload = {
   'recipient_addresses': ['someone@example.com'],
   'title': 'notification title',
   'body': 'notification body'
}
headers = {
  'X-Scp-Access-Key': '2sd2gg=2agbdSD26svcD',
  'X-Scp-Signature': 'fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef=',
  'X-Scp-Timestamp': '1605290625682',
  'X-Scp-Client-Type': 'Userapi',
  'Content-Type': 'application/json'
}

response = requests.request("POST", url, headers=headers, json=payload)

if response.status_code == 204:
    return None
else:
    raise Exception(f"Failed to POST API: {response.status_code}, {response.text}")

Java

String apiUrl = "https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/emails/33ff0000a8a345d78cdf163673f3da11/send";
String accessKey = "2sd2gg=2agbdSD26svcD";
String signature = "fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef=";
String timestamp = "1605290625682";
String clientType = "Userapi";
String requestBody = "{\"recipient_addresses\":[\"someone@example.com\"],\"title\":\"notification title\",\"body\":\"notification body\"}";

public static void sendMessage(String apiUrl, String requestBody) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost postRequest = new HttpPost(apiUrl);
        postRequest.addHeader("X-Scp-Access-Key", accessKey);
        postRequest.addHeader("X-Scp-Signature", signature);
        postRequest.addHeader("X-Scp-Timestamp", timestamp);
        postRequest.addHeader("X-Scp-Client-Type", clientType);
        postRequest.addHeader("Content-Type", "application/json");
        postRequest.setEntity(new StringEntity(requestBody, "UTF-8"));

        HttpResponse response = httpClient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 204) {
            httpClient.close();
        } else {
            String responseBody = EntityUtils.toString(response.getEntity());
            httpClient.close();
            throw new RuntimeException("Failed to Request: " + statusCode + ", " + responseBody);
        }
    }

Message Hub Message API

Message Hub는 채널별로 다음과 같은 메시지 전송 API를 제공합니다.

채널API설명
EmailPOST /v1/emails/{email_id}/sendEmail 발송
SMSPOST /v1/phones/{phone_id}/sendPhone Book SMS 발송
PushPOST /v1/push-applications/{application_id}/sendPush Application 발송(FCM HTTP v1)
참고
모든 메시지 전송 API는 성공 시 응답 본문이 없는 204 No Content를 반환합니다. 요청 본문 전체 크기는 294,912 bytes를 초과할 수 없습니다.

Email 발송

POST https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/emails/{email_id}/send

Description

등록된 발신 Email 리소스를 사용하여 수신자에게 Email을 발송합니다.

Path Parameters

필드명필수 여부타입설명
email_idtruestring발신 Email 리소스 ID(32자)

Body Parameters

필드명필수 여부타입설명제약 사항
recipient_addressestruestring[]수신자 메일 주소 목록최소 1개, 최대 100개. 빈 문자열 불가
titletruestring메일 제목
bodytruestring메일 본문(HTML/텍스트)최대 262,144 bytes

Responses

HTTP CodeDescriptionSchema
204No Content
400Bad Request
401 / 403Unauthorized / Forbidden
404Not Found
413Request Entity Too Large
429Too Many Requests
500Internal Server Error
503Service Unavailable

Errors

HTTP CodeError Code설명
400MissingParameteremail_id, recipient_addresses, title 누락
400InvalidParameterValue본문 형식 오류, 알 수 없는 필드, 빈 수신 주소, 수신자 100개 초과
400InvalidParameterCombinationX-Scp-Client-Type 헤더 누락
400AccessDeniedException미인증 발신자(unverified_policy=deny), 발신 리소스의 계정 불일치, private endpoint 미허용
401 / 403UnAuthorized / MissingAuthenticationToken서명 검증 실패, 권한 없음
404StatusNotFound발신 Email 리소스 없음
413RequestEntityTooLarge요청 본문 294,912 bytes 초과 또는 메일 본문 262,144 bytes 초과
429LimitExceededException월 발송 quota 초과(Retry-After 헤더 동반)
500InternalServerError내부 오류
503ServiceUnavailable일시적 처리 불가

Example HTTP request

Request Header
"X-Scp-Access-Key:2sd2gg=2agbdSD26svcD",
"X-Scp-Signature:fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef=",
"X-Scp-Timestamp:1605290625682",
"X-Scp-Client-Type:Userapi",
"Content-Type:application/json"
Request Body
{
  "recipient_addresses": ["someone@example.com"],
  "title": "notification title",
  "body": "notification body"
}

Example HTTP response

204 Response

Phone Book SMS 발송

POST https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/phones/{phone_id}/send

Description

등록된 발신 Phone 리소스를 사용하여 수신 전화번호로 SMS를 발송합니다.

Path Parameters

필드명필수 여부타입설명
phone_idtruestring발신 Phone 리소스 ID(32자)

Body Parameters

필드명필수 여부타입설명제약 사항
recipientstruestring[]수신 전화번호 목록국제발신번호 사용, 최소 1개, 최대 100개
texttruestring문자메시지 본문최대 90 bytes
수신자 번호 입력 형식

수신자 번호는 ITU-T E.164 형식을 따르며, + 접두 유무로 국내/국제 표기를 구분합니다.

입력 예시해석국가번호설명
+821012345678국제 표기(E.164)82국가번호를 표에서 최장 접두 일치로 유도
+14155552671국제 표기(NANP)1NANP 영토는 4자리까지 매칭(+1876 등)
01012345678국내(대한민국)82(기본값)+가 없으면 국내 번호로 본다
010-1234-5678국내82-와 공백은 제거된다

Responses

HTTP CodeDescriptionSchema
204No Content
400Bad Request
401 / 403Unauthorized / Forbidden
404Not Found
413Request Entity Too Large
429Too Many Requests
500Internal Server Error
503Service Unavailable

Errors

HTTP CodeError Code설명
400MissingParameterphone_id, recipients 누락
400InvalidParameterValue본문 형식 오류, 알 수 없는 필드, 수신자 100개 초과
400InvalidParameterCombinationX-Scp-Client-Type 헤더 누락
400AccessDeniedException미인증 발신자, 발신 리소스의 계정 불일치, private endpoint 미허용
401 / 403UnAuthorized / MissingAuthenticationToken서명 검증 실패, 권한 없음
404StatusNotFound발신 Phone 리소스 없음
413RequestEntityTooLarge요청 본문 초과 또는 문자 본문 90 bytes 초과
429LimitExceededException월 발송 quota 초과(Retry-After 헤더 동반)
500InternalServerError내부 오류
503ServiceUnavailable일시적 처리 불가

Example HTTP request

Request Header
"X-Scp-Access-Key:2sd2gg=2agbdSD26svcD",
"X-Scp-Signature:fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef=",
"X-Scp-Timestamp:1605290625682",
"X-Scp-Client-Type:Userapi",
"Content-Type:application/json"
Request Body
{
  "recipients": ["01012345678", "+14155552671"],
  "text": "sms text"
}

Example HTTP response

204 Response

Push Application 발송

POST https://messagehub.service.kr-west1.e.samsungsdscloud.com/v1/push-applications/{application_id}/send

Description

등록된 Push Application 리소스를 사용하여 디바이스 토큰으로 FCM HTTP v1 기반의 Push 메시지를 발송합니다.

Path Parameters

필드명필수 여부타입설명
application_idtruestringPush Application 리소스 ID(32자)

Body Parameters

필드명필수 여부타입설명제약 사항
datatrueobjectdata-only 페이로드최대 1,024 bytes. title, body 필드는 제공하지 않는다
tokenstruestring[]디바이스 토큰 목록최대 100개, 빈 문자열 불가
priorityfalsestringFCM 우선순위
ttlfalsestring메시지 TTL
참고
Push 메시지는 data-only 페이로드로만 발송됩니다. 알림 제목과 본문은 data 페이로드에 담아 전달하고, 디바이스 애플리케이션에서 직접 화면에 표시해야 합니다.

Responses

HTTP CodeDescriptionSchema
204No Content
400Bad Request
401 / 403Unauthorized / Forbidden
404Not Found
413Request Entity Too Large
429Too Many Requests
500Internal Server Error
503Service Unavailable

Errors

HTTP CodeError Code설명
400MissingParameterapplication_id, data 누락, tokens/topic/condition 전부 없음
400InvalidParameterValue본문 형식 오류, 알 수 없는 필드, 빈 토큰, 토큰 100개 초과
400InvalidParameterCombinationX-Scp-Client-Type 헤더 누락
400AccessDeniedException리소스의 계정 불일치, private endpoint 미허용
401 / 403UnAuthorized / MissingAuthenticationToken서명 검증 실패, 권한 없음
404StatusNotFoundPush Application 리소스 없음
413RequestEntityTooLarge요청 본문 초과 또는 data 1,024 bytes 초과
429LimitExceededException월 발송 quota 초과(Retry-After 헤더 동반)
500InternalServerError내부 오류
503ServiceUnavailable일시적 처리 불가

Example HTTP request

Request Header
"X-Scp-Access-Key:2sd2gg=2agbdSD26svcD",
"X-Scp-Signature:fsfsdf235f9U35sdgf35Xsf/qgsdgsdg326=sfsdr23rsef=",
"X-Scp-Timestamp:1605290625682",
"X-Scp-Client-Type:Userapi",
"Content-Type:application/json"
Request Body
{
  "tokens": ["fcm-device-token-1"],
  "data": {
    "key1": "value1",
    "key2": "value2"
  },
  "priority": "high",
  "ttl": "3600s"
}

Example HTTP response

204 Response
How-to guides
Release Note