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:
parent
b8cb665264
commit
c9baf031c9
27 changed files with 1318 additions and 98 deletions
|
|
@ -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
|
||||
|
||||
|
|
|
|||
281
server/supabase/functions/_shared/payple.ts
Normal file
281
server/supabase/functions/_shared/payple.ts
Normal 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+',
|
||||
}
|
||||
113
server/supabase/functions/payple-checkout/index.ts
Normal file
113
server/supabase/functions/payple-checkout/index.ts
Normal 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)
|
||||
}
|
||||
})
|
||||
99
server/supabase/functions/payple-manage/index.ts
Normal file
99
server/supabase/functions/payple-manage/index.ts
Normal 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)
|
||||
}
|
||||
})
|
||||
112
server/supabase/functions/payple-webhook/index.ts
Normal file
112
server/supabase/functions/payple-webhook/index.ts
Normal 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)
|
||||
}
|
||||
})
|
||||
30
server/supabase/migrations/20260412000002_payple_billing.sql
Normal file
30
server/supabase/migrations/20260412000002_payple_billing.sql
Normal 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 정책이 자동 커버하므로 추가 정책 불필요
|
||||
Loading…
Add table
Add a link
Reference in a new issue