이미지 문자발송자동화 #16
-
사용 중인 프로그래밍 언어 및 버전Python 3.9 SDK 버전No response 운영 환경개발 환경 (로컬) 질문/문제 설명파일 업로드 API(v1/files)에 HMAC-SHA256 방식으로 요청을 보내도 'SignatureDoesNotMatch' 또는 'Basic 인증 실패' 오류가 발생합니다. 사용 중인 API Key: NCSBMLJ6DWGBKSFS 코드 예시import requests
import pandas as pd
import base64
import mimetypes
import os
import uuid
import hmac
import hashlib
from datetime import datetime, timezone
# ✅ Solapi 인증 정보
API_KEY = 'NCSBMLJ6DWGBKSFS'
API_SECRET = ''
SENDER = '' # 등록된 발신 번호
# ✅ Basic 인증 (문자 전송용)
def get_basic_auth_header():
user_pass = f"{API_KEY}:{API_SECRET}"
encoded = base64.b64encode(user_pass.encode()).decode()
return {
"Authorization": f"Basic {encoded}"
}
# ✅ HMAC 인증 (파일 업로드용)
import uuid
from datetime import datetime, timezone
def make_hmac_headers():
salt = str(uuid.uuid4())
date = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ')
# signature = HMAC_SHA256(salt, API_SECRET)
message = salt.encode('utf-8')
key = API_SECRET.encode('utf-8')
signature = hmac.new(key, message, hashlib.sha256).hexdigest()
print(f"[DEBUG] salt: {salt}")
print(f"[DEBUG] date: {date}")
print(f"[DEBUG] signature: {signature}")
return {
"Authorization": f"HMAC-SHA256 apiKey={API_KEY}, date={date}, salt={salt}, signature={signature}",
"Content-Type": "application/json" # ✅ 꼭 필요!
}
# ✅ 참가자 명단 로드
df = pd.read_csv("participants.csv") # name, academy, phone, participant_id
# ✅ 이미지 업로드 함수 (HMAC 인증)
def upload_image(filepath):
mime_type = mimetypes.guess_type(filepath)[0]
with open(filepath, "rb") as f:
file_data = f.read()
encoded = base64.b64encode(file_data).decode("utf-8")
upload_data = {
"file": encoded,
"name": os.path.basename(filepath),
"type": "image",
"mime": mime_type
}
res = requests.post(
"https://api.solapi.com/storage/v1/files",
json=upload_data,
headers=make_hmac_headers()
)
res = requests.get(
"https://api.solapi.com/storage/v1/files",
headers=get_basic_auth_header() # 또는 make_hmac_headers()
)
print(res.status_code, res.text)
if res.status_code == 200:
return res.json()["fileId"]
else:
print("❌ 이미지 업로드 실패:", res.text)
return None
# ✅ 문자(MMS) 전송 함수 (Basic 인증)
def send_mms(to, name, academy, image_id):
message = {
"message": {
"to": to,
"from": SENDER,
"type": "MMS",
"subject": f"{academy} 행사 안내",
"text": f"{name} 원장님, 아래 QR 이미지를 확인해주세요!",
"imageId": image_id
}
}
res = requests.post(
"https://api.solapi.com/messages/v4/send",
json=message,
headers=get_basic_auth_header()
)
if res.status_code == 200:
print(f"✅ {name}님 문자 전송 완료")
else:
print(f"❌ {name}님 전송 실패: {res.text}")
# ✅ 참가자 순회하며 자동 처리
for _, row in df.iterrows():
name = row['name']
phone = row['phone']
academy = row['academy']
pid = row['participant_id']
image_path = f"./qrcodes/{name}_{pid}.png"
image_id = upload_image(image_path)
if image_id:
send_mms(phone, name, academy, image_id)시도한 해결 방법No response 기대하는 결과이미지형태로 문자가 발송되어야합니다 확인사항
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
안녕하세요, 솔라피 기술지원팀입니다. 솔라피 개발연동은 반드시 HMAC-256 방식으로 진행해주셔야 합니다. 관련한 사항은 개발연동 문서 에서도 확인하실 수 있습니다. 솔라피에서는 파이썬에서도 개발연동을 편하게 하실 수 있도록 pip 패키지 형식의 sdk를 제공해드리고 있습니다. 아래 링크를 참고하시면 예제와 더불어 파일업로드도 쉽게 구현하실 수 있으니 관련하여 참고해주시면 감사드리겠습니다. |
Beta Was this translation helpful? Give feedback.
-
|
HMAC-SHA256 방식으로 파일 업로드를 구현하고 있으며, 인증은 아래 공식 문서를 참고하고 있습니다: 또한 headers에 다음과 같이 Authorization 값을 포함하고 있으며, Signature는 정상적으로 생성되고 있습니다. 하지만 파일 업로드 시 다음과 같은 오류가 반복되고 있습니다: 이미 다양한 조합으로 확인했으며, 다른 사용자들의 인증 코드 예제도 참고하였습니다. 현재 테스트 중인 API_KEY: NCSBMLJ6DWGBKSFS 입니다. 답변 부탁드립니다. 감사합니다. |
Beta Was this translation helpful? Give feedback.
#17 에서 문의를 올려주신 사항을 토대로 확인했을 때, date에서 문제가 발생했을 것으로 보입니다. 보내주신 코드에서는 date 포맷이 UTC 형식을 따르고 있지 않아서, 관련한 문제가 있을 것으로 추측되며, 아래 실제 SDK 내 인증 구현방식이 담긴 코드 링크를 통해 관련한 코드 참고하셔서 진행 부탁드립니다. 당연히 API Secret Key는 문의를 위해 의도적으로 지우셨겠지만 실제 발송 시 API Secret Key도 누락이 없었는지도 확인해주시면 감사드리겠습니다.
https://github.com/solapi/solapi-python/blob/ee40449389dd31d0030f4bfcf62f0cf58726a946/solapi/lib/authenticator.py#L14-L42
번외로, 앞서 안내드렸듯이 SOLAPI Python SDK MMS 예제를 참고하여 SOLAPI Python SDK를 사용하시면 매우 간편하게 연동하실 수 있는점도 다시 안내드립니다.