안녕하세요 현재 모든 것이 다 작동되는데 NCP SENS로 알림톡 안내문 작성시 치환 오류가 생겨요.
알림톡 전송이 성공을 하면 변수가 하나도 수정이 안된
#{학생이름} 학생이........ 👏 ▶ 교재명: #{교재명} ▶ 교재비: #{교재비}원 입금 시 '#{학생이름}교재비'로 보내주시면 빠르게 확인됩니다. 감사합니다.`;
네이버 프레임에 있는 그대로만 전송이 되고
그래서 다시 치환을 해달라고 제미나이, 끌로드,에 요청한 걸 넣으면 발송 완료라고 뜨지만.
발송이 되지 않아요.
혹시나 해서 네이버에 문의 했더니,
function sendKakaoTalk(recipientName, recipientPhone, bookTitle, bookPrice) {
const properties = PropertiesService.getScriptProperties();
const accessKey = properties.getProperty('NCP_ACCESS_KEY');
const secretKey = properties.getProperty('NCP_SECRET_KEY');
const message = makeSignature(accessKey, secretKey);
const headers = {
"Content-Type": "application/json; charset=utf-8",
"x-ncp-apigw-timestamp": message.timestamp,
"x-ncp-iam-access-key": accessKey,
"x-ncp-apigw-signature-v2": message.signature,
};
const body = {
"templateCode": SENS_TEMPLATE_CODE,
"plusFriendId": SENS_PLUS_FRIEND_ID,
"messages": [
{
"to": recipientPhone.replace(/-/g, "").replace(/\s/g, ""),
"templateValues": {
"학생이름": recipientName,
"교재명": bookTitle,
"교재비": bookPrice.toLocaleString('ko-KR')
}
}
]
};
const options = {
method: "POST",
headers: headers,
payload: JSON.stringify(body),
muteHttpExceptions: true,
};
try {
Logger.log("=== 알림톡 발송 시작 ===");
Logger.log("수신자: " + recipientName + " (" + recipientPhone + ")");
Logger.log("교재: " + bookTitle + " (가격: " + bookPrice + ")");
const response = UrlFetchApp.fetch(`https://sens.apigw.ntruss.com/alimtalk/v2/services/${SENS_SERVICE_ID}/messages`, options);
const responseText = response.getContentText();
Logger.log("알림톡 발송 응답: " + responseText);
// 응답 상태 확인
const responseJson = JSON.parse(responseText);
if (response.getResponseCode() !== 202) {
Logger.log("알림톡 발송 실패 - HTTP 상태: " + response.getResponseCode());
Logger.log("오류 내용: " + responseText);
} else {
Logger.log("알림톡 API 호출 성공 - 처리 중");
}
return responseJson;
} catch (e) {
Logger.log("알림톡 발송 오류: " + e.toString());
return null;
}
}
function makeSignature(accessKey, secretKey) {
const space = " ";
const newLine = "\n";
const method = "POST";
const url = /alimtalk/v2/services/${SENS_SERVICE_ID}/messages;
const timestamp = Date.now().toString();
const hmac = Utilities.computeHmacSignature(
Utilities.MacAlgorithm.HMAC_SHA_256,
method + space + url + newLine + timestamp + newLine + accessKey,
secretKey
);
const signature = Utilities.base64Encode(hmac);
return {
signature: signature,
timestamp: timestamp,
};
}
이 코드를 써서 개인맞춤화 된 메세지르 보내고 싶은데 자꾸 실패가 뜹니다!@
어떻게 해야 하나요? 외부에서 자료를 넣으면 여기에 개인 학생이름이 안 오고 그냥 [학생이름] 이렇게 와요.
답변 내용
안녕하세요, 네이버 클라우드 플랫폼입니다.
안타깝지만, 코드 리뷰는 진행하지 않는 점 양해 부탁드립니다.
다만, 해당 코드로 알림톡을 정상 발송하신 것으로 보입니다.
해당 코드 내에서 #{학생이름}, #{교재명}, #{교재비)에 대해 치환하는 코드가 보이지 않는 것 같습니다.
관련하여 해당 부분 코드를 점검해 보시기 바라며, 추가적인 도움을 드리지 못하는 점 양해 부탁드립니다.
감사합니다.
그래서 아래와 같이 치환하면 또 안되여요....ㅠㅠ
도대체 어디를 고쳐야 하는걸까요? 비개발자 코딩 지식 1도 없는 문과생은 절대 고칠 수 없는 부분일까요?? ^^;; 도와 주세요~~~^^!
NCP SENS 알림톡 발송 관련 함수
//================================================================================
function sendKakaoTalk(recipientName, recipientPhone, bookTitle, bookPrice) {
try {
const properties = PropertiesService.getScriptProperties();
const accessKey = properties.getProperty('NCP_ACCESS_KEY');
const secretKey = properties.getProperty('NCP_SECRET_KEY');
if (!accessKey || !secretKey) {
console.error('NCP API 키가 설정되지 않았습니다.');
return null;
}
const message = makeSignature(accessKey, secretKey);
const headers = {
"Content-Type": "application/json; charset=utf-8",
"x-ncp-apigw-timestamp": message.timestamp,
"x-ncp-iam-access-key": accessKey,
"x-ncp-apigw-signature-v2": message.signature,
};
// 템플릿 내용을 직접 정의하고 변수 치환
let messageContent = `#{학생이름} 학부모님 안녕하세요!
#{학생이름} ....👏
▶ 교재명: #{교재명}
▶ 교재비: #{교재비}원
입금 시 '#{학생이름}교재비'로 보내주시면 빠르게 확인됩니다.
감사합니다.`;
// 실제 값으로 치환
messageContent = messageContent.replace(/#{학생이름}/g, recipientName);
messageContent = messageContent.replace(/#{교재명}/g, bookTitle);
messageContent = messageContent.replace(/#{교재비}/g, bookPrice.toLocaleString('ko-KR'));
const body = {
"templateCode": SENS_TEMPLATE_CODE,
"plusFriendId": SENS_PLUS_FRIEND_ID,
"messages": [
{
"to": recipientPhone.replace(/-/g, "").replace(/\s/g, ""),
"content": messageContent
}
]
};
const options = {
method: "POST",
headers: headers,
payload: JSON.stringify(body),
muteHttpExceptions: true,
};
console.log("=== 알림톡 발송 시작 ===");
console.log("수신자: " + recipientName + " (" + recipientPhone + ")");
console.log("교재: " + bookTitle + " (가격: " + bookPrice + ")");
const response = UrlFetchApp.fetch(`https://sens.apigw.ntruss.com/alimtalk/v2/services/${SENS_SERVICE_ID}/messages`, options);
const responseText = response.getContentText();
console.log("알림톡 발송 응답: " + responseText);
// 응답 상태 확인
const responseJson = JSON.parse(responseText);
if (response.getResponseCode() !== 202) {
console.error("알림톡 발송 실패 - HTTP 상태: " + response.getResponseCode());
console.error("오류 내용: " + responseText);
return null;
} else {
console.log("알림톡 API 호출 성공 - 처리 중");
return responseJson;
}
} catch (error) {
console.error("알림톡 발송 오류: " + error.toString());
return null;
}
}
function makeSignature(accessKey, secretKey) {
const space = " ";
const newLine = "\n";
const method = "POST";
const url = `/alimtalk/v2/services/${SENS_SERVICE_ID}/messages`;
const timestamp = Date.now().toString();
const hmac = Utilities.computeHmacSignature(
Utilities.MacAlgorithm.HMAC_SHA_256,
method + space + url + newLine + timestamp + newLine + accessKey,
secretKey
);
const signature = Utilities.base64Encode(hmac);
return {
signature: signature,
timestamp: timestamp,
};
}