fix(payple): reject checkout while a paid Payple period is still active

This commit is contained in:
Yun Chan 2026-09-28 02:16:21 +09:00
parent f456d737c4
commit e69fe0335d
5 changed files with 717 additions and 71 deletions

View file

@ -17,19 +17,13 @@ import {
TIER_GOODS_NAME,
TIER_PRICE,
} from '../_shared/payple.ts'
interface CheckoutRequest {
payer_id?: unknown
tier?: unknown
idempotency_key?: unknown
}
interface OperationReservation {
created?: boolean
operation_id?: string
state?: string
reason?: string
}
import {
chargeMatchesOrder,
decideReservation,
isBillingKeyOwnedBy,
parseCheckoutRequest,
planCheckoutFailure,
} from './checkout-policy.ts'
interface ApplyResult {
applied?: boolean
@ -44,10 +38,6 @@ function jsonResponse(body: Record<string, unknown>, status = 200): Response {
})
}
function validIdempotencyKey(value: unknown): value is string {
return typeof value === 'string' && /^[A-Za-z0-9._:-]{12,160}$/.test(value)
}
Deno.serve(async (req: Request) => {
const preflight = handleCorsPreflightRequest(req)
if (preflight) return preflight
@ -60,21 +50,13 @@ Deno.serve(async (req: Request) => {
try {
const user = await requireUser(req)
const body = await req.json() as CheckoutRequest
if (
typeof body.payer_id !== 'string'
|| body.payer_id.length < 8
|| body.payer_id.length > 255
|| (body.tier !== 'pro' && body.tier !== 'pro_plus')
|| (body.idempotency_key !== undefined && !validIdempotencyKey(body.idempotency_key))
) {
return jsonResponse({ error: 'invalid_request' }, 400)
}
const input = parseCheckoutRequest(await req.json())
if (!input) return jsonResponse({ error: 'invalid_request' }, 400)
// Configuration is validated before reserving state or contacting Payple.
// There are deliberately no bundled/test credential fallbacks.
const config = getPaypleConfig()
const idempotencyKey = body.idempotency_key
const idempotencyKey = input.idempotencyKey
?? `payple-checkout:${crypto.randomUUID()}`
const orderId = generateOrderId(user.id)
providerOrderId = orderId
@ -84,40 +66,35 @@ Deno.serve(async (req: Request) => {
p_user_id: user.id,
p_provider: 'payple',
p_operation_type: 'checkout',
p_requested_tier: body.tier,
p_requested_tier: input.tier,
p_idempotency_key: idempotencyKey,
p_provider_order_id: orderId,
// Bind the reserved order to this billing key before any charge. The
// PUSERINFO lookup below still verifies its authenticated user owner.
p_provider_resource_id: body.payer_id,
p_provider_resource_id: input.payerId,
},
)
if (reservationError) throw new Error('payment_reservation_failed')
const reservation = reservationData as OperationReservation | null
if (!reservation?.created || typeof reservation.operation_id !== 'string') {
return jsonResponse({
error: reservation?.reason ?? 'payment_operation_in_progress',
state: reservation?.state ?? 'rejected',
}, 409)
// The reservation is the single serialization point: it rejects an
// in-flight operation, another provider's ownership, and an active paid
// Payple period ('subscription_already_active') before any charge.
const reservation = decideReservation(reservationData)
if (reservation.kind === 'reject') {
return jsonResponse(reservation.body, reservation.status)
}
operationId = reservation.operation_id
operationId = reservation.operationId
const price = TIER_PRICE[body.tier]
const goodsName = TIER_GOODS_NAME[body.tier]
const price = TIER_PRICE[input.tier]
const goodsName = TIER_GOODS_NAME[input.tier]
const billingKeyAuth = await paypleAuth(config, { payWork: 'PUSERINFO' })
const billingKey = await paypleLookupBillingKey(config, billingKeyAuth, body.payer_id)
const billingKey = await paypleLookupBillingKey(config, billingKeyAuth, input.payerId)
const expectedPayerNumbers = [user.id, await payplePayerNumber(user.id)]
if (
billingKey.PCD_PAY_RST !== 'success'
|| billingKey.PCD_PAYER_ID !== body.payer_id
|| !billingKey.PCD_PAYER_NO
|| !expectedPayerNumbers.includes(billingKey.PCD_PAYER_NO)
) {
if (!isBillingKeyOwnedBy(billingKey, input.payerId, expectedPayerNumbers)) {
throw new Error('payple_billing_key_owner_mismatch')
}
const auth = await paypleAuth(config, { simpleFlag: true })
const billingResult = await paypleBilling(config, auth, {
payerId: body.payer_id,
payerId: input.payerId,
amount: price,
orderId,
goodsName,
@ -132,11 +109,7 @@ Deno.serve(async (req: Request) => {
})
if (chargedError) throw new Error('payment_operation_update_failed')
if (
billingResult.PCD_PAY_OID !== orderId
|| billingResult.PCD_PAY_TOTAL !== String(price)
|| (billingResult.PCD_PAYER_ID && billingResult.PCD_PAYER_ID !== body.payer_id)
) {
if (!chargeMatchesOrder(billingResult, { orderId, amount: price, payerId: input.payerId })) {
throw new Error('payple_charge_response_mismatch')
}
@ -155,19 +128,19 @@ Deno.serve(async (req: Request) => {
p_event_type: 'payment.completed',
p_payload_digest: await payplePaymentEventDigest({
orderId,
payerId: body.payer_id,
payerId: input.payerId,
payType: 'card',
amount: price,
}),
p_provider_resource_id: body.payer_id,
p_tier: body.tier,
p_provider_resource_id: input.payerId,
p_tier: input.tier,
p_status: 'active',
p_entitled: true,
p_current_period_start: start,
p_current_period_end: end,
p_cancel_at: null,
p_auto_renewing: true,
p_provider_customer_id: body.payer_id,
p_provider_customer_id: input.payerId,
p_provider_order_id: orderId,
p_store_product_id: null,
p_store_purchase_id: null,
@ -186,39 +159,38 @@ Deno.serve(async (req: Request) => {
return jsonResponse({
success: true,
tier: body.tier,
tier: input.tier,
order_id: orderId,
amount: price,
})
} catch (error) {
const chargeOutcomeUnknown = error instanceof PaypleBillingError && !error.definitive
if (operationId && chargeOutcomeUnknown) {
const plan = planCheckoutFailure(
{
hasOperation: operationId !== null,
externalChargeCompleted,
chargeOutcomeUnknown: error instanceof PaypleBillingError && !error.definitive,
configurationError: error instanceof PaypleConfigurationError,
},
error instanceof PaypleConfigurationError ? error.code : 'payple_not_configured',
)
if (operationId && plan.mark?.state === 'external_created') {
await serviceClient.rpc('mark_payment_provider_operation', {
p_operation_id: operationId,
p_state: 'external_created',
p_external_reference: providerOrderId,
p_error_code: null,
})
} else if (operationId && !externalChargeCompleted) {
} else if (operationId && plan.mark?.state === 'failed') {
await serviceClient.rpc('mark_payment_provider_operation', {
p_operation_id: operationId,
p_state: 'failed',
p_external_reference: null,
p_error_code: error instanceof PaypleConfigurationError
? 'payple_not_configured'
: 'payple_checkout_failed',
p_error_code: plan.mark.errorCode,
})
}
if (error && typeof error === 'object' && 'status' in error && 'message' in error) {
return authErrorResponse(error as AuthError, corsHeaders)
}
if (error instanceof PaypleConfigurationError) {
return jsonResponse({ error: error.code }, 503)
}
return jsonResponse({
error: externalChargeCompleted || chargeOutcomeUnknown
? 'payment_requires_reconciliation'
: 'payple_checkout_failed',
}, externalChargeCompleted || chargeOutcomeUnknown ? 409 : 502)
return jsonResponse({ error: plan.error }, plan.status)
}
})