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 키
This commit is contained in:
윤찬 2026-04-12 19:18:40 +09:00
parent b8cb665264
commit c9baf031c9
27 changed files with 1318 additions and 98 deletions

View file

@ -1,7 +1,7 @@
// src/main/ipc/license-handlers.ts
// Phase 11: 라이센스 IPC 핸들러
import { ipcMain, BrowserWindow } from 'electron'
import { ipcMain, BrowserWindow, shell } from 'electron'
import { IPC_CHANNELS } from '@d3ro/core/ipc-channels'
import { ipcSuccess, ipcError, ErrorCode } from '@d3ro/core/errors'
import { getLicenseService } from '../services/LicenseService'
@ -97,4 +97,16 @@ export function registerLicenseHandlers(): void {
return ipcError(ErrorCode.UnknownError, `Tier comparison failed: ${err}`)
}
})
ipcMain.handle(IPC_CHANNELS.LICENSE.OPEN_BILLING, async (_event, params: { tier: 'pro' | 'pro_plus' }) => {
try {
// Phase 3.2-B: 웹 결제 페이지 열기
// 프로덕션: https://d3ro.dev/billing, 개발: NEXT_PUBLIC_SITE_URL 참조
const billingUrl = `https://d3ro.dev/billing?tier=${params.tier}`
await shell.openExternal(billingUrl)
return ipcSuccess(undefined)
} catch (err) {
return ipcError(ErrorCode.UnknownError, `Failed to open billing: ${err}`)
}
})
}

View file

