API 연동
포털 빠른 시작
문의하기 버튼 하나를 복붙으로 5분 안에 연결합니다.
문의하기 버튼 하나를 연결하는 전체 흐름을 따라 합니다. 화면을 직접 만들 필요 없이, 파트너 서버에 CS_API_KEY를 두고 브라우저에서 팝업만 열면 됩니다.
1. API 키를 서버 환경변수에 저장#
CS_API_KEY는 파트너 서버의 환경변수에만 둡니다. 로컬 개발 중이면 프로젝트 최상위 폴더의 .env(Next.js면 .env.local)에 추가하고, 이 파일은 절대 git에 커밋하지 않습니다(.gitignore에 .env* 포함 여부 확인). 실제 운영 서버에 올릴 때는 파일에 적는 게 아니라 배포 방식에 맞는 환경변수/시크릿 설정 화면에 등록합니다.
| 배포 방식 | 넣는 곳 |
|---|---|
| Vercel | 프로젝트 Settings → Environment Variables |
| Docker(직접 서버 운영) | docker-compose.yml의 environment: 항목, 또는 서버의 .env 파일을 컨테이너가 읽게 마운트 |
| GitHub Actions로 CI/CD 배포 | 리포지토리 Settings → Secrets and variables → Actions에 등록 후, 배포 워크플로우에서 컨테이너로 주입 |
| 그 외 일반 호스팅(PM2 등) | 서버에 직접 .env 파일 생성, 또는 PM2 ecosystem 설정의 env 항목 |
2. 토큰 발급 요청 형식 확인#
이 단계에서 실제로 호출하는 건 POST /launch-tokens 하나입니다. 어떤 요청을 보내고 뭐가 돌아오는지 먼저 봅니다.
{
"context": {
"customerId": "user_1234",
"name": "홍길동",
"email": "hong@example.com",
"phone": "010-1234-5678"
}
}{
"success": true,
"item": {
"token": "a1b2c3d4e5f6...",
"url": "https://<도메인>/portal/exchange?token=a1b2c3d4e5f6...",
"expiresAt": "2026-09-28T00:02:00.000Z"
}
}item.url이 다음 단계에서 팝업에 넣을 주소입니다.
3. 서버에 토큰 발급 엔드포인트 만들기#
브라우저가 직접 API 키를 쓰지 않고, 이 엔드포인트를 거치게 하기 위한 것입니다. 그대로 복붙해서 씁니다.
// app/api/cs/launch/route.ts (파트너 서버)
const CS_BASE_URL = process.env.CS_BASE_URL!; // https://<도메인>/api/v1
const CS_API_KEY = process.env.CS_API_KEY!; // sk_live_... (서버 전용)
export async function POST(request: Request) {
const user = await getCurrentUser(request); // 파트너의 로그인 사용자
if (!user) return Response.json({ message: "로그인이 필요합니다" }, { status: 401 });
const res = await fetch(`${CS_BASE_URL}/launch-tokens`, {
method: "POST",
headers: {
"X-API-Key": CS_API_KEY,
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify({
context: { customerId: user.id, name: user.name, email: user.email },
}),
cache: "no-store",
});
const result = await res.json();
if (!result.success) return Response.json({ message: result.error.message }, { status: 502 });
return Response.json({ url: result.item.url });
}4. 프론트엔드에 훅 추가#
훅(useCsInquiry)이 팝업 열기·결과 수신·창 닫힘 감지·팝업 차단 감지를 전부 처리하므로 이건 그대로 복붙해서 쓴다(로직이라 서비스마다 달라질 이유가 없음).
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
const CS_ORIGIN = "https://<도메인>"; // 연동 대상 origin으로 교체
const POPUP_NAME = "cs-inquiry-myservice"; // 쓰는 서비스 이름으로 교체(고정값)
const SUBMITTED_TYPE = "cs-portal:submitted";
const LAUNCH_ENDPOINT = "/api/cs/launch";
export type CsSubmittedIssue = {
id: string;
issueNum: number;
title: string;
body: string;
category: string;
priority: string;
status: string;
channel: string;
requesterName: string;
requesterEmail: string;
requesterPhone: string | null;
replyChannel: "이메일" | "문자" | null;
customerId: string | null;
createdAt: string;
};
type UseCsInquiryOptions = {
onSubmitted?: (issue: CsSubmittedIssue) => void;
onClosed?: () => void; // 접수 없이 창이 닫힌 경우
onError?: (message: string) => void;
};
export function useCsInquiry({ onSubmitted, onClosed, onError }: UseCsInquiryOptions = {}) {
const [isOpening, setIsOpening] = useState(false);
const [isBlocked, setIsBlocked] = useState(false); // 팝업 차단 감지 여부
const submittedRef = useRef(false);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const stopPolling = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
}, []);
// 결과 수신 - 마운트 시점에 등록해 타이밍 문제를 없앤다
useEffect(() => {
function handleMessage(event: MessageEvent) {
if (event.origin !== CS_ORIGIN) return;
if (event.data?.type !== SUBMITTED_TYPE) return;
submittedRef.current = true;
stopPolling();
onSubmitted?.(event.data.issue);
}
window.addEventListener("message", handleMessage);
return () => window.removeEventListener("message", handleMessage);
}, [onSubmitted, stopPolling]);
useEffect(() => stopPolling, [stopPolling]);
const open = useCallback(async () => {
submittedRef.current = false;
setIsBlocked(false);
// 클릭 직후 빈 창부터 연다
const popup = window.open("about:blank", POPUP_NAME, "width=480,height=860");
// 차단됐으면 여기서 중단한다 - 토큰을 요청하지 않는다(2분 만료라 낭비)
if (!popup) {
setIsBlocked(true);
return;
}
setIsOpening(true);
try {
const res = await fetch(LAUNCH_ENDPOINT, { method: "POST" });
const data = await res.json();
if (!res.ok) throw new Error(data.message ?? "문의 창을 열지 못했습니다");
popup.location.href = data.url;
} catch (e) {
popup.close();
onError?.(e instanceof Error ? e.message : "문의 창을 열지 못했습니다");
return;
} finally {
setIsOpening(false);
}
// 접수 없이 닫히는 경우 감지 (닫힘 이벤트가 없어 폴링)
stopPolling();
pollRef.current = setInterval(() => {
if (popup.closed) {
stopPolling();
if (!submittedRef.current) onClosed?.();
}
}, 500);
}, [onClosed, onError, stopPolling]);
return { open, isOpening, isBlocked };
}5. 버튼에 연결#
버튼 쪽은 실제 디자인이 서비스마다 다르므로 동작 방식만 보여주는 최소 예시입니다 - open/isOpening/isBlocked 세 가지를 쓰는 버튼 컴포넌트에 맞게 연결하면 됩니다.
"use client";
import { useCsInquiry } from "@/hooks/use-cs-inquiry";
export function InquiryButton() {
const { open, isOpening, isBlocked } = useCsInquiry({
onSubmitted: async (issue) => {
// 접수 내용 전체가 넘어온다 - 그대로 DB에 저장하면 된다 (아래 경로는 내 서버에 직접 만드는 저장용 엔드포인트, 경로는 임의)
await fetch("/api/cs/link", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(issue),
});
},
onClosed: () => console.log("접수하지 않고 창을 닫음"),
onError: (message) => alert(message),
});
return (
<>
<button type="button" onClick={open} disabled={isOpening}>
{isOpening ? "여는 중..." : "문의하기"}
</button>
{isBlocked && (
<div role="alert">
<p>팝업이 차단되어 문의 창을 열지 못했습니다.</p>
<p>주소창의 차단 아이콘을 눌러 허용한 뒤, 아래 버튼을 눌러주세요.</p>
<button type="button" onClick={open}>다시 시도</button>
</div>
)}
</>
);
}팝업 차단을 피하는 순서
- 클릭 직후 빈 창부터 열고, 토큰을 받은 뒤 주소를 바꿉니다. 토큰을 기다렸다가 창을 열면 브라우저가 차단합니다(위 훅에 이미 반영되어 있어 직접 손대지 않는 한 신경 쓸 필요 없음).
- 창 이름은 고정값을 씁니다.
_blank를 쓰면 창이 계속 쌓이고 부모 창 연결이 끊겨 결과를 못 받습니다.
다음 단계
- 세션 수명, 에러 코드, 결과 수신 도메인 제한 같은 상세 규격은 포털 연동
- 담당자 답변은 이 경로로 오지 않습니다 - 고객이 팝업의 접수 내역 화면에서 직접 확인합니다.
직접 해보기
API 테스트 콘솔의 포털 영역에서 토큰 발급, 팝업 열기, 결과 메시지 수신까지 실제로 확인할 수 있습니다.