// 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' siteUrl: string } 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 PCD_PAY_TIME?: 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 interface PayplePaymentLookupResult { PCD_PAY_RST: 'success' | 'error' PCD_PAY_CODE: string PCD_PAY_MSG: string PCD_PAY_OID: string PCD_PAY_TYPE: 'card' | 'transfer' PCD_PAYER_ID?: string PCD_PAYER_NO?: string PCD_PAY_TOTAL?: string PCD_PAY_TIME?: string PCD_PAY_STATE?: string } export interface PaypleBillingKeyLookupResult { PCD_PAY_RST: 'success' | 'error' PCD_PAY_CODE: string PCD_PAY_MSG: string PCD_PAYER_ID?: string PCD_PAYER_NO?: string } export class PaypleConfigurationError extends Error { readonly code = 'payple_not_configured' constructor(message: string) { super(message) this.name = 'PaypleConfigurationError' } } export class PaypleVerificationError extends Error { readonly code: string constructor(code: string) { super(code) this.name = 'PaypleVerificationError' this.code = code } } export class PaypleBillingError extends Error { readonly code: string readonly definitive: boolean constructor(code: string, definitive: boolean) { super(code) this.name = 'PaypleBillingError' this.code = code this.definitive = definitive } } // ── 환경변수에서 설정 로드 ────────────────────────────── export function buildPaypleConfig(values: Record): PaypleConfig { const environment = values['PAYPLE_ENVIRONMENT'] if (environment !== 'test' && environment !== 'live') { throw new PaypleConfigurationError('PAYPLE_ENVIRONMENT must be test or live') } const required = [ 'PAYPLE_CST_ID', 'PAYPLE_CUST_KEY', 'PAYPLE_REFUND_KEY', 'PAYPLE_CLIENT_KEY', 'PAYPLE_SITE_URL', ] as const for (const key of required) { if (!values[key]?.trim()) { throw new PaypleConfigurationError(`${key} is required`) } } const siteUrl = new URL(values['PAYPLE_SITE_URL']!.trim()) if (siteUrl.protocol !== 'https:' && !(environment === 'test' && siteUrl.hostname === 'localhost')) { throw new PaypleConfigurationError('PAYPLE_SITE_URL must use HTTPS') } return { cstId: values['PAYPLE_CST_ID']!.trim(), custKey: values['PAYPLE_CUST_KEY']!.trim(), refundKey: values['PAYPLE_REFUND_KEY']!.trim(), clientKey: values['PAYPLE_CLIENT_KEY']!.trim(), siteUrl: siteUrl.origin, isTest: environment === 'test', baseUrl: environment === 'test' ? 'https://democpay.payple.kr' : 'https://cpay.payple.kr', } } export function getPaypleConfig(): PaypleConfig { return buildPaypleConfig({ PAYPLE_ENVIRONMENT: Deno.env.get('PAYPLE_ENVIRONMENT'), PAYPLE_CST_ID: Deno.env.get('PAYPLE_CST_ID'), PAYPLE_CUST_KEY: Deno.env.get('PAYPLE_CUST_KEY'), PAYPLE_REFUND_KEY: Deno.env.get('PAYPLE_REFUND_KEY'), PAYPLE_CLIENT_KEY: Deno.env.get('PAYPLE_CLIENT_KEY'), PAYPLE_SITE_URL: Deno.env.get('PAYPLE_SITE_URL'), }) } // ── Referer 헤더 ────────────────────────────────────── function getReferer(config: PaypleConfig): string { return config.siteUrl } function getPaypleApiUrl(config: PaypleConfig, candidate: string | undefined, fallbackPath: string): string { const url = new URL(candidate || fallbackPath, config.baseUrl) const expected = new URL(config.baseUrl) if (url.protocol !== 'https:' || url.origin !== expected.origin) { throw new PaypleVerificationError('payple_untrusted_api_host') } return url.toString() } // ── 파트너 인증 ─────────────────────────────────────── export async function paypleAuth( config: PaypleConfig, options?: { cancelFlag?: boolean // PCD_PAYCANCEL_FLAG simpleFlag?: boolean // PCD_SIMPLE_FLAG (빌링 결제용) payWork?: string // PCD_PAY_WORK (PUSERDEL 등) payCheckFlag?: boolean // PCD_PAYCHK_FLAG (단건 결과조회) } ): Promise { const body: Record = { cst_id: config.cstId, custKey: config.custKey, } if (options?.cancelFlag) { body['PCD_PAYCANCEL_FLAG'] = 'Y' } else if (options?.payCheckFlag) { body['PCD_PAYCHK_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(config), }, body: JSON.stringify(body), }) if (!resp.ok) { throw new Error(`Payple auth failed: HTTP ${resp.status}`) } const data = await resp.json() as Record if (data['result'] !== 'success') { throw new Error(`Payple auth error: ${data['result_msg'] ?? data['cst_id'] ?? 'unknown'}`) } const result = { 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'] ?? '', } if (!result.PCD_CST_ID || !result.PCD_CUST_KEY || !result.PCD_AUTH_KEY) { throw new PaypleVerificationError('payple_auth_response_incomplete') } getPaypleApiUrl(config, result.PCD_PAY_HOST, '/') return result } // ── 빌링키로 결제 ──────────────────────────────────── export async function paypleBilling( config: PaypleConfig, auth: PaypleAuthResult, params: { payerId: string // PCD_PAYER_ID (빌링키) amount: number // 결제 금액 (원) orderId: string // 주문번호 goodsName: string // 상품명 } ): Promise { const url = getPaypleApiUrl( config, auth.PCD_PAY_HOST, '/php/SimplePayCardAct.php?ACT_=PAYM', ) const billingUrl = new URL('/php/SimplePayCardAct.php?ACT_=PAYM', url).toString() let resp: Response try { resp = await fetch(billingUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Referer': getReferer(config), }, 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', }), }) } catch { throw new PaypleBillingError('payple_billing_transport_unknown', false) } if (!resp.ok) { throw new PaypleBillingError('payple_billing_http_unknown', false) } let data: PaypleBillingResult try { data = await resp.json() as PaypleBillingResult } catch { throw new PaypleBillingError('payple_billing_response_unknown', false) } if (data.PCD_PAY_RST !== 'success') { throw new PaypleBillingError('payple_billing_declined', true) } return data } // ── 결제 취소/환불 ──────────────────────────────────── export async function paypleCancel( config: PaypleConfig, auth: PaypleAuthResult, params: { payOid: string // 원거래 주문번호 payDate: string // 결제일자 (YYYYMMDD) refundTotal: number // 환불 금액 } ): Promise { const resp = await fetch(`${config.baseUrl}/php/account/api/cPayCAct.php`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Referer': getReferer(config), }, 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 { const host = getPaypleApiUrl(config, auth.PCD_PAY_HOST, '/') const url = new URL('/php/cPayUser/api/cPayUserAct.php?ACT_=PUSERDEL', host).toString() const resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Referer': getReferer(config), }, 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'}`) } } // ── 서버 대 서버 결과조회 ────────────────────────────── /** * Payple 국내 결제 웹훅에는 별도 서명 헤더 계약이 없다. 웹훅 payload를 * 신뢰하지 않고 공식 단건 결과조회 API로 원거래를 다시 조회한 결과만 * entitlement event로 사용할 수 있도록 한다. */ export async function paypleLookupPayment( config: PaypleConfig, auth: PaypleAuthResult, params: { orderId: string payType: 'card' | 'transfer' payDate: string }, ): Promise { if (!/^[A-Za-z0-9._-]{8,64}$/.test(params.orderId)) { throw new PaypleVerificationError('payple_invalid_order_id') } if (!/^\d{8}$/.test(params.payDate)) { throw new PaypleVerificationError('payple_invalid_pay_date') } const lookupUrl = getPaypleApiUrl( config, auth.PCD_PAY_URL, '/php/PayChkAct.php', ) const resp = await fetch(lookupUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Referer': getReferer(config), }, 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_PAYCHK_FLAG: 'Y', PCD_PAY_TYPE: params.payType, PCD_PAY_OID: params.orderId, PCD_PAY_DATE: params.payDate, }), }) if (!resp.ok) { throw new PaypleVerificationError(`payple_lookup_http_${resp.status}`) } const data = await resp.json() as PayplePaymentLookupResult if ( data.PCD_PAY_RST !== 'success' || data.PCD_PAY_CODE !== 'PCHK0000' || data.PCD_PAY_OID !== params.orderId || data.PCD_PAY_TYPE !== params.payType ) { throw new PaypleVerificationError('payple_lookup_mismatch') } return data } export async function paypleLookupBillingKey( config: PaypleConfig, auth: PaypleAuthResult, payerId: string, ): Promise { if (!payerId || payerId.length > 255) { throw new PaypleVerificationError('payple_invalid_payer_id') } const host = getPaypleApiUrl(config, auth.PCD_PAY_HOST, '/') const url = new URL('/php/cPayUser/api/cPayUserAct.php?ACT_=PUSERINFO', host).toString() const resp = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-cache', 'Referer': getReferer(config), }, 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 PaypleVerificationError(`payple_billing_key_lookup_http_${resp.status}`) } return await resp.json() as PaypleBillingKeyLookupResult } export function parsePaypleTimestamp(value: string): Date { const compact = value.trim().replace(/[- :]/g, '') if (!/^\d{14}$/.test(compact)) { throw new PaypleVerificationError('payple_invalid_timestamp') } const iso = `${compact.slice(0, 4)}-${compact.slice(4, 6)}-${compact.slice(6, 8)}` + `T${compact.slice(8, 10)}:${compact.slice(10, 12)}:${compact.slice(12, 14)}+09:00` const parsed = new Date(iso) if (!Number.isFinite(parsed.getTime())) { throw new PaypleVerificationError('payple_invalid_timestamp') } return parsed } export function resolvePaypleOrderDate(orderId: string, payTime?: string): string { if (payTime) { const parsed = payTime.trim().replace(/[- :]/g, '') if (!/^\d{14}$/.test(parsed)) { throw new PaypleVerificationError('payple_invalid_pay_date') } return parsed.slice(0, 8) } const d3roMatch = /^D3RO-(\d{8})\d{6}-/.exec(orderId) if (d3roMatch) return d3roMatch[1] throw new PaypleVerificationError('payple_missing_pay_date') } export async function sha256Text(value: string): Promise { const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value)) return Array.from(new Uint8Array(bytes)) .map((part) => part.toString(16).padStart(2, '0')) .join('') } export async function payplePayerNumber(userId: string): Promise { const digest = await sha256Text(`d3ro-payple:${userId}`) return (BigInt(`0x${digest}`) % 1_000_000_000_000_000_000n) .toString() .padStart(18, '0') } export function payplePaymentEventId(orderId: string): string { if (!/^[A-Za-z0-9._-]{8,64}$/.test(orderId)) { throw new PaypleVerificationError('payple_invalid_order_id') } return `payment:${orderId}` } export async function payplePaymentEventDigest(params: { orderId: string payerId: string payType: 'card' | 'transfer' amount: number }): Promise { payplePaymentEventId(params.orderId) if (!params.payerId || params.payerId.length > 255) { throw new PaypleVerificationError('payple_invalid_payer_id') } if (!Number.isSafeInteger(params.amount) || params.amount <= 0) { throw new PaypleVerificationError('payple_invalid_amount') } return await sha256Text(JSON.stringify({ amount: params.amount, order_id: params.orderId, payer_id: params.payerId, payment_type: params.payType, })) } // ── 주문번호 생성 유틸리티 ───────────────────────────── export function generateOrderId(userId: string, nonce = crypto.randomUUID()): string { const koreaNow = new Date(Date.now() + 9 * 60 * 60 * 1000) const ts = koreaNow.toISOString().replace(/[-:T.Z]/g, '').substring(0, 14) const short = userId.substring(0, 8) const unique = nonce.replace(/-/g, '').substring(0, 8) return `D3RO-${ts}-${short}-${unique}` } // ── 구독 기간 계산 ──────────────────────────────────── export function calcSubscriptionPeriod(now = new Date()): { start: string; end: string } { const end = new Date(now) end.setMonth(end.getMonth() + 1) return { start: now.toISOString(), end: end.toISOString(), } } // ── 티어별 가격 ────────────────────────────────────── export const TIER_PRICE: Record = { pro: 9900, pro_plus: 29900, } export const TIER_GOODS_NAME: Record = { pro: 'D3RO Voice Pro', pro_plus: 'D3RO Voice Pro+', }