// Worker de cobro con PayPal + entrega digital para gypsyjazz.online // El precio NUNCA viene del navegador: se toma del catalogo embebido. const catalogo = { "7683": { "nombre": "Sergio Repiso Spanish Classical 1964 mint", "precio_usd": "2850.00" }, "8084": { "nombre": "II-V-I Django Licks & Standard forms and Gypsy phrases", "precio_usd": "6.95", "archivo": "licks/II-V-I-Django-Licks.zip", "digital": true }, "8123": { "nombre": "Oscar Alemán - Vida con Swing DVD", "precio_usd": "21.95" }, "8129": { "nombre": "Si tu savais ballad by May Bittel performed by David Reinhardt", "precio_usd": "6.99", "archivo": "licks/Si-tu-savais-ballad.pdf", "digital": true }, "8188": { "nombre": "Django Reinhardt signature licks: Note-for-note classic phrases to apply!", "precio_usd": "6.95", "archivo": "licks/Django-Reinhardt-10-Signature-Licks.pdf", "digital": true }, "9009": { "nombre": "Minor Swing Improvisation Pack: soloing ideas, Licks, arpeggios and phrases!", "precio_usd": "6.95", "archivo": "licks/Minor-Swing-Improvisation-Pack.zip", "digital": true }, "9011": { "nombre": "Minor Blues Improvisation Pack: soloing ideas, licks, arpeggios & phrases!", "precio_usd": "6.95", "archivo": "licks/Minor-Blues-Improvisation-Pack.pdf", "digital": true }, "9501": { "nombre": "Galli gypsy jazz strings PACK of 10 Ball End GSL10 Light 0.10", "precio_usd": "111.00" }, "9778": { "nombre": "Django Reinhardt Guitar tablatures: 10 Classics transcribed with chords and full solos!", "precio_usd": "6.95", "archivo": "licks/Django-Reinhardt-10-Classics-Pack.zip", "digital": true }, "9780": { "nombre": "C major key: Learn and apply the basics! Patterns, forms, diagrams for improvisation.", "precio_usd": "6.95", "archivo": "licks/C-Major-Key-licks.zip", "digital": true }, "10147": { "nombre": "Violin Stradella Mv1411 4/4", "precio_usd": "360.00" }, "10204": { "nombre": "Bass contrabass", "precio_usd": "1450.00" }, "10253": { "nombre": "Montagne Sainte-Geneviève pdf tab - Django's Waltz", "precio_usd": "6.95", "archivo": "licks/Montagne-Sainte-Genevieve-Pack.zip", "digital": true }, "10309": { "nombre": "Busato f hole style archtop django reinhardt gypsy jazz guitar", "precio_usd": "1450.00" }, "10361": { "nombre": "Galli gypsy jazz strings PACK x10 Ball End GSB11 Medium 0.11", "precio_usd": "111.00" }, "10363": { "nombre": "Galli gypsy jazz strings PACK of 5 Sets Ball End GSL10 Light 0.10", "precio_usd": "84.99" }, "10364": { "nombre": "Galli gypsy jazz strings PACK x 5 Sets Ball End GSB11 Medium 0.11", "precio_usd": "84.99" }, // Producto digital: el PDF se entrega por email despues de pagar. "11001": { "nombre": "Oscar Alemán: The Complete Style Guide (PDF)", "precio_usd": "6.95", "archivo": "books/Oscar-Aleman-The-Complete-Style-Guide.pdf", "digital": true } }; const ALLOWED_ORIGINS = ["https://gypsyjazz.online", "https://www.gypsyjazz.online", "https://gypsyjazz-test.pages.dev", "https://main.gypsyjazz-test.pages.dev"]; const MAX_QTY = 1; const FROM_EMAIL = "Gypsy Jazz "; const SALES_EMAIL = "sales@gypsyjazz.online"; // Copia oculta de cada confirmación. En pruebas va a joseiacona@gmail.com; antes de producción volver a SALES_EMAIL. const COPY_EMAIL = "joseiacona@gmail.com"; const LINK_DAYS = 7; const MAX_DOWNLOADS = 5; function cors(origin) { const allowed = ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0]; return { "Access-Control-Allow-Origin": allowed, "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Content-Type", "Vary": "Origin" }; } function json(data, status, origin) { return new Response(JSON.stringify(data), { status, headers: Object.assign({ "Content-Type": "application/json" }, cors(origin)) }); } function esc(s) { return String(s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); } function paypalBase(env) { return env.PAYPAL_ENV === "live" ? "https://api-m.paypal.com" : "https://api-m.sandbox.paypal.com"; } async function accessToken(env) { const creds = btoa(env.PAYPAL_CLIENT_ID + ":" + env.PAYPAL_CLIENT_SECRET); const res = await fetch(paypalBase(env) + "/v1/oauth2/token", { method: "POST", headers: { Authorization: "Basic " + creds, "Content-Type": "application/x-www-form-urlencoded" }, body: "grant_type=client_credentials" }); if (!res.ok) throw new Error("PayPal auth failed: " + res.status); return (await res.json()).access_token; } function buildCart(items) { if (!Array.isArray(items) || items.length === 0 || items.length > 10) return { error: "Carrito inválido" }; const lines = []; let total = 0; for (const it of items) { const prod = catalogo[String(it.id)]; const qty = Number(it.qty === undefined ? 1 : it.qty); if (!prod) return { error: "Producto no disponible: " + it.id }; if (!Number.isInteger(qty) || qty < 1 || qty > MAX_QTY) return { error: "Cantidad inválida para " + prod.nombre }; lines.push({ id: String(it.id), nombre: prod.nombre, qty, unit: prod.precio_usd, digital: !!prod.digital, archivo: prod.archivo || null }); total += Number(prod.precio_usd) * qty; } return { lines, total: total.toFixed(2) }; } function b64url(bytes) { let s = ""; for (const b of bytes) s += String.fromCharCode(b); return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function b64urlDecode(str) { const s = atob(str.replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(s, (c) => c.charCodeAt(0)); } async function hmacKey(env) { return crypto.subtle.importKey("raw", new TextEncoder().encode(env.DOWNLOAD_SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]); } async function signToken(env, payload) { const body = b64url(new TextEncoder().encode(JSON.stringify(payload))); const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await hmacKey(env), new TextEncoder().encode(body))); return body + "." + b64url(sig); } async function verifyToken(env, token) { const parts = String(token).split("."); if (parts.length !== 2) return null; const ok = await crypto.subtle.verify("HMAC", await hmacKey(env), b64urlDecode(parts[1]), new TextEncoder().encode(parts[0])); if (!ok) return null; const payload = JSON.parse(new TextDecoder().decode(b64urlDecode(parts[0]))); if (!payload || Date.now() > payload.e) return null; return payload; } async function saveOrder(env, order) { await env.STORE.put("orders/" + order.id + ".json", JSON.stringify(order), { httpMetadata: { contentType: "application/json" } }); } async function getOrder(env, id) { const obj = await env.STORE.get("orders/" + id + ".json"); return obj ? obj.json() : null; } async function makeLinks(env, orderId, digitalLines) { const expiry = Date.now() + LINK_DAYS * 24 * 60 * 60 * 1000; const links = []; for (const l of digitalLines) { const token = await signToken(env, { o: orderId, p: l.id, e: expiry }); links.push({ nombre: l.nombre, url: env.BASE_URL + "/download/" + token }); } return links; } async function sendEmail(env, to, subject, html) { if (!env.RESEND_API_KEY) throw new Error("RESEND_API_KEY no configurada"); if (!to) throw new Error("Comprador sin email"); const res = await fetch("https://api.resend.com/emails", { method: "POST", headers: { Authorization: "Bearer " + env.RESEND_API_KEY, "Content-Type": "application/json" }, body: JSON.stringify({ from: FROM_EMAIL, to: [to], bcc: [COPY_EMAIL], subject, html }) }); if (!res.ok) throw new Error("Resend respondió " + res.status + ": " + (await res.text())); } async function sendConfirmation(env, to, orderId, lines, total, links) { const rows = lines.map((l) => "" + esc(l.nombre) + "USD " + esc(l.unit) + "").join(""); let downloads = ""; if (links.length) { downloads = "

