접속·공통 인증
운영 Base URL: https://<운영 도메인>/api/v1. 예제의 pay.example.com은 자리표시자입니다. 현재 로컬 주소는 http://127.0.0.1:3000/api/v1입니다. 개발 연동 서버는 https://qwer8.site/api/v1이며, 실서버는 별도로 배포합니다. 개발 서버도 TRON Mainnet에 연결됩니다.
첫 호출: 접속과 인증 확인
파트너 서버의 Bash 터미널에서 실행합니다. 아래 URL과 API 키를 발급받은 값으로 교체하면 파트너 지갑 잔액 조회 결과를 받습니다. 응답 전체는 파트너 지갑 잔액 조회에서 확인할 수 있습니다.
curl --request GET 'https://pay.example.com/api/v1/balance' \
--header 'x-api-key: <파트너 API 키>'| 필드 | 타입 | 필수 | 설명 | 예시 |
|---|---|---|---|---|
x-api-key | string | 필수 | 운영자가 발급한 활성 파트너 API 키입니다. 파트너 서버에서 보내며 관리자 키·포털 쿠키·Bearer 토큰은 사용하지 않습니다. | <파트너 API 키> |
Content-Type | string | 선택 | JSON 본문이 있을 때 사용합니다. | application/json |
회원 입금주소에 들어온 코인을 파트너 지갑으로 모으는 작업은 파트너 포털의 회원 돈 모으기(TRON)와 다른 네트워크 회원 돈 모으기(이더리움·BNB 스마트 체인·폴리곤·솔라나·비트코인 계열)에서 자기 회원을 대상으로 실행합니다. 포털의 돈 모으기 경로는 /api/v1 밖에 있습니다. 운영자 전체 조회·복구는 기존 관리자 돈 모으기 API를 사용하며, 관리자 키를 파트너 연동 서버에 배포하지 않습니다.
- 운영자가 켜면 이더리움·BNB 스마트 체인·폴리곤의 코인도 입금·돈 모으기·보내기를 지원합니다. 회원마다 0x 주소 하나를 세 네트워크에서 함께 씁니다. 지원 목록은 <지원 코인과 네트워크>를 참고하세요.
- 같은 TRON Mainnet 주소로 USDT(TRC-20)와 TRX의 입금·돈 모으기·보내기를 지원합니다. 보내기 전에 예상 수수료를 조회하세요. 수수료 정보를 사용하면 TRX는 입력한 총액에서 수수료용 TRX를 뺀 만큼 보내고, USDT는 입력한 수량을 그대로 보내며 수수료용 TRX를 따로 확보합니다.
- 요청 금액은 소수 문자열을 권장합니다. 최대 6자리이며 응답 금액도 문자열입니다. 날짜는 UTC ISO 8601, 값이 없을 때는 null입니다.
- 코인·네트워크별 장부를 분리합니다. 거래 조회 기본값은 USDT(모든 네트워크)이므로 TRX·USDC를 포함하려면 asset=all을 지정하세요. TRX의 USDT 환산액은 fresh 환율에 따른 참고 표시이며 자동 환전하지 않습니다.
- 파트너 서버가 회원 잔액·보내기 권한을 관리합니다. COINPG는 파트너 지갑 전체 잔액에서 보냅니다.
- 아래 성공 JSON은 실제 응답 필드를 모두 포함한 형식 예시입니다. 키·주소·ID·시간은 예시 값으로 바꿔 표시했습니다.
받은 값을 다음 작업에 연결하기
| 작업 | 호출·확인 | 저장하거나 처리할 값 |
|---|---|---|
| 회원 입금주소 발급 | PUT /users/{externalUserId} | externalUserId는 파트너의 회원 ID입니다. 응답의 deposit_address를 해당 회원과 연결해 저장하고 회원에게 안내합니다. 여러 코인·네트워크를 받는다면 deposit_addresses의 코인 → 네트워크 → 주소 순서로 안내합니다. |
| 회원 입금 반영 | GET /transactions?asset=all | 회원이 입금한 뒤 type=deposit, status=confirmed 거래의 external_user_id로 회원을 찾고 id로 중복을 막아 asset·network별 장부에 amount를 한 번 반영합니다. |
| 회원 입금주소에서 파트너 지갑으로 돈 모으기 | 파트너 포털 회원 돈 모으기 다른 네트워크 회원 돈 모으기 | 자기 회원과 USDT 또는 TRX를 선택하고 1. 모을 금액 확인 후 2. 돈 모으기로 실행합니다. 다른 네트워크는 같은 순서로 network와 asset을 지정합니다. 관리자 키 없이 사용할 수 있으며, 돈 모으기가 status=confirmed 상태가 된 뒤 파트너 지갑 잔액에 반영됩니다. |
| 예상 수수료·수신량 확인 | POST /payout-quotes | 회원·주소·자산·금액으로 예상 수수료를 조회합니다. recipient_amount와 수수료를 표시하고 30초의 만료 시각 전에 확인합니다. 예상 수수료 조회만으로는 송금하지 않습니다. |
| 회원에게 보내기 요청 | POST /payouts | 주문·quote_id를 포함한 원래 본문·Idempotency-Key를 먼저 저장하고 호출합니다. 받은 보내기 id를 주문에 저장합니다. HTTP 202는 접수이며 보내기 완료가 아닙니다. |
| 보내기 결과 확정 | GET /payouts/{id} | 저장한 보내기 id로 조회합니다. status=confirmed면 완료, failed면 실패로 처리합니다. 결과가 불명확한 요청은 같은 본문·멱등 키로 재확인합니다. |
오류 응답 형식
| 필드 | 타입 | 설명 |
|---|---|---|
error | string | 사람이 읽을 오류 설명. 한국어 또는 영어이므로 문구 대신 HTTP 상태와 code로 분기합니다. |
code | string | 오류 식별자. 각 API의 오류 표를 참고합니다. |
{
"error": "파트너 인증이 필요합니다.",
"code": "USER_REQUEST_FAILED"
}Node.js 공통 클라이언트 코드
아래 코드를 merchant-api-client.mjs로 저장합니다. Node.js 22.18 이상에서 추가 패키지 없이 사용합니다.
// Node.js 22.18+. Importing this file makes no requests and starts no payouts.
export class CoinpgApiError extends Error {
constructor(status, code, message) {
super(message);
this.name = "CoinpgApiError";
this.status = status;
this.code = code;
}
}
export class CoinpgClient {
constructor({ baseUrl, apiKey, timeoutMs = 15_000 }) {
if (!baseUrl || !apiKey) throw new Error("COINPG Base URL and merchant API key are required.");
const url = new URL(baseUrl);
const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
if ((url.protocol !== "https:" && !(local && url.protocol === "http:")) ||
url.username || url.password || url.search || url.hash ||
url.pathname.replace(/\/$/u, "") !== "/api/v1") {
throw new Error("Use an HTTPS Base URL ending in /api/v1 (HTTP is allowed on loopback).");
}
this.baseUrl = url.href.replace(/\/$/u, "");
this.apiKey = apiKey;
this.timeoutMs = timeoutMs;
}
async request(path, { method = "GET", body, idempotencyKey } = {}) {
if (!path.startsWith("/") || path.startsWith("//")) throw new Error("Use a relative API path.");
const response = await fetch(`${this.baseUrl}${path}`, {
method,
headers: {
"x-api-key": this.apiKey,
...(body !== undefined ? { "content-type": "application/json" } : {}),
...(idempotencyKey ? { "idempotency-key": idempotencyKey } : {}),
},
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
redirect: "error",
signal: AbortSignal.timeout(this.timeoutMs),
});
let payload;
try { payload = await response.json(); }
catch {
throw new CoinpgApiError(response.status, "INVALID_RESPONSE", "API response is not JSON; reconcile the original request.");
}
if (!response.ok) {
throw new CoinpgApiError(response.status, payload?.code ?? "HTTP_ERROR", payload?.error ?? "API request failed.");
}
return payload;
}
getBalance() { return this.request("/balance"); }
getExchangeRates() { return this.request("/exchange-rates"); }
getUser(externalUserId) { return this.request(`/users/${encodeURIComponent(externalUserId)}`); }
createOrGetUser(externalUserId, displayName) {
return this.request(`/users/${encodeURIComponent(externalUserId)}`, {
method: "PUT", body: displayName === undefined ? {} : { display_name: displayName },
});
}
listTransactions({ userId, asset, limit, cursor } = {}) {
const query = new URLSearchParams();
if (userId !== undefined) query.set("user_id", userId);
if (asset !== undefined) query.set("asset", asset);
if (limit !== undefined) query.set("limit", String(limit));
if (cursor !== undefined && cursor !== null) query.set("cursor", cursor);
return this.request(`/transactions${query.size ? `?${query}` : ""}`);
}
quotePayout(body) {
// Estimates only: no signing, transfer, or funds reservation.
// Display quote.recipient_amount and fees; accept before quote.expires_at.
return this.request("/payout-quotes", { method: "POST", body });
}
requestPayout(body, idempotencyKey) {
// With quote_id, amount must match the original quote.requested_amount.
// Without quote_id, amount remains the exact recipient quantity.
// Reuse the persisted body (including quote_id and asset) and key after an ambiguous response.
if (!idempotencyKey) throw new Error("Persist the payout idempotency key before calling requestPayout.");
if (body?.asset !== undefined && !["USDT", "TRX"].includes(body.asset)) {
throw new Error("Payout asset must be USDT or TRX.");
}
return this.request("/payouts", { method: "POST", body, idempotencyKey });
}
getPayout(payoutId) { return this.request(`/payouts/${encodeURIComponent(payoutId)}`); }
}
export COINPG_API_BASE_URL='https://pay.example.com/api/v1'
export COINPG_API_KEY='<파트너 API 키>'각 항목의 Node.js 호출 예제는 아래 coinpg 인스턴스를 사용합니다.
import { CoinpgClient } from './merchant-api-client.mjs';
const coinpg = new CoinpgClient({
baseUrl: process.env.COINPG_API_BASE_URL,
apiKey: process.env.COINPG_API_KEY,
});