sms_ncloud.py
· 2.3 KiB · Python
Raw
import sys
import json
import requests
import argparse
def send_sms_via_gateway(api_key, service_id, to_number, content):
"""
API Key만 사용하여 API Gateway(Cloud Functions 연결)를 호출합니다.
Access/Secret Key는 Cloud Function의 디폴트 파라미터를 사용하므로 필요 없습니다.
"""
# API Gateway 엔드포인트 도메인 및 경로
# 제공해주신 정보에 따라 v0_3 경로를 유지합니다.
url = f"https://nxw98mm70w.apigw.ntruss.com/baron_sso_sms/v0_3/services/{service_id}/messages"
# 헤더 설정 (Access Key/Signature 없이 API Key만 전송)
headers = {
'Content-Type': 'application/json; charset=utf-8',
'x-ncp-apigw-api-key': api_key
}
# 바디 설정 (Go 코드의 로그에서 확인된 구조에 맞춤)
body = {
"service_id": service_id,
"content": content,
"messages": [
{
"to": to_number.replace("-", "") # 하이픈 제거
}
]
}
try:
print(f"[Request URL]: {url}")
# SSL 인증서 검증 오류 방지를 위해 verify=False 추가 (필요시 제거)
response = requests.post(url, headers=headers, data=json.dumps(body), verify=False)
# 결과 반환
if response.status_code in [200, 202]:
return response.json()
else:
return {
"http_status": response.status_code,
"error": response.text
}
except Exception as e:
return {"error": str(e)}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Ncloud API Gateway SMS Client (API Key Only)")
# 이제 accessKey와 secretKey는 필수가 아닙니다.
parser.add_argument("--apiKey", required=True, help="NCP API Gateway API Key")
parser.add_argument("--serviceId", required=True, help="SENS Service ID")
parser.add_argument("--to", required=True, help="수신 번호 (예: 01012345678)")
parser.add_argument("--msg", default="API Key 인증 테스트 메시지", help="전송할 내용")
args = parser.parse_args()
print("--- SMS 발송 요청 시작 ---")
result = send_sms_via_gateway(args.apiKey, args.serviceId, args.to, args.msg)
print("\n[Response Result]")
print(json.dumps(result, indent=2, ensure_ascii=False))
| 1 | import sys |
| 2 | import json |
| 3 | import requests |
| 4 | import argparse |
| 5 | |
| 6 | def send_sms_via_gateway(api_key, service_id, to_number, content): |
| 7 | """ |
| 8 | API Key만 사용하여 API Gateway(Cloud Functions 연결)를 호출합니다. |
| 9 | Access/Secret Key는 Cloud Function의 디폴트 파라미터를 사용하므로 필요 없습니다. |
| 10 | """ |
| 11 | # API Gateway 엔드포인트 도메인 및 경로 |
| 12 | # 제공해주신 정보에 따라 v0_3 경로를 유지합니다. |
| 13 | url = f"https://nxw98mm70w.apigw.ntruss.com/baron_sso_sms/v0_3/services/{service_id}/messages" |
| 14 | |
| 15 | # 헤더 설정 (Access Key/Signature 없이 API Key만 전송) |
| 16 | headers = { |
| 17 | 'Content-Type': 'application/json; charset=utf-8', |
| 18 | 'x-ncp-apigw-api-key': api_key |
| 19 | } |
| 20 | |
| 21 | # 바디 설정 (Go 코드의 로그에서 확인된 구조에 맞춤) |
| 22 | body = { |
| 23 | "service_id": service_id, |
| 24 | "content": content, |
| 25 | "messages": [ |
| 26 | { |
| 27 | "to": to_number.replace("-", "") # 하이픈 제거 |
| 28 | } |
| 29 | ] |
| 30 | } |
| 31 | |
| 32 | try: |
| 33 | print(f"[Request URL]: {url}") |
| 34 | # SSL 인증서 검증 오류 방지를 위해 verify=False 추가 (필요시 제거) |
| 35 | response = requests.post(url, headers=headers, data=json.dumps(body), verify=False) |
| 36 | |
| 37 | # 결과 반환 |
| 38 | if response.status_code in [200, 202]: |
| 39 | return response.json() |
| 40 | else: |
| 41 | return { |
| 42 | "http_status": response.status_code, |
| 43 | "error": response.text |
| 44 | } |
| 45 | except Exception as e: |
| 46 | return {"error": str(e)} |
| 47 | |
| 48 | if __name__ == "__main__": |
| 49 | parser = argparse.ArgumentParser(description="Ncloud API Gateway SMS Client (API Key Only)") |
| 50 | |
| 51 | # 이제 accessKey와 secretKey는 필수가 아닙니다. |
| 52 | parser.add_argument("--apiKey", required=True, help="NCP API Gateway API Key") |
| 53 | parser.add_argument("--serviceId", required=True, help="SENS Service ID") |
| 54 | parser.add_argument("--to", required=True, help="수신 번호 (예: 01012345678)") |
| 55 | parser.add_argument("--msg", default="API Key 인증 테스트 메시지", help="전송할 내용") |
| 56 | |
| 57 | args = parser.parse_args() |
| 58 | |
| 59 | print("--- SMS 발송 요청 시작 ---") |
| 60 | result = send_sms_via_gateway(args.apiKey, args.serviceId, args.to, args.msg) |
| 61 | |
| 62 | print("\n[Response Result]") |
| 63 | print(json.dumps(result, indent=2, ensure_ascii=False)) |
| 64 |