feat(release): prepare 1.1.0 candidate

This commit is contained in:
Yun Chan 2026-08-29 18:33:45 +09:00
parent 5a34f66981
commit 5205dcdfa9
736 changed files with 115667 additions and 12203 deletions

View file

@ -10,6 +10,7 @@ export interface PaypleConfig {
clientKey: string
isTest: boolean
baseUrl: string // 'https://cpay.payple.kr' or 'https://democpay.payple.kr'
siteUrl: string
}
export interface PaypleAuthResult {
@ -33,6 +34,7 @@ export interface PaypleBillingResult {
PCD_PAY_CARDTRADENUM?: string
PCD_PAY_CARDRECEIPT?: string
PCD_PAYER_ID?: string
PCD_PAY_TIME?: string
}
export interface PaypleCancelResult {
@ -43,30 +45,121 @@ export interface PaypleCancelResult {
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<string, string | undefined>): 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 {
// @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 }
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(): string {
// @ts-expect-error — Deno.env
const siteUrl = Deno.env.get('PAYPLE_SITE_URL') ?? Deno.env.get('SITE_URL') ?? 'https://d3ro.dev'
return siteUrl
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()
}
// ── 파트너 인증 ───────────────────────────────────────
@ -77,6 +170,7 @@ export async function paypleAuth(
cancelFlag?: boolean // PCD_PAYCANCEL_FLAG
simpleFlag?: boolean // PCD_SIMPLE_FLAG (빌링 결제용)
payWork?: string // PCD_PAY_WORK (PUSERDEL 등)
payCheckFlag?: boolean // PCD_PAYCHK_FLAG (단건 결과조회)
}
): Promise<PaypleAuthResult> {
const body: Record<string, string> = {
@ -86,6 +180,8 @@ export async function paypleAuth(
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'
@ -98,7 +194,7 @@ export async function paypleAuth(
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
'Referer': getReferer(config),
},
body: JSON.stringify(body),
})
@ -112,13 +208,18 @@ export async function paypleAuth(
throw new Error(`Payple auth error: ${data['result_msg'] ?? data['cst_id'] ?? 'unknown'}`)
}
return {
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
}
// ── 빌링키로 결제 ────────────────────────────────────
@ -133,37 +234,50 @@ export async function paypleBilling(
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 url = getPaypleApiUrl(
config,
auth.PCD_PAY_HOST,
'/php/SimplePayCardAct.php?ACT_=PAYM',
)
const billingUrl = new URL('/php/SimplePayCardAct.php?ACT_=PAYM', url).toString()
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}`)
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)
}
const data = await resp.json() as PaypleBillingResult
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 Error(`Payple billing error: ${data.PCD_PAY_MSG} (${data.PCD_PAY_CODE})`)
throw new PaypleBillingError('payple_billing_declined', true)
}
return data
@ -185,7 +299,7 @@ export async function paypleCancel(
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'Referer': getReferer(),
'Referer': getReferer(config),
},
body: JSON.stringify({
PCD_CST_ID: auth.PCD_CST_ID,
@ -218,16 +332,15 @@ export async function paypleDeleteBillingKey(
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 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(),
'Referer': getReferer(config),
},
body: JSON.stringify({
PCD_CST_ID: auth.PCD_CST_ID,
@ -247,19 +360,179 @@ export async function paypleDeleteBillingKey(
}
}
// ── 서버 대 서버 결과조회 ──────────────────────────────
/**
* Payple . payload를
* API로
* entitlement event로 .
*/
export async function paypleLookupPayment(
config: PaypleConfig,
auth: PaypleAuthResult,
params: {
orderId: string
payType: 'card' | 'transfer'
payDate: string
},
): Promise<PayplePaymentLookupResult> {
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<PaypleBillingKeyLookupResult> {
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<string> {
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<string> {
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<string> {
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): string {
const now = new Date()
const ts = now.toISOString().replace(/[-:T.Z]/g, '').substring(0, 14)
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)
return `D3RO-${ts}-${short}`
const unique = nonce.replace(/-/g, '').substring(0, 8)
return `D3RO-${ts}-${short}-${unique}`
}
// ── 구독 기간 계산 ────────────────────────────────────
export function calcSubscriptionPeriod(): { start: string; end: string } {
const now = new Date()
export function calcSubscriptionPeriod(now = new Date()): { start: string; end: string } {
const end = new Date(now)
end.setMonth(end.getMonth() + 1)
return {