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,74 +77,74 @@ 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}>
{PLANS.map((plan) => {
const active = currentTier === plan.tier
return (
<Grid size={{ xs: 12, md: 4 }} key={plan.tier}>
<MetalCard
sx={{
p: 4,
height: '100%',
border: active
? `2px solid ${d3roPalette.accent.amber}`
: plan.highlight
? `2px solid ${d3roPalette.tag.purple}`
: undefined
}}
>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label, mb: 1 }}>
{plan.tier.toUpperCase()}
</Box>
<PhosphorText variant="title" sx={{ mb: 1 }}>
{plan.name}
</PhosphorText>
<Box sx={{ ...typoSx('value'), color: d3roPalette.text.primary, mb: 3 }}>
{plan.price}
</Box>
<Grid container spacing={3}>
{PLANS.map((plan) => {
const active = currentTier === plan.tier
return (
<Grid size={{ xs: 12, md: 4 }} key={plan.tier}>
<MetalCard
sx={{
p: 4,
height: '100%',
border: active
? `2px solid ${d3roPalette.accent.amber}`
: plan.highlight
? `2px solid ${d3roPalette.tag.purple}`
: undefined,
}}
>
<Box sx={{ ...typoSx('label'), color: d3roPalette.text.label, mb: 1 }}>
{plan.tier === 'pro_plus' ? 'PRO+' : plan.tier.toUpperCase()}
</Box>
<PhosphorText variant="title" sx={{ mb: 1 }}>
{plan.name}
</PhosphorText>
<Box sx={{ ...typoSx('value'), color: d3roPalette.text.primary, mb: 3 }}>
{plan.price}
</Box>
<Box component="ul" sx={{ pl: 2, mb: 3, color: d3roPalette.text.secondary }}>
{plan.features.map((f) => (
<Box component="li" key={f} sx={{ fontSize: 13, mb: 0.5 }}>
{f}
</Box>
))}
</Box>
<Box component="ul" sx={{ pl: 2, mb: 3, color: d3roPalette.text.secondary }}>
{plan.features.map((f) => (
<Box component="li" key={f} sx={{ fontSize: 13, mb: 0.5 }}>
{f}
</Box>
))}
</Box>
{active ? (
<Box
sx={{
textAlign: 'center',
p: 1.5,
bgcolor: d3roPalette.bg.inset,
borderRadius: 1,
color: d3roPalette.accent.amber,
...typoSx('label')
}}
>
</Box>
) : plan.tier === 'free' ? (
<Box sx={{ textAlign: 'center', color: d3roPalette.text.muted, fontSize: 12 }}>
</Box>
) : (
<CheckoutButton tier={plan.tier} />
)}
</MetalCard>
</Grid>
)
})}
</Grid>
{active ? (
<Box
sx={{
textAlign: 'center',
p: 1.5,
bgcolor: d3roPalette.bg.inset,
borderRadius: 1,
color: d3roPalette.accent.amber,
...typoSx('label'),
}}
>
</Box>
) : plan.tier === 'free' ? (
<Box sx={{ textAlign: 'center', color: d3roPalette.text.muted, fontSize: 12 }}>
</Box>
) : (
<PaypleCheckoutButton tier={plan.tier} />
)}
</MetalCard>
</Grid>
)
})}
</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>
)
}