@ -476,6 +476,8 @@ const electronAPI = {
invoke<UsageQuota[]>(IPC_CHANNELS.LICENSE.GET_ALL_USAGE),
getTierComparison: () =>
invoke<TierComparison[]>(IPC_CHANNELS.LICENSE.GET_TIER_COMPARISON),
openBilling: (params: { tier: 'pro' | 'pro_plus' }) =>
invoke<void>(IPC_CHANNELS.LICENSE.OPEN_BILLING, params),
onUpgradePrompt: (cb: (e: UpgradePromptEvent) => void): Unsubscribe =>
on(IPC_CHANNELS.LICENSE.UPGRADE_PROMPT, cb),
onTierChanged: (cb: (e: LicenseInfo) => void): Unsubscribe =>

View file

@ -83,9 +83,9 @@ export function LicenseModal({ open, onClose }: LicenseModalProps): React.ReactE
const isFree = currentTier === 'free'
const isPro = currentTier === 'pro'
const handleUpgrade = useCallback(() => {
alert(t('license.paymentPending'))
}, [t])
const handleUpgrade = useCallback((tier: 'pro' | 'pro_plus' = 'pro') => {
window.electronAPI.license.openBilling({ tier })
}, [])
return (
<Dialog
@ -141,7 +141,7 @@ export function LicenseModal({ open, onClose }: LicenseModalProps): React.ReactE
{isFree && (
<>
<PhysicalButton onClick={handleUpgrade} sx={{ width: '100%' }}>
<PhysicalButton onClick={() => handleUpgrade('pro')} sx={{ width: '100%' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Led color="green" size={8} />
<PhosphorText variant="compact">
@ -149,7 +149,7 @@ export function LicenseModal({ open, onClose }: LicenseModalProps): React.ReactE
</PhosphorText>
</Box>
</PhysicalButton>
<PhysicalButton onClick={handleUpgrade} sx={{ width: '100%' }}>
<PhysicalButton onClick={() => handleUpgrade('pro_plus')} sx={{ width: '100%' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Led color="green" size={8} />
<PhosphorText variant="compact">
@ -168,7 +168,7 @@ export function LicenseModal({ open, onClose }: LicenseModalProps): React.ReactE
{t('license.currentPlan')} {t('license.proPlan')}
</PhosphorText>
</Box>
<PhysicalButton onClick={handleUpgrade} sx={{ width: '100%' }}>
<PhysicalButton onClick={() => handleUpgrade('pro_plus')} sx={{ width: '100%' }}>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Led color="green" size={8} />
<PhosphorText variant="compact">

View file

@ -13,6 +13,23 @@ import { formatHotkeyLabel } from '../utils/format-hotkey'
import { FileDropZone } from '../components/FileDropZone'
import type { StatsSummary, HistoryEntry, HotkeyBinding, CaptionState, LicenseTier, UsageQuota } from '@d3ro/core/types'
// ── Premium 쿼터 모델별 한도 (서버 quota.ts / LicenseService QUOTA_LIMITS 와 동기) ──
const PREMIUM_MODEL_LIMITS: Record<LicenseTier, Array<{ model: string; i18nKey: string; limit: number; period: 'daily' | 'weekly' }>> = {
free: [
{ model: 'llm_haiku', i18nKey: 'dashboard.modelHaiku', limit: 250, period: 'weekly' },
],
pro: [
{ model: 'llm_haiku', i18nKey: 'dashboard.modelHaiku', limit: 1500, period: 'daily' },
{ model: 'llm_sonnet', i18nKey: 'dashboard.modelSonnet', limit: 300, period: 'daily' },
{ model: 'llm_opus', i18nKey: 'dashboard.modelOpus', limit: 50, period: 'daily' },
],
pro_plus: [
{ model: 'llm_haiku', i18nKey: 'dashboard.modelHaiku', limit: -1, period: 'daily' },
{ model: 'llm_sonnet', i18nKey: 'dashboard.modelSonnet', limit: 1500, period: 'daily' },
{ model: 'llm_opus', i18nKey: 'dashboard.modelOpus', limit: 300, period: 'daily' },
],
}
// ── 메인 컴포넌트 ─────────────────────────────────────
export function DashboardPage(): React.ReactElement {
@ -27,6 +44,7 @@ export function DashboardPage(): React.ReactElement {
const audioDecayRef = useRef<ReturnType<typeof setInterval> | null>(null)
const [licenseTier, setLicenseTier] = useState<LicenseTier>('free')
const [usageQuotas, setUsageQuotas] = useState<UsageQuota[]>([])
const [premiumStatus, setPremiumStatus] = useState<{ available: boolean; backend: 'local' | 'premium' } | null>(null)
const loadData = useCallback(() => {
window.electronAPI.stats.getSummary().then((r) => {
@ -50,6 +68,9 @@ export function DashboardPage(): React.ReactElement {
window.electronAPI.license.getAllUsage().then((r) => {
if (r.success) setUsageQuotas(r.data)
})
window.electronAPI.llm.premium.getStatus().then((r) => {
if (r.success) setPremiumStatus(r.data)
})
}, [])
useEffect(() => {
@ -89,9 +110,14 @@ export function DashboardPage(): React.ReactElement {
const services = useMemo(() => [
{ name: t('service.sttEngine'), status: t('service.ready'), ok: true },
{ name: t('service.ollamaLlm'), status: ollamaConnected ? t('service.connected') : t('service.offline'), ok: ollamaConnected },
{
name: t('service.premiumLlm'),
status: premiumStatus?.available ? t('service.connected') : t('service.notConfigured'),
ok: premiumStatus?.available ?? false,
},
{ name: t('service.hotkeyHook'), status: t('service.active'), ok: true },
{ name: t('service.audioInput'), status: t('service.standby'), ok: true },
], [t, ollamaConnected])
], [t, ollamaConnected, premiumStatus])
return (
<Box sx={{ maxWidth: 900, mx: 'auto', p: 4, pb: 8 }}>
@ -250,8 +276,51 @@ export function DashboardPage(): React.ReactElement {
))}
</Box>
{/* ── 2.4. 사용량 바 (Free 티어) ─────────────── */}
{licenseTier === 'free' && usageQuotas.length > 0 && (
{/* ── 2.4. 백엔드 인디케이터 + 사용량 바 ─────────────── */}
<Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 2, mt: 2 }}>
{/* 현재 백엔드 카드 */}
<MetalCard>
<Box sx={{ px: 1, py: 0.5 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>
{t('dashboard.currentBackend').toUpperCase()}
</PhosphorText>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Led
color={premiumStatus?.backend === 'premium' ? 'green' : 'amber'}
size={8}
pulse={premiumStatus?.backend === 'premium'}
/>
<PhosphorText variant="value">
{premiumStatus?.backend === 'premium'
? t('dashboard.backendPremium').toUpperCase()
: t('dashboard.backendLocal').toUpperCase()}
</PhosphorText>
</Box>
</Box>
</MetalCard>
{/* 티어 카드 */}
<MetalCard>
<Box sx={{ px: 1, py: 0.5 }}>
<PhosphorText variant="label" sx={{ mb: 1, display: 'block' }}>
{t('license.currentTier').toUpperCase()}
</PhosphorText>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Led
color={licenseTier === 'free' ? 'amber' : 'green'}
size={8}
pulse={licenseTier !== 'free'}
/>
<PhosphorText variant="value">
{t(`license.${licenseTier === 'pro_plus' ? 'proPlus' : licenseTier}`).toUpperCase()}
</PhosphorText>
</Box>
</Box>
</MetalCard>
</Box>
{/* 사용량 바 — 모든 티어에서 표시 */}
{usageQuotas.length > 0 && (
<Box sx={{ mt: 2 }}>
<MetalCard>
<Box sx={{ px: 1, py: 0.5 }}>
@ -288,6 +357,45 @@ export function DashboardPage(): React.ReactElement {
)}
</Box>
))}
{/* Premium 모델별 쿼터 표시 */}
{premiumStatus?.backend === 'premium' && PREMIUM_MODEL_LIMITS[licenseTier].length > 0 && (
<>
<PhosphorText variant="label" sx={{ mt: 1.5, mb: 0.5, display: 'block', color: d3roPalette.tag.green }}>
{t('dashboard.premiumQuota').toUpperCase()}
</PhosphorText>
{PREMIUM_MODEL_LIMITS[licenseTier].map((m) => (
<Box key={m.model} sx={{ mb: 1 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.3 }}>
<PhosphorText variant="small">
{t(m.i18nKey)}
</PhosphorText>
<PhosphorText variant="small" sx={{ color: d3roPalette.accent.amber }}>
{m.limit === -1
? t('license.unlimited')
: `${m.limit}/${t(m.period === 'weekly' ? 'dashboard.quotaWeekly' : 'dashboard.quotaDaily')}`}
</PhosphorText>
</Box>
{m.limit > 0 && (
<Box sx={{
height: 3,
borderRadius: '2px',
bgcolor: d3roPalette.bg.inset,
overflow: 'hidden',
}}>
<Box sx={{
height: '100%',
width: '0%',
bgcolor: d3roPalette.tag.green,
borderRadius: '2px',
transition: 'width 0.3s ease',
}} />
</Box>
)}
</Box>
))}
</>
)}
</Box>
</MetalCard>
</Box>

View file

@ -1,15 +1,15 @@
// apps/web/src/app/(app)/billing/page.tsx
// 구독 및 결제 페이지 — auth/Sidebar는 (app)/layout.tsx가 제공
// 구독 및 결제 페이지 — Payple 결제 연동 (Phase 3.2-B)
import { Box, Grid, Stack } from '@mui/material'
import { MetalCard, PhosphorText } from '@d3ro/ui/components/ds'
import { d3roPalette, typoSx } from '@d3ro/ui/theme'
import { CheckoutButton } from '@/components/billing/checkout-button'
import { PortalButton } from '@/components/billing/portal-button'
import { PaypleCheckoutButton } from '@/components/billing/payple-checkout-button'
import { PaypleManageButton } from '@/components/billing/payple-manage-button'
import { getSupabaseServerClient } from '@/lib/supabase-server'
interface Plan {
tier: 'free' | 'pro' | 'team'
tier: 'free' | 'pro' | 'pro_plus'
name: string
price: string
features: string[]
@ -20,40 +20,40 @@ const PLANS: Plan[] = [
{
tier: 'free',
name: 'Free',
price: '$0',
price: '0',
features: [
'월 5시간 전사',
'월 50회 LLM 처리',
'1기기 동기화',
'로컬 모델 (데스크톱)'
]
'로컬 STT/LLM 무제한',
'Haiku 250회/주간',
'히스토리 3일 보존',
],
},
{
tier: 'pro',
name: 'Pro',
price: '$10/월',
price: '₩9,900/월',
highlight: true,
features: [
'무제한 전사',
'무제한 LLM 처리',
'5기기 동기화',
'Sonnet 모델 사용',
'우선 지원'
]
'로컬 STT/LLM 무제한',
'Haiku 1,500회/일',
'Sonnet 300회/일',
'Opus 50회/일',
'히스토리 무제한',
'클라우드 동기화',
],
},
{
tier: 'team',
name: 'Team',
price: '$20/인/월',
tier: 'pro_plus',
name: 'Pro+',
price: '₩29,900/월',
features: [
'Pro 모든 기능',
'무제한 멤버',
'팀 회의 공유',
'관리자 대시보드',
'Opus 모델 사용',
'SSO/SAML (V2-8b)'
]
}
'Haiku 무제한',
'Sonnet 1,500회/일',
'Opus 300회/일',
'팀 협업 (회의 공유)',
'우선 지원',
],
},
]
async function loadCurrentTier(): Promise<string> {
@ -77,10 +77,10 @@ export default async function BillingPage(): Promise<React.ReactElement> {
BILLING
</PhosphorText>
<Box sx={{ color: d3roPalette.text.muted, fontSize: 13 }}>
: <strong>{currentTier.toUpperCase()}</strong>
: <strong>{currentTier === 'pro_plus' ? 'PRO+' : currentTier.toUpperCase()}</strong>
</Box>
</Box>
{currentTier !== 'free' && <PortalButton />}
{currentTier !== 'free' && <PaypleManageButton />}
</Stack>
<Grid container spacing={3}>
@ -96,11 +96,11 @@ export default async function BillingPage(): Promise<React.ReactElement> {
? `2px solid ${d3roPalette.accent.amber}`
: plan.highlight
? `2px solid ${d3roPalette.tag.purple}`
: undefined
: undefined,
}}
>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label, mb: 1 }}>
{plan.tier.toUpperCase()}
{plan.tier === 'pro_plus' ? 'PRO+' : plan.tier.toUpperCase()}
</Box>
<PhosphorText variant="title" sx={{ mb: 1 }}>
{plan.name}
@ -125,7 +125,7 @@ export default async function BillingPage(): Promise<React.ReactElement> {
bgcolor: d3roPalette.bg.inset,
borderRadius: 1,
color: d3roPalette.accent.amber,
...typoSx('label')
...typoSx('label'),
}}
>
@ -135,7 +135,7 @@ export default async function BillingPage(): Promise<React.ReactElement> {
</Box>
) : (
<CheckoutButton tier={plan.tier} />
<PaypleCheckoutButton tier={plan.tier} />
)}
</MetalCard>
</Grid>
@ -144,7 +144,7 @@ export default async function BillingPage(): Promise<React.ReactElement> {
</Grid>
<Box sx={{ mt: 4, color: d3roPalette.text.muted, fontSize: 11 }}>
Stripe로 . .
Payple로 . .
</Box>
</Box>
)

View file

@ -0,0 +1,165 @@
'use client'
// apps/web/src/components/billing/payple-checkout-button.tsx
// Payple 결제창 호출 → 빌링키 획득 → payple-checkout Edge Function 호출
import { useState, useEffect, useCallback } from 'react'
import { Button, CircularProgress, Alert, Box } from '@mui/material'
import Script from 'next/script'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
// Payple JS SDK 타입 (전역 함수)
declare global {
interface Window {
PaypleCpayAuthCheck: (obj: Record<string, unknown>) => void
}
}
interface PaypleCheckoutButtonProps {
tier: 'pro' | 'pro_plus'
}
// 테스트 환경 감지: 환경변수가 없거나 test면 테스트 모드
const PAYPLE_CLIENT_KEY = process.env.NEXT_PUBLIC_PAYPLE_CLIENT_KEY ?? 'test_DF55F29DA654A8CBC0F0A9DD4B556486'
const IS_TEST = PAYPLE_CLIENT_KEY.startsWith('test_')
const SDK_URL = IS_TEST
? 'https://democpay.payple.kr/js/v1/payment.js'
: 'https://cpay.payple.kr/js/v1/payment.js'
export function PaypleCheckoutButton({ tier }: PaypleCheckoutButtonProps): React.ReactElement {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [success, setSuccess] = useState(false)
const [sdkReady, setSdkReady] = useState(false)
// SDK가 이미 로드되어 있는지 확인
useEffect(() => {
if (typeof window !== 'undefined' && typeof window.PaypleCpayAuthCheck === 'function') {
setSdkReady(true)
}
}, [])
const handleCheckout = useCallback(async () => {
setError(null)
setSuccess(false)
if (!sdkReady || typeof window.PaypleCpayAuthCheck !== 'function') {
setError('결제 모듈 로딩 중입니다. 잠시 후 다시 시도해주세요.')
return
}
const supabase = getSupabaseBrowserClient()
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
setError('로그인이 필요합니다')
return
}
setBusy(true)
try {
// Payple 결제창 호출 (SPA 콜백 패턴)
const obj: Record<string, unknown> = {
clientKey: PAYPLE_CLIENT_KEY,
PCD_PAY_TYPE: 'card',
PCD_PAY_WORK: 'AUTH', // 카드 등록만 (빌링키 발급)
PCD_CARD_VER: '01', // 정기결제용
PCD_PAY_GOODS: tier === 'pro_plus' ? 'D3RO Voice Pro+' : 'D3RO Voice Pro',
PCD_PAY_TOTAL: tier === 'pro_plus' ? 29900 : 9900,
PCD_PAYER_NO: session.user.id,
PCD_PAYER_EMAIL: session.user.email ?? '',
PCD_RST_URL: '/billing', // 상대 경로 → callbackFunction 사용
callbackFunction: async (result: Record<string, string>) => {
try {
if (result['PCD_PAY_RST'] !== 'success') {
setError(result['PCD_PAY_MSG'] ?? '결제가 취소되었습니다')
setBusy(false)
return
}
const payerId = result['PCD_PAYER_ID']
if (!payerId) {
setError('빌링키를 받지 못했습니다')
setBusy(false)
return
}
// Edge Function 호출: 빌링키로 첫 결제 실행
const response = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/payple-checkout`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
payer_id: payerId,
tier,
pcd_pay_cardname: result['PCD_PAY_CARDNAME'],
pcd_pay_cardnum: result['PCD_PAY_CARDNUM'],
}),
}
)
if (!response.ok) {
const txt = await response.text()
throw new Error(`결제 처리 실패: ${response.status} ${txt}`)
}
setSuccess(true)
// 2초 후 페이지 리로드하여 구독 상태 반영
setTimeout(() => {
window.location.reload()
}, 2000)
} catch (e) {
setError(e instanceof Error ? e.message : '알 수 없는 오류')
} finally {
setBusy(false)
}
},
}
window.PaypleCpayAuthCheck(obj)
} catch (e) {
setError(e instanceof Error ? e.message : '알 수 없는 오류')
setBusy(false)
}
}, [sdkReady, tier])
return (
<Box>
<Script
src={SDK_URL}
strategy="afterInteractive"
onLoad={() => setSdkReady(true)}
onError={() => setError('결제 모듈 로드 실패')}
/>
{success ? (
<Alert severity="success" variant="filled" sx={{ fontSize: 13 }}>
! .
</Alert>
) : (
<>
<Button
fullWidth
variant="contained"
size="large"
onClick={() => void handleCheckout()}
disabled={busy || !sdkReady}
startIcon={busy ? <CircularProgress size={16} color="inherit" /> : null}
>
{busy ? '처리 중...' : '업그레이드'}
</Button>
{error && (
<Alert severity="error" variant="outlined" sx={{ mt: 1, fontSize: 11 }}>
{error}
</Alert>
)}
</>
)}
</Box>
)
}

View file

@ -0,0 +1,101 @@
'use client'
// apps/web/src/components/billing/payple-manage-button.tsx
// Payple 구독 관리 — payple-manage Edge Function 호출 (구독 취소)
import { useState } from 'react'
import { Button, CircularProgress, Alert, Box, Dialog, DialogTitle, DialogContent, DialogContentText, DialogActions } from '@mui/material'
import SettingsIcon from '@mui/icons-material/Settings'
import { getSupabaseBrowserClient } from '@/lib/supabase-browser'
export function PaypleManageButton(): React.ReactElement {
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [confirmOpen, setConfirmOpen] = useState(false)
const [success, setSuccess] = useState(false)
async function handleCancel(): Promise<void> {
setConfirmOpen(false)
setError(null)
setBusy(true)
try {
const supabase = getSupabaseBrowserClient()
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
setError('로그인이 필요합니다')
return
}
const response = await fetch(
`${process.env.NEXT_PUBLIC_SUPABASE_URL}/functions/v1/payple-manage`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${session.access_token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ action: 'cancel' }),
}
)
if (!response.ok) {
const txt = await response.text()
throw new Error(`구독 취소 실패: ${response.status} ${txt}`)
}
const data = await response.json() as { success?: boolean; cancel_at?: string }
if (data.success) {
setSuccess(true)
setTimeout(() => window.location.reload(), 2000)
}
} catch (e) {
setError(e instanceof Error ? e.message : '알 수 없는 오류')
} finally {
setBusy(false)
}
}
if (success) {
return (
<Alert severity="info" variant="outlined" sx={{ fontSize: 12 }}>
. .
</Alert>
)
}
return (
<Box>
<Button
variant="outlined"
size="small"
startIcon={busy ? <CircularProgress size={14} /> : <SettingsIcon />}
onClick={() => setConfirmOpen(true)}
disabled={busy}
>
</Button>
<Dialog open={confirmOpen} onClose={() => setConfirmOpen(false)}>
<DialogTitle> </DialogTitle>
<DialogContent>
<DialogContentText>
? .
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setConfirmOpen(false)}></Button>
<Button onClick={() => void handleCancel()} color="error" variant="contained">
</Button>
</DialogActions>
</Dialog>
{error && (
<Alert severity="error" variant="outlined" sx={{ mt: 1, fontSize: 11 }}>
{error}
</Alert>
)}
</Box>
)
}

View file

@ -1,8 +1,51 @@
# D3RO-VOICE 프로젝트 현황
> 마지막 갱신: 2026-04-12 (Phase 3.2 Premium LLM 완결 — 빅뱅 8/8 달성)
> 마지막 갱신: 2026-04-12 (Phase 3.2-B Payple 결제 연동 + 대시보드 Premium 표시)
> 규칙 13: 작업 완료 즉시 이 파일 갱신 의무
## Phase 3.2-B Payple 결제 연동 + 대시보드 Premium 상태 (2026-04-12) ✅
### A. Payple 결제 연동
Stripe 기반 결제를 Payple(한국 PG)로 전면 교체. 웹(apps/web) 결제 페이지가 핵심.
**신규 파일:**
- `server/supabase/functions/_shared/payple.ts` — Payple API 래퍼 (auth, billing, cancel, deleteBillingKey)
- `server/supabase/functions/payple-checkout/index.ts` — 빌링키로 첫 결제 + 구독 활성화
- `server/supabase/functions/payple-webhook/index.ts` — 결제완료/취소 이벤트 처리
- `server/supabase/functions/payple-manage/index.ts` — 구독 취소 (빌링키 해지)
- `server/supabase/migrations/20260412000002_payple_billing.sql` — payment_provider, payple_payer_id, payple_pay_oid 컬럼
- `apps/web/src/components/billing/payple-checkout-button.tsx` — Payple JS SDK 결제창 호출
- `apps/web/src/components/billing/payple-manage-button.tsx` — 구독 관리/취소 다이얼로그
**수정 파일:**
- `apps/web/src/app/(app)/billing/page.tsx` — 티어 통일(team→pro_plus) + Payple 컴포넌트로 교체
- `apps/desktop/src/renderer/components/LicenseModal.tsx` — 업그레이드 → shell.openExternal(웹 결제)
- `packages/core/src/ipc-channels.ts` — LICENSE.OPEN_BILLING 추가
- `apps/desktop/src/preload/index.ts` — license.openBilling() API
- `apps/desktop/src/main/ipc/license-handlers.ts` — OPEN_BILLING 핸들러
- `server/supabase/config.toml` — payple-* verify_jwt=false
### B. 대시보드 Premium 상태 표시
- DashboardPage services 배열에 PREMIUM LLM LED 추가 → CrtDisplay 자동 렌더
- 백엔드 인디케이터 카드(Local/Premium) + 티어 카드
- 사용량 바: 모든 티어에서 표시 + Premium 모델별(Haiku/Sonnet/Opus) 쿼터 섹션
### i18n
12개 locale에 14개 키 추가 (service.premiumLlm, dashboard.currentBackend 등)
### 알려진 이슈 (이월)
1. **세션 만료 렌더러 미동기화** — 기존 이슈
2. **LemonSqueezy 코드 잔존** — LicenseService.ts에 @deprecated 코드. 다음 사이클에서 정리
3. **Payple 테스트 키** — 라이브 전환 시 PAYPLE_CST_ID/CUST_KEY/REFUND_KEY/CLIENT_KEY Supabase Secrets 등록 필요
4. **Payple 정기 갱신 크론** — payple-renew 미구현. pg_cron 또는 외부 스케줄러 필요
### 백로그
- **관리자 백엔드 서비스 웹페이지**: 사용자 관리 CRM, 구독 현황 대시보드, 쿼터 관리, 결제 이력 조회. 별도 admin/ 앱 또는 apps/web 내 admin 라우트 그룹으로 구현 예정.
- **Payple 정기 갱신 크론** (payple-renew)
- **SSE 스트리밍 Premium**
---
## Phase 3.2 Premium LLM 완결 (2026-04-12) — 빅뱅 8/8 마지막 성공 기준 ✅
Supabase Edge Function(llm-proxy)을 통해 Anthropic Claude를 호출하는 PremiumLLMService 구현. 사용자가 Settings에서 Local/Premium 백엔드를 선택하면 VoiceModeService가 자동 분기하고, Premium 실패 시 Local로 silent fallback + 상단 중앙 배너 알림.

View file

@ -375,6 +375,7 @@ export const IPC_CHANNELS = {
GET_USAGE: 'license:getUsage',
GET_ALL_USAGE: 'license:getAllUsage',
GET_TIER_COMPARISON: 'license:getTierComparison',
OPEN_BILLING: 'license:openBilling',
// Main → Renderer events
UPGRADE_PROMPT: 'license:upgradePrompt',
TIER_CHANGED: 'license:tierChanged',

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} Einträge",
"dashboard.stat": "Statistiken",
"dashboard.sys": "System",
"dashboard.currentBackend": "Aktuelles Backend",
"dashboard.backendLocal": "Lokal (Ollama)",
"dashboard.backendPremium": "Premium (Claude)",
"dashboard.loginRequired": "Anmeldung erforderlich",
"dashboard.premiumQuota": "Premium-Kontingent",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Wöchentlich",
"dashboard.quotaDaily": "Täglich",
"history.title": "Transkriptionsverlauf",
"history.search": "Suchen...",
"history.entries": "{{count}} Einträge",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "AKTIV",
"service.standby": "BEREITSCHAFT",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Abbrechen",
"common.save": "Speichern",
"common.delete": "Löschen",

View file

@ -35,6 +35,16 @@
"dashboard.entries": "{{count}} entries",
"dashboard.stat": "Stats",
"dashboard.sys": "System",
"dashboard.currentBackend": "Current Backend",
"dashboard.backendLocal": "Local (Ollama)",
"dashboard.backendPremium": "Premium (Claude)",
"dashboard.loginRequired": "Login Required",
"dashboard.premiumQuota": "Premium Quota",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Weekly",
"dashboard.quotaDaily": "Daily",
"history.title": "Transcription History",
"history.search": "Search...",
"history.entries": "{{count}} entries",
@ -204,6 +214,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Cancel",
"common.save": "Save",
"common.delete": "Delete",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} entradas",
"dashboard.stat": "estadísticas",
"dashboard.sys": "sistema",
"dashboard.currentBackend": "Backend actual",
"dashboard.backendLocal": "Local (Ollama)",
"dashboard.backendPremium": "Premium (Claude)",
"dashboard.loginRequired": "Inicio de sesión requerido",
"dashboard.premiumQuota": "Cuota Premium",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Semanal",
"dashboard.quotaDaily": "Diario",
"history.title": "Historial de transcripciones",
"history.search": "Buscar...",
"history.entries": "{{count}} entradas",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVO",
"service.standby": "EN ESPERA",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Cancelar",
"common.save": "Guardar",
"common.delete": "Eliminar",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} entrées",
"dashboard.stat": "statistiques",
"dashboard.sys": "système",
"dashboard.currentBackend": "Backend actuel",
"dashboard.backendLocal": "Local (Ollama)",
"dashboard.backendPremium": "Premium (Claude)",
"dashboard.loginRequired": "Connexion requise",
"dashboard.premiumQuota": "Quota Premium",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Hebdomadaire",
"dashboard.quotaDaily": "Journalier",
"history.title": "Historique des transcriptions",
"history.search": "Rechercher...",
"history.entries": "{{count}} entrées",
@ -185,6 +195,8 @@
"service.offline": "HORS LIGNE",
"service.active": "ACTIF",
"service.standby": "EN VEILLE",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Annuler",
"common.save": "Enregistrer",
"common.delete": "Supprimer",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}}件",
"dashboard.stat": "統計",
"dashboard.sys": "システム",
"dashboard.currentBackend": "現在のバックエンド",
"dashboard.backendLocal": "ローカル (Ollama)",
"dashboard.backendPremium": "プレミアム (Claude)",
"dashboard.loginRequired": "ログインが必要",
"dashboard.premiumQuota": "プレミアムクォータ",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "週間",
"dashboard.quotaDaily": "日間",
"history.title": "文字起こし履歴",
"history.search": "検索...",
"history.entries": "{{count}}件",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "キャンセル",
"common.save": "保存",
"common.delete": "削除",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}}건",
"dashboard.stat": "통계",
"dashboard.sys": "시스템",
"dashboard.currentBackend": "현재 백엔드",
"dashboard.backendLocal": "로컬 (Ollama)",
"dashboard.backendPremium": "프리미엄 (Claude)",
"dashboard.loginRequired": "로그인 필요",
"dashboard.premiumQuota": "프리미엄 쿼터",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "주간",
"dashboard.quotaDaily": "일간",
"history.title": "전사 기록",
"history.search": "검색...",
"history.entries": "{{count}}건",
@ -205,6 +215,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "취소",
"common.save": "저장",
"common.delete": "삭제",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} entradas",
"dashboard.stat": "estatísticas",
"dashboard.sys": "sistema",
"dashboard.currentBackend": "Backend atual",
"dashboard.backendLocal": "Local (Ollama)",
"dashboard.backendPremium": "Premium (Claude)",
"dashboard.loginRequired": "Login necessário",
"dashboard.premiumQuota": "Cota Premium",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Semanal",
"dashboard.quotaDaily": "Diário",
"history.title": "Histórico de transcrições",
"history.search": "Pesquisar...",
"history.entries": "{{count}} entradas",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ATIVO",
"service.standby": "EM ESPERA",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Cancelar",
"common.save": "Salvar",
"common.delete": "Excluir",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} записей",
"dashboard.stat": "Статистика",
"dashboard.sys": "Система",
"dashboard.currentBackend": "Текущий бэкенд",
"dashboard.backendLocal": "Локальный (Ollama)",
"dashboard.backendPremium": "Премиум (Claude)",
"dashboard.loginRequired": "Требуется вход",
"dashboard.premiumQuota": "Премиум квота",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Недельная",
"dashboard.quotaDaily": "Дневная",
"history.title": "История транскрипций",
"history.search": "Поиск...",
"history.entries": "{{count}} записей",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Отмена",
"common.save": "Сохранить",
"common.delete": "Удалить",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} รายการ",
"dashboard.stat": "สถิติ",
"dashboard.sys": "ระบบ",
"dashboard.currentBackend": "แบ็กเอนด์ปัจจุบัน",
"dashboard.backendLocal": "ภายในเครื่อง (Ollama)",
"dashboard.backendPremium": "พรีเมียม (Claude)",
"dashboard.loginRequired": "ต้องเข้าสู่ระบบ",
"dashboard.premiumQuota": "โควต้าพรีเมียม",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "รายสัปดาห์",
"dashboard.quotaDaily": "รายวัน",
"history.title": "ประวัติการถอดความ",
"history.search": "ค้นหา...",
"history.entries": "{{count}} รายการ",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "ยกเลิก",
"common.save": "บันทึก",
"common.delete": "ลบ",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}} mục",
"dashboard.stat": "Thống kê",
"dashboard.sys": "Hệ thống",
"dashboard.currentBackend": "Backend hiện tại",
"dashboard.backendLocal": "Cục bộ (Ollama)",
"dashboard.backendPremium": "Cao cấp (Claude)",
"dashboard.loginRequired": "Cần đăng nhập",
"dashboard.premiumQuota": "Hạn mức Premium",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "Hàng tuần",
"dashboard.quotaDaily": "Hàng ngày",
"history.title": "Lịch sử phiên âm",
"history.search": "Tìm kiếm...",
"history.entries": "{{count}} mục",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "Hủy",
"common.save": "Lưu",
"common.delete": "Xóa",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}}筆",
"dashboard.stat": "統計",
"dashboard.sys": "系統",
"dashboard.currentBackend": "目前後端",
"dashboard.backendLocal": "本機 (Ollama)",
"dashboard.backendPremium": "進階 (Claude)",
"dashboard.loginRequired": "需要登入",
"dashboard.premiumQuota": "進階配額",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "每週",
"dashboard.quotaDaily": "每日",
"history.title": "轉錄歷史",
"history.search": "搜尋...",
"history.entries": "{{count}}筆",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "取消",
"common.save": "儲存",
"common.delete": "刪除",

View file

@ -36,6 +36,16 @@
"dashboard.entries": "{{count}}条",
"dashboard.stat": "统计",
"dashboard.sys": "系统",
"dashboard.currentBackend": "当前后端",
"dashboard.backendLocal": "本地 (Ollama)",
"dashboard.backendPremium": "高级 (Claude)",
"dashboard.loginRequired": "需要登录",
"dashboard.premiumQuota": "高级配额",
"dashboard.modelHaiku": "Haiku",
"dashboard.modelSonnet": "Sonnet",
"dashboard.modelOpus": "Opus",
"dashboard.quotaWeekly": "每周",
"dashboard.quotaDaily": "每日",
"history.title": "转录历史",
"history.search": "搜索...",
"history.entries": "{{count}}条",
@ -185,6 +195,8 @@
"service.offline": "OFFLINE",
"service.active": "ACTIVE",
"service.standby": "STANDBY",
"service.premiumLlm": "PREMIUM LLM",
"service.notConfigured": "NOT SET",
"common.cancel": "取消",
"common.save": "保存",
"common.delete": "删除",

View file

@ -94,6 +94,15 @@ verify_jwt = true
[functions.stripe-webhook]
verify_jwt = false
[functions.payple-checkout]
verify_jwt = false
[functions.payple-webhook]
verify_jwt = false
[functions.payple-manage]
verify_jwt = false
[functions.team-invite]
verify_jwt = true

View file

@ -0,0 +1,281 @@
// 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+',
}

View file

@ -0,0 +1,113 @@
// server/supabase/functions/payple-checkout/index.ts
// Payple 빌링키 결제 처리 — 웹 결제 페이지에서 카드 등록 후 호출.
// 1) 클라이언트가 Payple JS SDK로 카드 등록 → PCD_PAYER_ID(빌링키) 획득
// 2) 이 함수에 payer_id + tier 전달 → 파트너 인증 → 빌링 결제 → DB 업데이트
// verify_jwt = false (requireUser로 직접 인증)
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
import { requireUser, authErrorResponse, type AuthError } from '../_shared/auth.ts'
import { createServiceRoleClient } from '../_shared/quota.ts'
import {
getPaypleConfig,
paypleAuth,
paypleBilling,
generateOrderId,
calcSubscriptionPeriod,
TIER_PRICE,
TIER_GOODS_NAME,
} from '../_shared/payple.ts'
interface CheckoutRequest {
payer_id: string // PCD_PAYER_ID (빌링키)
tier: 'pro' | 'pro_plus'
pcd_pay_cardname?: string // 카드사명 (표시용)
pcd_pay_cardnum?: string // 카드번호 마스킹 (표시용)
}
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
})
}
// @ts-expect-error — Deno 런타임 전역
Deno.serve(async (req: Request) => {
const preflight = handleCorsPreflightRequest(req)
if (preflight) return preflight
if (req.method !== 'POST') {
return jsonResponse({ error: 'Method not allowed' }, 405)
}
try {
const user = await requireUser(req)
const body = (await req.json()) as CheckoutRequest
if (!body.payer_id || !body.tier) {
return jsonResponse({ error: 'payer_id and tier are required' }, 400)
}
if (body.tier !== 'pro' && body.tier !== 'pro_plus') {
return jsonResponse({ error: 'Invalid tier. Must be pro or pro_plus' }, 400)
}
const price = TIER_PRICE[body.tier]
const goodsName = TIER_GOODS_NAME[body.tier]
if (!price || !goodsName) {
return jsonResponse({ error: 'Unknown tier' }, 400)
}
// 1. Payple 파트너 인증 (simple flag — 빌링 결제용)
const config = getPaypleConfig()
const auth = await paypleAuth(config, { simpleFlag: true })
// 2. 빌링키로 첫 결제 실행
const orderId = generateOrderId(user.id)
const billingResult = await paypleBilling(config, auth, {
payerId: body.payer_id,
amount: price,
orderId,
goodsName,
})
// 3. 결제 성공 → DB 업데이트
const { start, end } = calcSubscriptionPeriod()
const serviceClient = createServiceRoleClient()
await serviceClient
.from('subscriptions')
.update({
tier: body.tier,
status: 'active',
payment_provider: 'payple',
payple_payer_id: body.payer_id,
payple_pay_oid: billingResult.PCD_PAY_OID || orderId,
current_period_start: start,
current_period_end: end,
cancel_at: null,
updated_at: new Date().toISOString(),
})
.eq('user_id', user.id)
// profiles.tier도 동기화
await serviceClient
.from('profiles')
.update({ tier: body.tier, updated_at: new Date().toISOString() })
.eq('id', user.id)
return jsonResponse({
success: true,
tier: body.tier,
order_id: billingResult.PCD_PAY_OID || orderId,
amount: price,
})
} catch (err) {
if (err && typeof err === 'object' && 'status' in err && 'message' in err) {
return authErrorResponse(err as AuthError, corsHeaders)
}
const message = err instanceof Error ? err.message : 'Unknown error'
return jsonResponse({ error: message }, 500)
}
})

View file

@ -0,0 +1,99 @@
// server/supabase/functions/payple-manage/index.ts
// Payple 구독 관리 — 취소 (빌링키 해지 + tier 다운그레이드)
// stripe-portal 대체.
// verify_jwt = false (requireUser로 직접 인증)
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
import { requireUser, authErrorResponse, type AuthError } from '../_shared/auth.ts'
import { createServiceRoleClient } from '../_shared/quota.ts'
import {
getPaypleConfig,
paypleAuth,
paypleDeleteBillingKey,
} from '../_shared/payple.ts'
interface ManageRequest {
action: 'cancel' | 'info'
}
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
})
}
// @ts-expect-error — Deno 런타임 전역
Deno.serve(async (req: Request) => {
const preflight = handleCorsPreflightRequest(req)
if (preflight) return preflight
if (req.method !== 'POST') {
return jsonResponse({ error: 'Method not allowed' }, 405)
}
try {
const user = await requireUser(req)
const body = (await req.json()) as ManageRequest
const serviceClient = createServiceRoleClient()
// 현재 구독 정보 조회
const { data: sub } = await serviceClient
.from('subscriptions')
.select('tier, status, payment_provider, payple_payer_id, current_period_end')
.eq('user_id', user.id)
.maybeSingle()
if (!sub) {
return jsonResponse({ error: 'No subscription found' }, 404)
}
// info: 현재 구독 상태 반환
if (body.action === 'info') {
return jsonResponse({
tier: sub.tier,
status: sub.status,
payment_provider: sub.payment_provider,
current_period_end: sub.current_period_end,
has_billing_key: !!sub.payple_payer_id,
})
}
// cancel: 구독 취소
if (body.action === 'cancel') {
if (sub.payment_provider !== 'payple' || !sub.payple_payer_id) {
return jsonResponse({ error: 'No active Payple subscription to cancel' }, 400)
}
// 1. Payple 빌링키 해지
const config = getPaypleConfig()
const auth = await paypleAuth(config, { payWork: 'PUSERDEL' })
await paypleDeleteBillingKey(config, auth, sub.payple_payer_id)
// 2. DB 업데이트 — 현재 구독 기간이 끝날 때까지 유지
await serviceClient
.from('subscriptions')
.update({
status: 'canceled',
cancel_at: sub.current_period_end ?? new Date().toISOString(),
payple_payer_id: null,
updated_at: new Date().toISOString(),
})
.eq('user_id', user.id)
return jsonResponse({
success: true,
message: 'Subscription will be canceled at the end of the current period',
cancel_at: sub.current_period_end,
})
}
return jsonResponse({ error: 'Invalid action. Must be cancel or info' }, 400)
} catch (err) {
if (err && typeof err === 'object' && 'status' in err && 'message' in err) {
return authErrorResponse(err as AuthError, corsHeaders)
}
const message = err instanceof Error ? err.message : 'Unknown error'
return jsonResponse({ error: message }, 500)
}
})

View file

@ -0,0 +1,112 @@
// server/supabase/functions/payple-webhook/index.ts
// Payple 웹훅 수신 — 결제완료, 취소, 빌링키 등록/해지 이벤트 처리.
// Payple 관리자에서 웹훅 URL을 등록해야 함.
// verify_jwt = false (외부 Payple 서버에서 호출)
import { corsHeaders, handleCorsPreflightRequest } from '../_shared/cors.ts'
import { createServiceRoleClient } from '../_shared/quota.ts'
interface PaypleWebhookPayload {
PCD_PAY_RST: 'success' | 'error'
PCD_PAY_CODE: string
PCD_PAY_MSG: string
PCD_PAY_TYPE: string
PCD_PAY_OID: string
PCD_PAY_TOTAL?: string
PCD_PAYER_ID?: string
PCD_PAYER_NO?: string // 우리가 전달한 user_id
PCD_PAY_CARDNAME?: string
PCD_PAY_CARDNUM?: string
PCD_PAY_TIME?: string // 결제 시간 (YYYYMMDDHHMMSS)
// 웹훅 이벤트 구분용
PCD_PAY_WORK?: string // 'AUTH' (등록), 'CERT' (등록+결제)
PCD_PAYCANCEL_FLAG?: string // 'Y' (취소 이벤트)
}
function jsonResponse(body: Record<string, unknown>, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
})
}
// @ts-expect-error — Deno 런타임 전역
Deno.serve(async (req: Request) => {
const preflight = handleCorsPreflightRequest(req)
if (preflight) return preflight
if (req.method !== 'POST') {
return jsonResponse({ error: 'Method not allowed' }, 405)
}
try {
const payload = (await req.json()) as PaypleWebhookPayload
const serviceClient = createServiceRoleClient()
// 취소 이벤트
if (payload.PCD_PAYCANCEL_FLAG === 'Y') {
if (payload.PCD_PAY_RST === 'success' && payload.PCD_PAY_OID) {
// 주문번호로 구독 찾아서 상태 변경
const { data: sub } = await serviceClient
.from('subscriptions')
.select('user_id')
.eq('payple_pay_oid', payload.PCD_PAY_OID)
.maybeSingle()
if (sub) {
await serviceClient
.from('subscriptions')
.update({
status: 'canceled',
tier: 'free',
updated_at: new Date().toISOString(),
})
.eq('user_id', sub.user_id)
await serviceClient
.from('profiles')
.update({ tier: 'free', updated_at: new Date().toISOString() })
.eq('id', sub.user_id)
}
}
return jsonResponse({ received: true, event: 'cancel' })
}
// 결제 완료 이벤트
if (payload.PCD_PAY_RST === 'success' && payload.PCD_PAYER_ID) {
// payer_id(빌링키)로 구독 찾기
const { data: sub } = await serviceClient
.from('subscriptions')
.select('user_id, tier')
.eq('payple_payer_id', payload.PCD_PAYER_ID)
.maybeSingle()
if (sub && payload.PCD_PAY_OID) {
// 주문번호 + 구독 기간 갱신 (정기결제 갱신 시)
const now = new Date()
const end = new Date(now)
end.setMonth(end.getMonth() + 1)
await serviceClient
.from('subscriptions')
.update({
payple_pay_oid: payload.PCD_PAY_OID,
status: 'active',
current_period_start: now.toISOString(),
current_period_end: end.toISOString(),
updated_at: now.toISOString(),
})
.eq('user_id', sub.user_id)
}
return jsonResponse({ received: true, event: 'payment_complete' })
}
// 그 외 이벤트는 로깅만
return jsonResponse({ received: true, event: 'unknown' })
} catch (err) {
const message = err instanceof Error ? err.message : 'Unknown error'
return jsonResponse({ error: message }, 500)
}
})

View file

@ -0,0 +1,30 @@
-- Phase 3.2-B: Payple 결제 연동을 위한 스키마 확장
-- 기존 Stripe 필드를 보존하면서 Payple 결제 수단을 추가
-- 1. payment_provider 컬럼 — 어떤 결제 수단으로 구독했는지
ALTER TABLE public.subscriptions
ADD COLUMN IF NOT EXISTS payment_provider text NOT NULL DEFAULT 'none';
-- 기존 Stripe 구독자는 payment_provider = 'stripe' 로 갱신
UPDATE public.subscriptions
SET payment_provider = 'stripe'
WHERE stripe_customer_id IS NOT NULL
AND payment_provider = 'none';
-- CHECK 제약 추가
ALTER TABLE public.subscriptions
ADD CONSTRAINT subscriptions_payment_provider_check
CHECK (payment_provider IN ('none', 'stripe', 'payple'));
-- 2. Payple 결제 정보 컬럼
ALTER TABLE public.subscriptions
ADD COLUMN IF NOT EXISTS payple_payer_id text, -- 빌링키 (PCD_PAYER_ID)
ADD COLUMN IF NOT EXISTS payple_pay_oid text; -- 최근 주문번호 (PCD_PAY_OID)
-- 3. 인덱스: 빌링키로 구독 조회 (갱신 시 사용)
CREATE INDEX IF NOT EXISTS idx_subscriptions_payple_payer
ON public.subscriptions(payple_payer_id)
WHERE payple_payer_id IS NOT NULL;
-- 4. RLS: 기존 subscriptions 정책 그대로 적용 (user_id = auth.uid())
-- 새 컬럼은 기존 RLS 정책이 자동 커버하므로 추가 정책 불필요