Añade gold y transfer: patrón de pago unificado con fulfill + metadata

- lib/stripe.ts: createCheckoutSession acepta metadata; claimPaidCheckout la
  recupera de la sesión Stripe y la devuelve.
- lib/paid-services.ts: config unificado con fulfill(character, meta) + extraFields.
  gold -> UPDATE characters money (BD directa, no SOAP), transfer -> SOAP
  .char changeaccount. Los 5 simples usan soapFulfill.
- checkout [service]: lee extraFields -> metadata, precio depende de metadata (gold),
  valida precio>0. service-success llama cfg.fulfill(name, metadata).
- prices.ts: getTransferPrice, getGoldOptions/goldPriceFor (home_goldprice).
- GoldForm (personaje + cantidad) y TransferForm (personaje + destino); páginas
  /gold y /transfer. Catálogos Paid.gold/transfer.

Verificado: /gold /transfer redirigen a login, checkout 401 sin sesión, home OK.
NOTA: transfer no valida aún el token de seguridad ni reglas AC (nivel>=55, DK).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 23:32:12 +00:00
parent 87f9b0b003
commit 548fca16e6
12 changed files with 310 additions and 29 deletions
+26
View File
@@ -0,0 +1,26 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getGameCharacters } from '@/lib/characters'
import { getGoldOptions } from '@/lib/prices'
import { GoldForm } from '@/components/GoldForm'
export const dynamic = 'force-dynamic'
export default async function GoldPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
setRequestLocale(locale)
const t = await getTranslations('Paid')
const session = await getSession()
if (!session.bnetId) redirect({ href: '/login', locale })
if (!session.username) redirect({ href: '/select-account', locale })
const [chars, options] = await Promise.all([getGameCharacters(session.accountId!), getGoldOptions()])
return (
<main className="mx-auto max-w-3xl px-4 py-8">
<h1 className="mb-6 text-center text-2xl font-bold text-amber-500">{t('gold.title')}</h1>
<GoldForm characters={chars.map((c) => c.name)} options={options} />
</main>
)
}
@@ -1,6 +1,5 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { claimPaidCheckout } from '@/lib/stripe'
import { executeSoapCommand } from '@/lib/soap'
import { getPaidService } from '@/lib/paid-services'
export const dynamic = 'force-dynamic'
@@ -23,8 +22,8 @@ export default async function ServiceSuccessPage({
if (cfg && session_id) {
const claim = await claimPaidCheckout(session_id)
if (claim) {
const resp = await executeSoapCommand(cfg.command(claim.characterName))
if (resp !== null) okName = claim.characterName
const ok = await cfg.fulfill(claim.characterName, claim.metadata)
if (ok) okName = claim.characterName
}
}
+26
View File
@@ -0,0 +1,26 @@
import { getTranslations, setRequestLocale } from 'next-intl/server'
import { redirect } from '@/i18n/navigation'
import { getSession } from '@/lib/session'
import { getGameCharacters } from '@/lib/characters'
import { getTransferPrice } from '@/lib/prices'
import { TransferForm } from '@/components/TransferForm'
export const dynamic = 'force-dynamic'
export default async function TransferPage({ params }: { params: Promise<{ locale: string }> }) {
const { locale } = await params
setRequestLocale(locale)
const t = await getTranslations('Paid')
const session = await getSession()
if (!session.bnetId) redirect({ href: '/login', locale })
if (!session.username) redirect({ href: '/select-account', locale })
const [chars, price] = await Promise.all([getGameCharacters(session.accountId!), getTransferPrice()])
return (
<main className="mx-auto max-w-3xl px-4 py-8">
<h1 className="mb-6 text-center text-2xl font-bold text-amber-500">{t('transfer.title')}</h1>
<TransferForm characters={chars.map((c) => c.name)} price={price} />
</main>
)
}
@@ -11,13 +11,13 @@ export async function POST(request: Request, { params }: { params: Promise<{ ser
const session = await getSession()
if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
let character = ''
let body: Record<string, string> = {}
try {
const body = await request.json()
character = String(body.character ?? '')
body = await request.json()
} catch {
return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
}
const character = String(body.character ?? '')
if (!character) return Response.json({ success: false, error: 'invalidCharacter' })
const chars = await getGameCharacters(session.accountId)
@@ -25,7 +25,17 @@ export async function POST(request: Request, { params }: { params: Promise<{ ser
return Response.json({ success: false, error: 'invalidCharacter' })
}
const price = await cfg.getPrice()
// Campos extra del servicio (gold_amount, destination_account...) -> metadata
const metadata: Record<string, string> = {}
for (const f of cfg.extraFields) {
const v = String(body[f] ?? '').trim()
if (!v) return Response.json({ success: false, error: 'missingFields' })
metadata[f] = v
}
const price = await cfg.price(metadata)
if (!price || price <= 0) return Response.json({ success: false, error: 'invalidRequest' })
const site = process.env.SITE_URL || ''
const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim() || '0.0.0.0'
@@ -36,9 +46,10 @@ export async function POST(request: Request, { params }: { params: Promise<{ ser
acoreIp: ip,
amount: price,
characterName: character,
productName: cfg.productName(character),
productName: cfg.productName(character, metadata),
successUrl: `${site}/service-success?service=${service}`,
cancelUrl: `${site}/${service}`,
metadata,
})
if (!r.success || !r.url) return Response.json({ success: false, error: 'stripeError' })
return Response.json({ success: true, url: r.url })
+64
View File
@@ -0,0 +1,64 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import type { GoldOption } from '@/lib/prices'
export function GoldForm({ characters, options }: { characters: string[]; options: GoldOption[] }) {
const t = useTranslations('Services')
const tp = useTranslations('Paid')
const [character, setCharacter] = useState('')
const [amount, setAmount] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || !character || !amount) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/character/gold/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ character, gold_amount: amount }),
})
const data: { success?: boolean; url?: string } = await res.json()
if (data.success && data.url) window.location.href = data.url
else {
setError(t('genericError'))
setBusy(false)
}
} catch {
setError(t('genericError'))
setBusy(false)
}
}
const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
if (characters.length === 0) return <p className="text-amber-200/70">{t('noCharactersYet')}</p>
return (
<div className="mx-auto max-w-sm text-center">
<form onSubmit={handleSubmit} className="space-y-3">
<select value={character} onChange={(e) => setCharacter(e.target.value)} required className={field}>
<option value="" disabled>{t('selectCharacter')}</option>
{characters.map((c) => <option key={c} value={c}>{c}</option>)}
</select>
<select value={amount} onChange={(e) => setAmount(e.target.value)} required className={field}>
<option value="" disabled>{tp('gold.selectAmount')}</option>
{options.map((o) => (
<option key={o.gold_amount} value={o.gold_amount}>
{tp('gold.option', { amount: o.gold_amount, price: o.price })}
</option>
))}
</select>
<button type="submit" disabled={busy || !character || !amount} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('processing') : tp('gold.buy')}
</button>
</form>
{error && <p className="mt-3 text-red-400">{error}</p>}
</div>
)
}
+1 -1
View File
@@ -17,7 +17,7 @@ export async function ServicePageContent({ service, locale }: { service: string;
if (!session.bnetId) redirect({ href: '/login', locale })
if (!session.username) redirect({ href: '/select-account', locale })
const [chars, price] = await Promise.all([getGameCharacters(session.accountId!), cfg!.getPrice()])
const [chars, price] = await Promise.all([getGameCharacters(session.accountId!), cfg!.price({})])
return (
<main className="mx-auto max-w-3xl px-4 py-8">
+56
View File
@@ -0,0 +1,56 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
export function TransferForm({ characters, price }: { characters: string[]; price: number }) {
const t = useTranslations('Services')
const tp = useTranslations('Paid')
const [character, setCharacter] = useState('')
const [destination, setDestination] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (busy || !character || !destination.trim()) return
setBusy(true)
setError(null)
try {
const res = await fetch('/api/character/transfer/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ character, destination_account: destination.trim() }),
})
const data: { success?: boolean; url?: string } = await res.json()
if (data.success && data.url) window.location.href = data.url
else {
setError(t('genericError'))
setBusy(false)
}
} catch {
setError(t('genericError'))
setBusy(false)
}
}
const field = 'w-full rounded border border-amber-900/60 bg-[#2c1e14] px-3 py-2'
if (characters.length === 0) return <p className="text-amber-200/70">{t('noCharactersYet')}</p>
return (
<div className="mx-auto max-w-sm text-center">
<form onSubmit={handleSubmit} className="space-y-3">
<select value={character} onChange={(e) => setCharacter(e.target.value)} required className={field}>
<option value="" disabled>{t('selectCharacter')}</option>
{characters.map((c) => <option key={c} value={c}>{c}</option>)}
</select>
<input type="text" placeholder={tp('transfer.destination')} value={destination} onChange={(e) => setDestination(e.target.value)} required className={field} />
<button type="submit" disabled={busy || !character || !destination.trim()} className="w-full rounded bg-amber-600 px-4 py-2 font-semibold text-[#1b120b] disabled:opacity-60">
{busy ? t('processing') : tp('transfer.pay', { price })}
</button>
</form>
{error && <p className="mt-3 text-red-400">{error}</p>}
</div>
)
}
+53 -15
View File
@@ -1,44 +1,82 @@
import { executeSoapCommand } from './soap'
import { db, DB } from './db'
import {
getRenamePrice,
getCustomizePrice,
getChangeRacePrice,
getChangeFactionPrice,
getLevelUpPrice,
getTransferPrice,
goldPriceFor,
} from './prices'
type Meta = Record<string, string>
export interface PaidServiceConfig {
command: (character: string) => string
getPrice: () => Promise<number>
productName: (character: string) => string
price: (meta: Meta) => Promise<number>
productName: (character: string, meta: Meta) => string
fulfill: (character: string, meta: Meta) => Promise<boolean>
extraFields: string[] // campos (además de character) que el form envía y se guardan en metadata
}
async function soapFulfill(command: string): Promise<boolean> {
return (await executeSoapCommand(command)) !== null
}
async function addGold(character: string, goldAmount: number): Promise<boolean> {
try {
await db(DB.characters).query('UPDATE characters SET money = money + ? WHERE name = ?', [
goldAmount * 10000,
character,
])
return true
} catch {
return false
}
}
// Servicios de personaje de pago. slug = ruta (/rename, /customize, ...) y clave de
// catálogo (Paid.<slug>). Comandos SOAP tal cual las success views de Django.
export const PAID_SERVICES: Record<string, PaidServiceConfig> = {
rename: {
command: (c) => `.char rename ${c}`,
getPrice: getRenamePrice,
price: () => getRenamePrice(),
productName: (c) => `Renombrar personaje: ${c}`,
fulfill: (c) => soapFulfill(`.char rename ${c}`),
extraFields: [],
},
customize: {
command: (c) => `.char customi ${c}`,
getPrice: getCustomizePrice,
price: () => getCustomizePrice(),
productName: (c) => `Personalizar personaje: ${c}`,
fulfill: (c) => soapFulfill(`.char customi ${c}`),
extraFields: [],
},
'change-race': {
command: (c) => `.char changerace ${c}`,
getPrice: getChangeRacePrice,
price: () => getChangeRacePrice(),
productName: (c) => `Cambiar raza: ${c}`,
fulfill: (c) => soapFulfill(`.char changerace ${c}`),
extraFields: [],
},
'change-faction': {
command: (c) => `.char changef ${c}`,
getPrice: getChangeFactionPrice,
price: () => getChangeFactionPrice(),
productName: (c) => `Cambiar facción: ${c}`,
fulfill: (c) => soapFulfill(`.char changef ${c}`),
extraFields: [],
},
'level-up': {
command: (c) => `.char level ${c} 80`,
getPrice: getLevelUpPrice,
price: () => getLevelUpPrice(),
productName: (c) => `Subir a nivel 80: ${c}`,
fulfill: (c) => soapFulfill(`.char level ${c} 80`),
extraFields: [],
},
gold: {
price: (m) => goldPriceFor(Number(m.gold_amount)),
productName: (c, m) => `Aumentar el Oro: ${m.gold_amount} al Personaje: ${c}`,
fulfill: (c, m) => addGold(c, Number(m.gold_amount)),
extraFields: ['gold_amount'],
},
transfer: {
price: () => getTransferPrice(),
productName: (c, m) => `Transferir ${c} a la cuenta ${m.destination_account}`,
fulfill: (c, m) => soapFulfill(`.char changeaccount ${m.destination_account} ${c}`),
extraFields: ['destination_account'],
},
}
+23
View File
@@ -15,3 +15,26 @@ export const getCustomizePrice = () => priceFrom('home_customizeprice', 1.0)
export const getChangeRacePrice = () => priceFrom('home_changeraceprice', 10.0)
export const getChangeFactionPrice = () => priceFrom('home_changefactionprice', 10.0)
export const getLevelUpPrice = () => priceFrom('home_levelupprice', 10.0)
export const getTransferPrice = () => priceFrom('home_transferprice', 10.0)
export interface GoldOption {
gold_amount: number
price: number
}
export async function getGoldOptions(): Promise<GoldOption[]> {
try {
const [rows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT gold_amount, price FROM home_goldprice ORDER BY gold_amount',
)
return rows.map((r) => ({ gold_amount: r.gold_amount, price: Number(r.price) }))
} catch {
return []
}
}
/** Precio de una cantidad de oro concreta (0 si no existe esa opción). */
export async function goldPriceFor(goldAmount: number): Promise<number> {
const opts = await getGoldOptions()
return opts.find((o) => o.gold_amount === goldAmount)?.price ?? 0
}
+15 -3
View File
@@ -25,6 +25,7 @@ export interface CheckoutParams {
successUrl: string
cancelUrl: string
currency?: string
metadata?: Record<string, string>
}
/** Crea una sesión de pago Stripe y registra el StripeLog. Devuelve la URL de checkout. */
@@ -49,6 +50,7 @@ export async function createCheckoutSession(
mode: 'payment',
success_url: successUrl,
cancel_url: p.cancelUrl,
metadata: p.metadata,
})
const mode = (process.env.STRIPE_SECRET_KEY || '').startsWith('sk_live') ? 'live' : 'test'
await db(DB.default).query(
@@ -67,8 +69,18 @@ export async function createCheckoutSession(
* (evita re-entregas). Devuelve el character_name del log o null. (Port de
* require_paid_stripe.)
*/
export async function claimPaidCheckout(sessionId: string): Promise<{ characterName: string } | null> {
if (!(await isSessionPaid(sessionId))) return null
export async function claimPaidCheckout(
sessionId: string,
): Promise<{ characterName: string; metadata: Record<string, string> } | null> {
if (!sessionId) return null
let metadata: Record<string, string> = {}
try {
const s = await stripe.checkout.sessions.retrieve(sessionId)
if (s.payment_status !== 'paid') return null
metadata = (s.metadata as Record<string, string>) ?? {}
} catch {
return null
}
const [rows] = await db(DB.default).query<RowDataPacket[]>(
'SELECT id, character_name, fulfilled FROM home_stripelog WHERE session_id = ?',
[sessionId],
@@ -76,5 +88,5 @@ export async function claimPaidCheckout(sessionId: string): Promise<{ characterN
const log = rows[0]
if (!log || log.fulfilled) return null
await db(DB.default).query('UPDATE home_stripelog SET fulfilled = 1 WHERE id = ?', [log.id])
return { characterName: log.character_name }
return { characterName: log.character_name, metadata }
}
+14 -1
View File
@@ -162,6 +162,19 @@
"pay": "Level up to 80 for {price} €",
"success": "Character {name} has been leveled to 80."
},
"error": "The operation could not be completed. If you were charged, contact support."
"error": "The operation could not be completed. If you were charged, contact support.",
"gold": {
"title": "Buy gold",
"buy": "Buy gold",
"selectAmount": "Select the amount",
"option": "{amount} gold — {price} €",
"success": "Gold has been added to character {name}."
},
"transfer": {
"title": "Transfer character",
"pay": "Transfer for {price} €",
"destination": "Destination account",
"success": "Character {name} has been transferred to the destination account."
}
}
}
+14 -1
View File
@@ -162,6 +162,19 @@
"pay": "Subir a nivel 80 por {price} €",
"success": "El personaje {name} ha sido subido al nivel 80."
},
"error": "No se pudo completar la operación. Si se te ha cobrado, contacta con soporte."
"error": "No se pudo completar la operación. Si se te ha cobrado, contacta con soporte.",
"gold": {
"title": "Adquirir oro",
"buy": "Comprar oro",
"selectAmount": "Selecciona la cantidad",
"option": "{amount} oro — {price} €",
"success": "El oro ha sido añadido al personaje {name}."
},
"transfer": {
"title": "Transferir personaje",
"pay": "Transferir por {price} €",
"destination": "Cuenta de destino",
"success": "El personaje {name} ha sido transferido a la cuenta de destino."
}
}
}