Permitir pagar los servicios con PD, Stripe o SumUp (elección)

Los 9 servicios con precio en euros (rename, customize, change-race,
change-faction, level-up, gold, transfer, restore-item, send-gift) ahora
ofrecen un selector de forma de pago con las 3 opciones: saldo PD, tarjeta
(Stripe) o tarjeta (SumUp).

- lib/dpoints: spendDPoints() descuenta PD de forma atómica (FOR UPDATE).
- lib/pay-with-dpoints: paga con saldo PD, ejecuta la acción al momento y
  reembolsa si la ejecución falla; 100 PD = 1 €.
- rutas checkout (character/[service] y gift): rama provider='pd' que valida
  saldo, descuenta, ejecuta fulfill y devuelve la URL de éxito (sin pasarela).
- service-success: rama provider='pd' (la entrega ya se hizo en el checkout).
- PaymentMethodSelect: componente compartido con coste por método y saldo;
  desactiva PD si no hay saldo suficiente.
- Formularios (PaidServiceForm, Gold, Transfer, RestoreItems, SendGift) y sus
  páginas pasan el saldo PD y envían el método elegido + locale.
- i18n: namespace Pay (es/en); añadidas claves Paid.restore-item que faltaban.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-14 21:44:31 +00:00
parent 942fe2e397
commit 1b0920d11f
24 changed files with 420 additions and 66 deletions
@@ -4,6 +4,12 @@ import { getGameCharacters } from '@/lib/characters'
import { createCheckoutSession } from '@/lib/stripe'
import { createSumUpCheckout, sumupConfigured } from '@/lib/sumup'
import { getPaidService } from '@/lib/paid-services'
import { payServiceWithDPoints } from '@/lib/pay-with-dpoints'
/** Locale seguro (es/en) para construir la URL de retorno. */
function safeLocale(v: unknown): string {
return v === 'en' ? 'en' : 'es'
}
export async function POST(request: Request, { params }: { params: Promise<{ service: string }> }) {
const { service } = await params
@@ -49,6 +55,19 @@ export async function POST(request: Request, { params }: { params: Promise<{ ser
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
const productName = cfg.productName(character, metadata)
// Pago con saldo PD: se descuenta el saldo y se ejecuta la acción al momento
// (sin pasarela). Devuelve la URL de éxito para que el form redirija igual que
// con Stripe/SumUp; la entrega ya se ha realizado aquí.
if (String(body.provider) === 'pd') {
const r = await payServiceWithDPoints(session.accountId, price, () => cfg.fulfill(character, metadata))
if (!r.success) return Response.json({ success: false, error: r.error })
const locale = safeLocale(body.locale)
return Response.json({
success: true,
url: `${site}/${locale}/service-success?service=${service}&provider=pd&name=${encodeURIComponent(character)}`,
})
}
// Pago por SumUp (euros): al pagar, la reconciliación/return ejecuta la acción
// del servicio sobre el personaje (no acredita PD).
if (String(body.provider) === 'sumup') {
+19 -4
View File
@@ -3,7 +3,8 @@ import { getSession } from '@/lib/session'
import { getGameCharacters, getAccountIdByCharacterName } from '@/lib/characters'
import { checkSecurityToken } from '@/lib/security-token'
import { createSumUpCheckout, sumupConfigured } from '@/lib/sumup'
import { priceCart, isValidCharName, type CartLine } from '@/lib/gift'
import { priceCart, isValidCharName, sendGiftByMail, type CartLine } from '@/lib/gift'
import { payServiceWithDPoints } from '@/lib/pay-with-dpoints'
/**
* Inicia el pago (SumUp) de un regalo. Condiciones:
@@ -18,7 +19,7 @@ export async function POST(request: Request) {
const session = await getSession()
if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
let body: { source?: string; destination?: string; cart?: CartLine[]; security_token?: string; provider?: string } = {}
let body: { source?: string; destination?: string; cart?: CartLine[]; security_token?: string; provider?: string; locale?: string } = {}
try {
body = await request.json()
} catch {
@@ -58,14 +59,28 @@ export async function POST(request: Request) {
return Response.json({ success: false, message: 'Tu carrito está vacío o contiene objetos no válidos.' })
}
const site = process.env.SITE_URL || ''
const items = priced.lines.map((l) => ({ i: l.itemId, q: l.qty }))
// Pago con saldo PD: se descuenta el saldo y se envía el regalo al momento.
if (String(body.provider) === 'pd') {
const r = await payServiceWithDPoints(session.accountId, priced.total, () =>
sendGiftByMail(destination, source, items),
)
if (!r.success) return Response.json({ success: false, error: r.error, message: 'No se pudo completar el pago con PD.' })
const locale = String(body.locale) === 'en' ? 'en' : 'es'
return Response.json({
success: true,
url: `${site}/${locale}/service-success?service=send-gift&provider=pd&name=${encodeURIComponent(destination)}`,
})
}
if (String(body.provider) !== 'sumup' || !sumupConfigured()) {
return Response.json({ success: false, error: 'notConfigured', message: 'El método de pago no está disponible ahora mismo.' })
}
const site = process.env.SITE_URL || ''
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
const reference = randomUUID()
const items = priced.lines.map((l) => ({ i: l.itemId, q: l.qty }))
const description = `Regalo para ${destination} (${priced.lines.length} objeto${priced.lines.length === 1 ? '' : 's'})`
const r = await createSumUpCheckout({