d3ro-voice/server/supabase/functions/_shared/payple.ts
윤찬 c9baf031c9 feat(server+web+desktop): Phase 3.2-B Payple 결제 연동 + 대시보드 Premium 상태 표시
Payple PG 연동:
- _shared/payple.ts: Payple API 래퍼 (auth/billing/cancel/deleteBillingKey)
- payple-checkout Edge Function: 빌링키 결제 + 구독 활성화
- payple-webhook Edge Function: 결제완료/취소 이벤트
- payple-manage Edge Function: 구독 취소 (빌링키 해지)
- DB migration: payment_provider + payple_payer_id + payple_pay_oid
- 웹 billing 페이지: Payple JS SDK 결제창 + 관리 버튼 (Stripe 대체)
- Electron LicenseModal: shell.openExternal → 웹 결제 페이지

대시보드 Premium 상태:
- CrtDisplay services에 PREMIUM LLM LED 추가
- 백엔드 인디케이터 카드 (Local/Premium) + 티어 카드
- 사용량 섹션: 전 티어 표시 + 모델별 Premium 쿼터
- 12개 locale × 14개 i18n 키
2026-04-12 19:18:40 +09:00

281 lines
8.9 KiB
TypeScript

// server/supabase/functions/_shared/payple.ts
// Payple 결제 API 래퍼 — 파트너 인증, 빌링 결제, 취소, 빌링키 해지
// ── 타입 ──────────────────────────────────────────────
export interface PaypleConfig {
cstId: string
custKey: string
refundKey: string
clientKey: string
isTest: boolean
baseUrl: string // 'https://cpay.payple.kr' or 'https://democpay.payple.kr'
}
export interface PaypleAuthResult {
PCD_CST_ID: string // 암호화된 상점 ID
PCD_CUST_KEY: string // 암호화된 고객 키
PCD_AUTH_KEY: string // 인증 토큰
PCD_PAY_HOST: string // 결제 요청 호스트
PCD_PAY_URL: string // 결제 요청 URL
}
export interface PaypleBillingResult {
PCD_PAY_RST: 'success' | 'error'
PCD_PAY_CODE: string
PCD_PAY_MSG: string
PCD_PAY_OID: string
PCD_PAY_TYPE: string
PCD_PAY_TOTAL: string
PCD_PAY_CARDNAME?: string
PCD_PAY_CARDNUM?: string
PCD_PAY_CARDAUTHNO?: string
PCD_PAY_CARDTRADENUM?: string
PCD_PAY_CARDRECEIPT?: string
PCD_PAYER_ID?: string
}
export interface PaypleCancelResult {
PCD_PAY_RST: 'success' | 'error'
PCD_PAY_CODE: string
PCD_PAY_MSG: string
PCD_PAY_OID: string
PCD_REFUND_TOTAL: string
}
// ── 환경변수에서 설정 로드 ──────────────────────────────
export function getPaypleConfig(): PaypleConfig {
// @ts-expect-error — Deno.env
const cstId = Deno.env.get('PAYPLE_CST_ID') ?? 'test'
// @ts-expect-error — Deno.env
const custKey = Deno.env.get('PAYPLE_CUST_KEY') ?? 'abcd1234567890'
// @ts-expect-error — Deno.env
const refundKey = Deno.env.get('PAYPLE_REFUND_KEY') ?? 'a41ce010ede9fcbfb3be86b24858806596a9db68b79d138b147c3e563e1829a0'
// @ts-expect-error — Deno.env
const clientKey = Deno.env.get('PAYPLE_CLIENT_KEY') ?? 'test_DF55F29DA654A8CBC0F0A9DD4B556486'
const isTest = cstId === 'test'
const baseUrl = isTest ? 'https://democpay.payple.kr' : 'https://cpay.payple.kr'
return { cstId, custKey, refundKey, clientKey, isTest, baseUrl }
}
// ── Referer 헤더 ──────────────────────────────────────
function getReferer(): string {
// @ts-expect-error — Deno.env
const siteUrl = Deno.env.get('PAYPLE_SITE_URL') ?? Deno.env.get('SITE_URL') ?? 'https://d3ro.dev'
return siteUrl
}
// ── 파트너 인증 ───────────────────────────────────────
export async function paypleAuth(
config: PaypleConfig,
options?: {
cancelFlag?: boolean // PCD_PAYCANCEL_FLAG
simpleFlag?: boolean // PCD_SIMPLE_FLAG (빌링 결제용)
payWork?: string // PCD_PAY_WORK (PUSERDEL 등)
}
): Promise<PaypleAuthResult> {
const body: Record<string, string> = {
cst_id: config.cstId,
custKey: config.custKey,
}
if (options?.cancelFlag) {
body['PCD_PAYCANCEL_FLAG'] = 'Y'
} else if (options?.simpleFlag) {
body['PCD_PAY_TYPE'] = 'card'
body['PCD_SIMPLE_FLAG'] = 'Y'
} else if (options?.payWork) {
body['PCD_PAY_WORK'] = options.payWork
}
const resp = await fetch(`${config.baseUrl}/php/auth.php`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
},
body: JSON.stringify(body),
})
if (!resp.ok) {
throw new Error(`Payple auth failed: HTTP ${resp.status}`)
}
const data = await resp.json() as Record<string, string>
if (data['result'] !== 'success') {
throw new Error(`Payple auth error: ${data['result_msg'] ?? data['cst_id'] ?? 'unknown'}`)
}
return {
PCD_CST_ID: data['cst_id'] ?? '',
PCD_CUST_KEY: data['custKey'] ?? '',
PCD_AUTH_KEY: data['AuthKey'] ?? '',
PCD_PAY_HOST: data['PCD_PAY_HOST'] ?? config.baseUrl,
PCD_PAY_URL: data['PCD_PAY_URL'] ?? '',
}
}
// ── 빌링키로 결제 ────────────────────────────────────
export async function paypleBilling(
config: PaypleConfig,
auth: PaypleAuthResult,
params: {
payerId: string // PCD_PAYER_ID (빌링키)
amount: number // 결제 금액 (원)
orderId: string // 주문번호
goodsName: string // 상품명
}
): Promise<PaypleBillingResult> {
const url = auth.PCD_PAY_HOST
? `${auth.PCD_PAY_HOST}/php/SimplePayCardAct.php?ACT_=PAYM`
: `${config.baseUrl}/php/SimplePayCardAct.php?ACT_=PAYM`
const resp = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
},
body: JSON.stringify({
PCD_CST_ID: auth.PCD_CST_ID,
PCD_CUST_KEY: auth.PCD_CUST_KEY,
PCD_AUTH_KEY: auth.PCD_AUTH_KEY,
PCD_PAY_TYPE: 'card',
PCD_PAYER_ID: params.payerId,
PCD_PAY_GOODS: params.goodsName,
PCD_PAY_TOTAL: String(params.amount),
PCD_PAY_OID: params.orderId,
PCD_SIMPLE_FLAG: 'Y',
}),
})
if (!resp.ok) {
throw new Error(`Payple billing failed: HTTP ${resp.status}`)
}
const data = await resp.json() as PaypleBillingResult
if (data.PCD_PAY_RST !== 'success') {
throw new Error(`Payple billing error: ${data.PCD_PAY_MSG} (${data.PCD_PAY_CODE})`)
}
return data
}
// ── 결제 취소/환불 ────────────────────────────────────
export async function paypleCancel(
config: PaypleConfig,
auth: PaypleAuthResult,
params: {
payOid: string // 원거래 주문번호
payDate: string // 결제일자 (YYYYMMDD)
refundTotal: number // 환불 금액
}
): Promise<PaypleCancelResult> {
const resp = await fetch(`${config.baseUrl}/php/account/api/cPayCAct.php`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
},
body: JSON.stringify({
PCD_CST_ID: auth.PCD_CST_ID,
PCD_CUST_KEY: auth.PCD_CUST_KEY,
PCD_AUTH_KEY: auth.PCD_AUTH_KEY,
PCD_REFUND_KEY: config.refundKey,
PCD_PAYCANCEL_FLAG: 'Y',
PCD_PAY_OID: params.payOid,
PCD_PAY_DATE: params.payDate,
PCD_REFUND_TOTAL: String(params.refundTotal),
}),
})
if (!resp.ok) {
throw new Error(`Payple cancel failed: HTTP ${resp.status}`)
}
const data = await resp.json() as PaypleCancelResult
if (data.PCD_PAY_RST !== 'success') {
throw new Error(`Payple cancel error: ${data.PCD_PAY_MSG} (${data.PCD_PAY_CODE})`)
}
return data
}
// ── 빌링키 해지 ──────────────────────────────────────
export async function paypleDeleteBillingKey(
config: PaypleConfig,
auth: PaypleAuthResult,
payerId: string
): Promise<void> {
const url = auth.PCD_PAY_HOST
? `${auth.PCD_PAY_HOST}/php/cPayUser/api/cPayUserAct.php?ACT_=PUSERDEL`
: `${config.baseUrl}/php/cPayUser/api/cPayUserAct.php?ACT_=PUSERDEL`
const resp = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
},
body: JSON.stringify({
PCD_CST_ID: auth.PCD_CST_ID,
PCD_CUST_KEY: auth.PCD_CUST_KEY,
PCD_AUTH_KEY: auth.PCD_AUTH_KEY,
PCD_PAYER_ID: payerId,
}),
})
if (!resp.ok) {
throw new Error(`Payple delete billing key failed: HTTP ${resp.status}`)
}
const data = await resp.json() as { PCD_PAY_RST: string; PCD_PAY_MSG?: string }
if (data.PCD_PAY_RST !== 'success') {
throw new Error(`Payple delete billing key error: ${data.PCD_PAY_MSG ?? 'unknown'}`)
}
}
// ── 주문번호 생성 유틸리티 ─────────────────────────────
export function generateOrderId(userId: string): string {
const now = new Date()
const ts = now.toISOString().replace(/[-:T.Z]/g, '').substring(0, 14)
const short = userId.substring(0, 8)
return `D3RO-${ts}-${short}`
}
// ── 구독 기간 계산 ────────────────────────────────────
export function calcSubscriptionPeriod(): { start: string; end: string } {
const now = new Date()
const end = new Date(now)
end.setMonth(end.getMonth() + 1)
return {
start: now.toISOString(),
end: end.toISOString(),
}
}
// ── 티어별 가격 ──────────────────────────────────────
export const TIER_PRICE: Record<string, number> = {
pro: 9900,
pro_plus: 29900,
}
export const TIER_GOODS_NAME: Record<string, string> = {
pro: 'D3RO Voice Pro',
pro_plus: 'D3RO Voice Pro+',
}