Descargas

Tus enlaces son válidos por " + LINK_DAYS + " días y permiten hasta " + MAX_DOWNLOADS + " descargas cada uno.

"; } const html = "

¡Gracias por tu compra!

Recibimos tu pago. Número de orden: " + esc(orderId) + "

" + rows + "
TotalUSD " + esc(total) + "
" + downloads + "

Si tenés alguna consulta, respondé a este correo o escribinos a " + SALES_EMAIL + ".

"; await sendEmail(env, to, "Confirmación de tu pedido " + orderId, html); } async function createOrder(request, env, origin) { const body = await request.json().catch(() => null); const cart = buildCart(body && body.items); if (cart.error) return json({ error: cart.error }, 400, origin); const token = await accessToken(env); const res = await fetch(paypalBase(env) + "/v2/checkout/orders", { method: "POST", headers: { Authorization: "Bearer " + token, "Content-Type": "application/json" }, body: JSON.stringify({ intent: "CAPTURE", purchase_units: [{ reference_id: cart.lines.map((l) => l.id).join(","), description: cart.lines.map((l) => l.nombre).join(" + ").slice(0, 127), amount: { currency_code: "USD", value: cart.total, breakdown: { item_total: { currency_code: "USD", value: cart.total } } }, items: cart.lines.map((l) => ({ name: l.nombre.slice(0, 127), quantity: String(l.qty), unit_amount: { currency_code: "USD", value: l.unit }, category: l.digital ? "DIGITAL_GOODS" : "PHYSICAL_GOODS" })) }] }) }); const data = await res.json(); if (!res.ok) { console.error("PayPal create-order", res.status, JSON.stringify(data)); return json({ error: "PayPal rechazó la orden" }, 502, origin); } return json({ id: data.id }, 200, origin); } // Captura una orden aprobada. Usado por el boton (capture-order) y por el webhook CHECKOUT.ORDER.APPROVED. async function captureOrder(orderID, env, origin) { if (!orderID || !/^[A-Z0-9]{10,30}$/.test(orderID)) return json({ error: "orderID inválido" }, 400, origin); const token = await accessToken(env); const headers = { Authorization: "Bearer " + token, "Content-Type": "application/json" }; const check = await fetch(paypalBase(env) + "/v2/checkout/orders/" + orderID, { headers }); const order = await check.json(); const unit = order && order.purchase_units && order.purchase_units[0]; const expectedTotal = unit && unit.amount && unit.amount.value; const currency = unit && unit.amount && unit.amount.currency_code; if (!check.ok || currency !== "USD" || !expectedTotal) return json({ error: "No se pudo verificar la orden" }, 400, origin); const ids = (unit.reference_id || "").split(",").filter(Boolean); const recomputed = buildCart(ids.map((id) => ({ id, qty: 1 }))); if (recomputed.error || recomputed.total !== expectedTotal) return json({ error: "El monto de la orden no coincide con el catálogo" }, 400, origin); // Idempotencia: si PayPal ya la tiene capturada (botón o webhook anterior) o ya se entregó, no se vuelve a entregar ni a enviar email. if (order.status === "COMPLETED") return json({ status: "COMPLETED", id: orderID, duplicate: true }, 200, origin); if (await getOrder(env, orderID)) return json({ status: "COMPLETED", id: orderID, duplicate: true }, 200, origin); const cap = await fetch(paypalBase(env) + "/v2/checkout/orders/" + orderID + "/capture", { method: "POST", headers }); const data = await cap.json(); const status = data && data.status; if (!cap.ok || status !== "COMPLETED") { console.error("PayPal capture", orderID, cap.status, JSON.stringify(data)); return json({ error: "El pago no se completó", status }, 402, origin); } const buyer = (order.payer && order.payer.email_address) || null; const digitalLines = recomputed.lines.filter((l) => l.digital); let links = []; // El pago ya está cobrado: guardamos primero y luego entregamos. Cualquier error queda logueado con el orderID. try { if (digitalLines.length) { links = await makeLinks(env, orderID, digitalLines); await saveOrder(env, { id: orderID, email: buyer, created: new Date().toISOString(), items: digitalLines.map((l) => ({ id: l.id, archivo: l.archivo, downloads: 0 })) }); } } catch (e) { console.error("ENTREGA FALLIDA (pagado)", orderID, String(e)); } try { await sendConfirmation(env, buyer, orderID, recomputed.lines, recomputed.total, links); } catch (e) { console.error("EMAIL FALLIDO (pagado)", orderID, buyer, String(e)); } return json({ status, id: data.id, links: links.length ? links : undefined }, 200, origin); } // GET /download/: valida firma, vencimiento y cantidad de descargas, luego entrega el archivo desde R2. async function download(env, token) { const payload = await verifyToken(env, token).catch(() => null); if (!payload) return new Response("Enlace inválido o vencido.", { status: 403 }); const order = await getOrder(env, payload.o); if (!order) return new Response("Pedido no encontrado.", { status: 404 }); const item = order.items.find((i) => i.id === payload.p); if (!item) return new Response("Producto no encontrado en el pedido.", { status: 404 }); if (item.downloads >= MAX_DOWNLOADS) return new Response("Se alcanzó el límite de descargas.", { status: 403 }); const obj = await env.STORE.get(item.archivo); if (!obj) { console.error("ARCHIVO FALTANTE en R2", item.archivo, payload.o); return new Response("Archivo no disponible.", { status: 404 }); } item.downloads += 1; await saveOrder(env, order); const name = item.archivo.split("/").pop(); const type = name.endsWith(".zip") ? "application/zip" : "application/pdf"; return new Response(obj.body, { headers: { "Content-Type": type, "Content-Disposition": 'attachment; filename="' + name + '"', "Cache-Control": "private, no-store" } }); } export default { async fetch(request, env) { const origin = request.headers.get("Origin") || ""; const url = new URL(request.url); if (request.method === "GET" && url.pathname.startsWith("/download/")) { return download(env, url.pathname.slice("/download/".length)); } // Webhook de PayPal: si el cliente aprobó la orden pero nunca llegó a capturarse (se cerró el navegador), la capturamos acá. // No confiamos en el cuerpo del webhook: captureOrder vuelve a consultar la orden en PayPal y verifica el monto. if (request.method === "POST" && url.pathname === "/webhook/paypal") { const ev = await request.json().catch(() => null); if (ev && ev.event_type === "CHECKOUT.ORDER.APPROVED" && ev.resource && ev.resource.id) { try { await captureOrder(ev.resource.id, env, ""); } catch (e) { console.error("WEBHOOK captura fallida", ev.resource.id, String(e)); } } return new Response("ok", { status: 200 }); } if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: cors(origin) }); if (request.method !== "POST") return json({ error: "Método no permitido" }, 405, origin); if (!ALLOWED_ORIGINS.includes(origin)) return json({ error: "Origen no permitido" }, 403, origin); try { if (url.pathname === "/api/paypal/create-order") return await createOrder(request, env, origin); if (url.pathname === "/api/paypal/capture-order") { const body = await request.json().catch(() => null); return await captureOrder(body && body.orderID, env, origin); } return json({ error: "No encontrado" }, 404, origin); } catch (err) { console.error("ERROR INTERNO", String(err && err.stack || err)); return json({ error: "Error interno" }, 500, origin); } } };