async function handleCompletedCheckout(session) {
const { authforge_app_id, license_duration, max_hwid_slots } =
session.metadata;
// Idempotency: check if we've already created a license for this session
const existingLicense = await db.getLicenseByStripeSession(session.id);
if (existingLicense) {
console.log("License already created for session", session.id);
return;
}
// Calculate expiration
const expiresAt = license_duration
? new Date(Date.now() + parseInt(license_duration) * 86400000).toISOString()
: null;
// Create license via AuthForge API
const response = await fetch("https://api.authforge.cc/v1/licenses", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.AUTHFORGE_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
appId: authforge_app_id,
quantity: 1,
expiresAt,
maxHwidSlots: parseInt(max_hwid_slots) || 1,
label: `Stripe session ${session.id}`,
}),
});
const data = await response.json();
const licenseKey = data.licenses[0].licenseKey;
// Store the mapping in your database
await db.saveLicense({
stripeSessionId: session.id,
customerEmail: session.customer_details.email,
licenseKey,
});
// Deliver the key to the customer
await sendLicenseEmail(session.customer_details.email, licenseKey);
}