Mitsuki / server.js
Aisnsio's picture
オンラインショップ(カート・飲食券・月額サブスク / Stripe) (part 2)
0e7f115 verified
Raw History Blame Contribute Delete
14.8 kB
// 充輝亭 web server: serves the static site + the in-site shop API (Stripe, no SDK).
// Env: STRIPE_SECRET_KEY, STRIPE_PUBLISHABLE_KEY (payments), STAFF_PIN (staff ticket/member check), PORT.
// Stripe is the order database: tickets live in PaymentIntent metadata, members are Stripe subscriptions,
// so an HF rebuild loses nothing.
'use strict';
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const ROOT = __dirname;
const PORT = Number(process.env.PORT || 7860);
const SK = process.env.STRIPE_SECRET_KEY || '';
const PK = process.env.STRIPE_PUBLISHABLE_KEY || '';
const STAFF_PIN = process.env.STAFF_PIN || '';
const STRIPE_API = process.env.STRIPE_API_BASE || 'https://api.stripe.com';
const CATALOG = JSON.parse(fs.readFileSync(path.join(ROOT, 'shop/catalog.json'), 'utf8'));
const PRODUCTS = new Map(CATALOG.products.map(p => [p.id, p]));
const PLANS = new Map(CATALOG.plans.map(p => [p.id, p]));
const TICKET_DAYS = 183; // 有効期限 ご購入日から6ヶ月
const MAX_QTY = 20, MAX_LINES = 30;
// ---------- Stripe over fetch (JPY is zero-decimal: amounts are yen as-is) ----------
function form(obj, prefix, out = []) {
for (const [k, v] of Object.entries(obj)) {
if (v === undefined || v === null) continue;
const key = prefix ? `${prefix}[${k}]` : k;
if (typeof v === 'object') form(v, key, out);
else out.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(v)));
}
return out.join('&');
}
async function stripe(method, url, body) {
const r = await fetch(STRIPE_API + url, {
method,
headers: { Authorization: `Bearer ${SK}`, 'Content-Type': 'application/x-www-form-urlencoded', 'Stripe-Version': '2024-06-20' },
body: body ? form(body) : undefined,
});
const j = await r.json().catch(() => ({}));
if (!r.ok) { const e = new Error(j.error?.message || `stripe ${r.status}`); e.status = r.status; throw e; }
return j;
}
// ---------- helpers ----------
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
'.webp': 'image/webp', '.gif': 'image/gif', '.ico': 'image/x-icon', '.xml': 'application/xml; charset=utf-8', '.txt': 'text/plain; charset=utf-8',
'.woff2': 'font/woff2', '.mp4': 'video/mp4' };
function send(res, code, obj) {
res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
res.end(JSON.stringify(obj));
}
function readBody(req) {
return new Promise((ok, bad) => {
let n = 0; const c = [];
req.on('data', d => { n += d.length; if (n > 64 * 1024) { bad(new Error('too large')); req.destroy(); } else c.push(d); });
req.on('end', () => { try { ok(c.length ? JSON.parse(Buffer.concat(c).toString('utf8')) : {}); } catch { bad(new Error('bad json')); } });
});
}
function origin(req) {
const proto = (req.headers['x-forwarded-proto'] || 'http').split(',')[0];
return `${proto}://${req.headers['x-forwarded-host'] || req.headers.host}`;
}
function ticketCode() { // 8 chars, no look-alikes (0/O, 1/I)
const A = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; const b = crypto.randomBytes(8);
return Array.from(b, x => A[x % A.length]).join('').replace(/^(.{4})/, '$1-');
}
const pinOk = pin => STAFF_PIN && typeof pin === 'string' && pin.length === STAFF_PIN.length &&
crypto.timingSafeEqual(Buffer.from(pin), Buffer.from(STAFF_PIN));
const fails = new Map(); // ip -> [count, firstTs] brute-force guard for the staff PIN
function staffGuard(req) {
const ip = (req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
const f = fails.get(ip); if (f && Date.now() - f[1] < 15 * 60e3 && f[0] >= 8) return { ip, locked: true };
return { ip, locked: false };
}
function staffFail(ip) { const f = fails.get(ip); if (!f || Date.now() - f[1] > 15 * 60e3) fails.set(ip, [1, Date.now()]); else f[0]++; }
// ticket items are stored compactly in PaymentIntent metadata: "id:qty:used,id:qty:used"
const packItems = items => items.map(i => `${i.id}:${i.qty}:${i.used || 0}`).join(',');
const unpackItems = s => (s || '').split(',').filter(Boolean).map(x => { const [id, q, u] = x.split(':'); const p = PRODUCTS.get(id);
return { id, name: p ? p.name : id, price: p ? p.price : 0, qty: +q, used: +u || 0 }; });
function ticketView(pi) {
const created = pi.created * 1000, expires = created + TICKET_DAYS * 864e5;
return { code: pi.metadata.ticket, paid: pi.status === 'succeeded', amount: pi.amount, created, expires,
expired: Date.now() > expires, items: unpackItems(pi.metadata.items), buyer: pi.metadata.buyer || '' };
}
// ---------- API ----------
async function api(req, res, url) {
const p = url.pathname;
if (p === '/api/shop/config') return send(res, 200, { enabled: !!(SK && PK), publishableKey: PK || null });
if (!SK || !PK) return send(res, 503, { error: 'オンライン決済は現在準備中です。お電話(050-1793-6755)でご注文ください。' });
// cart -> embedded Checkout (one-time, 飲食券)
if (p === '/api/checkout' && req.method === 'POST') {
const b = await readBody(req);
const lines = Array.isArray(b.items) ? b.items.slice(0, MAX_LINES) : [];
const items = [];
for (const l of lines) {
const pr = PRODUCTS.get(String(l.id)); const qty = Math.floor(Number(l.qty));
if (!pr || !(qty >= 1 && qty <= MAX_QTY)) return send(res, 400, { error: '商品または数量が正しくありません。' });
const ex = items.find(i => i.id === pr.id); if (ex) ex.qty = Math.min(MAX_QTY, ex.qty + qty); else items.push({ id: pr.id, qty });
}
if (!items.length) return send(res, 400, { error: 'カートが空です。' });
const packed = packItems(items);
if (packed.length > 480) return send(res, 400, { error: '一度にご購入いただける品目数を超えています。分けてご購入ください。' });
const code = ticketCode();
const s = await stripe('POST', '/v1/checkout/sessions', {
mode: 'payment', ui_mode: 'embedded', locale: 'ja', currency: 'jpy',
return_url: `${origin(req)}/shop/complete.html?session_id={CHECKOUT_SESSION_ID}`,
line_items: items.map(i => { const pr = PRODUCTS.get(i.id); return { quantity: i.qty, price_data: { currency: 'jpy', unit_amount: pr.price,
product_data: { name: `飲食券|${pr.name}`, description: '居酒屋 充輝 飲食券(ご購入日から6ヶ月有効・1枚につき1品)', metadata: { item: pr.id } } } }; }),
customer_creation: 'always',
payment_intent_data: { description: `充輝亭 飲食券 ${code}`, metadata: { kind: 'ticket', ticket: code, items: packed } },
metadata: { kind: 'ticket', ticket: code },
});
return send(res, 200, { clientSecret: s.client_secret });
}
// subscription plan -> embedded Checkout (subscription)
if (p === '/api/subscribe' && req.method === 'POST') {
const b = await readBody(req); const pl = PLANS.get(String(b.plan));
if (!pl) return send(res, 400, { error: 'プランが正しくありません。' });
const s = await stripe('POST', '/v1/checkout/sessions', {
mode: 'subscription', ui_mode: 'embedded', locale: 'ja', currency: 'jpy',
return_url: `${origin(req)}/shop/complete.html?session_id={CHECKOUT_SESSION_ID}`,
line_items: [{ quantity: 1, price_data: { currency: 'jpy', unit_amount: pl.price, recurring: { interval: 'month' },
product_data: { name: `充輝の月額サブスク|${pl.name}`, metadata: { plan: pl.id } } } }],
custom_text: { submit: { message: `お申し込みにより会員規約(${origin(req)}/index.html#sub-terms)に同意したものとみなします。ご入会は20歳以上の方に限ります。解約は次回決済日の3日前までに。` } },
subscription_data: { description: `充輝の月額サブスク ${pl.name}`, metadata: { kind: 'member', plan: pl.id } },
metadata: { kind: 'member', plan: pl.id },
});
return send(res, 200, { clientSecret: s.client_secret });
}
// completion page: what was bought (ticket code / membership)
if (p === '/api/order' && req.method === 'GET') {
const id = url.searchParams.get('session_id') || '';
if (!/^cs_(test|live)_[A-Za-z0-9]+$/.test(id)) return send(res, 400, { error: 'bad session' });
const s = await stripe('GET', `/v1/checkout/sessions/${id}?expand[]=payment_intent&expand[]=subscription`);
const base = { status: s.status, paid: s.payment_status === 'paid', email: s.customer_details?.email || '', name: s.customer_details?.name || '' };
if (s.mode === 'payment' && s.payment_intent) return send(res, 200, { ...base, kind: 'ticket', ticket: ticketView(s.payment_intent) });
if (s.mode === 'subscription' && s.subscription) {
const pl = PLANS.get(s.subscription.metadata?.plan);
return send(res, 200, { ...base, kind: 'member', plan: pl ? pl.name : '', member: s.subscription.id.slice(-8).toUpperCase(),
subStatus: s.subscription.status, canManage: true });
}
return send(res, 200, base);
}
// member self-service (Stripe customer portal), reachable from the completion page
if (p === '/api/portal' && req.method === 'POST') {
const b = await readBody(req); const id = String(b.session_id || '');
if (!/^cs_(test|live)_[A-Za-z0-9]+$/.test(id)) return send(res, 400, { error: 'bad session' });
const s = await stripe('GET', `/v1/checkout/sessions/${id}`);
if (s.mode !== 'subscription' || !s.customer) return send(res, 400, { error: 'not a membership' });
const ps = await stripe('POST', '/v1/billing_portal/sessions', { customer: s.customer, return_url: `${origin(req)}/shop/complete.html?session_id=${id}`, locale: 'ja' });
return send(res, 200, { url: ps.url });
}
// ---- staff: ticket lookup / redeem, member check (STAFF_PIN) ----
if (p.startsWith('/api/staff/') && req.method === 'POST') {
const g = staffGuard(req);
if (g.locked) return send(res, 429, { error: '試行回数が多すぎます。15分後にお試しください。' });
const b = await readBody(req);
if (!pinOk(b.pin)) { staffFail(g.ip); return send(res, 401, { error: 'PINが違います。' }); }
if (p === '/api/staff/login') return send(res, 200, { ok: true });
if (p === '/api/staff/ticket' || p === '/api/staff/redeem') {
const code = String(b.code || '').toUpperCase().replace(/[^A-Z0-9]/g, '').replace(/^(.{4})/, '$1-');
if (!/^[A-Z0-9]{4}-[A-Z0-9]{4}$/.test(code)) return send(res, 400, { error: 'コードは8文字です(例 ABCD-2345)。' });
const r = await stripe('GET', `/v1/payment_intents/search?query=${encodeURIComponent(`metadata['ticket']:'${code}'`)}`);
const pi = (r.data || []).find(x => x.status === 'succeeded');
if (!pi) return send(res, 404, { error: 'この飲食券は見つかりません(購入直後は1分ほどかかる場合があります)。' });
if (p === '/api/staff/redeem') {
const t = ticketView(pi);
if (t.expired) return send(res, 400, { error: '有効期限切れの飲食券です。' });
const items = unpackItems(pi.metadata.items); const it = items.find(i => i.id === String(b.item));
if (!it) return send(res, 400, { error: '品目が見つかりません。' });
const n = Math.floor(Number(b.n || 1));
if (!(n >= 1) || it.used + n > it.qty) return send(res, 400, { error: '残り枚数を超えています。' });
it.used += n;
const up = await stripe('POST', `/v1/payment_intents/${pi.id}`, { metadata: { items: packItems(items), last_redeemed: new Date().toISOString() } });
return send(res, 200, { ticket: ticketView(up) });
}
return send(res, 200, { ticket: ticketView(pi) });
}
if (p === '/api/staff/member') {
const email = String(b.email || '').trim().toLowerCase();
if (!/^\S+@\S+\.\S+$/.test(email)) return send(res, 400, { error: 'メールアドレスを入力してください。' });
const cs = await stripe('GET', `/v1/customers?email=${encodeURIComponent(email)}&limit=10`);
const subs = [];
for (const c of cs.data || []) {
const ss = await stripe('GET', `/v1/subscriptions?customer=${c.id}&status=all&limit=10`);
for (const s of ss.data || []) if (s.metadata?.kind === 'member') {
const pl = PLANS.get(s.metadata.plan);
subs.push({ plan: pl ? pl.name : s.metadata.plan, status: s.status, member: s.id.slice(-8).toUpperCase(), name: c.name || '',
periodEnd: (s.current_period_end || s.items?.data?.[0]?.current_period_end || 0) * 1000, cancelAtEnd: !!s.cancel_at_period_end });
}
}
return send(res, 200, { members: subs });
}
}
return send(res, 404, { error: 'not found' });
}
// ---------- static ----------
function serveStatic(req, res, url) {
let rel = decodeURIComponent(url.pathname);
if (rel.endsWith('/')) rel += 'index.html';
const file = path.normalize(path.join(ROOT, rel));
if (!file.startsWith(ROOT + path.sep) || /(^|[\\/])(\.|server\.js|Dockerfile|node_modules)/.test(path.relative(ROOT, file))) { res.writeHead(404); return res.end('Not found'); }
fs.stat(file, (err, st) => {
if (err || !st.isFile()) {
if (!path.extname(rel)) { res.writeHead(302, { Location: rel + '/' }); return res.end(); }
res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' }); return res.end('<h1>404</h1><p><a href="/">充輝亭 トップへ</a></p>');
}
const ext = path.extname(file).toLowerCase();
const long = /^\/(img|sq|menu|brand)\//.test(rel);
res.writeHead(200, { 'Content-Type': MIME[ext] || 'application/octet-stream', 'Content-Length': st.size,
'Cache-Control': long ? 'public, max-age=86400' : 'no-cache', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' });
if (req.method === 'HEAD') return res.end();
fs.createReadStream(file).pipe(res);
});
}
http.createServer(async (req, res) => {
const url = new URL(req.url, 'http://x');
try {
if (url.pathname.startsWith('/api/')) return await api(req, res, url);
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405); return res.end(); }
serveStatic(req, res, url);
} catch (e) {
console.error(url.pathname, e.message);
if (!res.headersSent) send(res, e.status && e.status < 500 ? 400 : 502, { error: '決済サーバーとの通信に失敗しました。時間をおいてお試しください。' });
}
}).listen(PORT, () => console.log(`mitsuki on :${PORT} payments=${!!(SK && PK)} staff=${!!STAFF_PIN}`));