I keep getting an error that I just can’t figure out. my website is subscription based, uses a firebase and JavaScript backend and stripe for payments. just deployed and when I try to subscribe I get the error in console:
createSubscription:1
Failed to load resource: the server responded with a status of 500 ()
I am not a coder so I probably screwed up somewhere. This is my index.js
const functions = require("firebase-functions/v1");
const admin = require("firebase-admin");
const stripe = require("stripe")("your-secret-code-here");
const cors = require("cors")({ origin: "https://thenerdfinder.com" });
admin.initializeApp();
// Create Subscription
exports.createSubscription = functions.https.onRequest((req, res) => {
cors(req, res, async () => {
if (req.method === 'OPTIONS') {
return res.status(204).send('');
}
const { email, uid } = req.body;
if (!email || !uid) {
console.log("Missing email or uid in request body", req.body);
return res.status(400).send({ error: 'Email and UID are required.' });
}
try {
console.log("Fetching or creating customer for email:", email);
const customers = await stripe.customers.list({ email });
let customer = customers.data.length ? customers.data[0] : await stripe.customers.create({ email });
console.log("Customer ID:", customer.id);
console.log("Creating subscription for customer:", customer.id);
const subscription = await stripe.subscriptions.create({
customer: customer.id,
items: [{ price: "price_ID_HERE" }],
payment_behavior: "default_incomplete",
trial_period_days: 30,
expand: ["latest_invoice.payment_intent"]
});
console.log("Created subscription:", JSON.stringify(subscription, null, 2));
await admin.firestore().collection("users").doc(uid).set({
email,
stripeCustomerId: customer.id,
subscriptionId: subscription.id,
subscriptionStatus: "active",
createdAt: admin.firestore.FieldValue.serverTimestamp()
}, { merge: true });
console.log("Saved subscription info to Firestore for UID:", uid);
const clientSecret = subscription.latest_invoice.payment_intent?.client_secret;
if (!clientSecret) {
console.error("Missing clientSecret in subscription:", subscription);
throw new Error("Payment intent not found in the subscription.");
}
res.status(200).json({ clientSecret });
} catch (error) {
console.error("Stripe error:", error);
res.status(500).send({ error: error.message });
}
});
});
// Cancel Subscription
exports.cancelSubscription = functions.https.onRequest((req, res) => {
cors(req, res, async () => {
if (req.method !== 'POST') {
return res.status(405).send({ error: 'Method not allowed' });
}
const { subscriptionId } = req.body;
if (!subscriptionId) {
return res.status(400).json({ error: 'Subscription ID is required.' });
}
try {
const canceledSubscription = await stripe.subscriptions.del(subscriptionId);
const userSnapshot = await admin.firestore()
.collection("users")
.where("subscriptionId", "==", subscriptionId)
.get();
userSnapshot.forEach(async (doc) => {
await doc.ref.update({
subscriptionStatus: "canceled",
subscriptionId: null
});
});
return res.status(200).json({ success: true, canceledSubscription });
} catch (error) {
console.error('Error canceling subscription:', error);
return res.status(500).json({ error: 'Failed to cancel subscription.' });
}
});
});
This is my firebase console log:
C:UsersgavitDesktopNerdFinderFunctions>firebase functions:log
2025-04-15T18:36:41.018392Z ? createSubscription: server: 'nginx',
2025-04-15T18:36:41.018396Z ? createSubscription: date: 'Tue, 15 Apr 2025 18:36:41 GMT',
2025-04-15T18:36:41.018399Z ? createSubscription: 'content-type': 'application/json',
2025-04-15T18:36:41.018402Z ? createSubscription: 'content-length': '218',
2025-04-15T18:36:41.018405Z ? createSubscription: connection: 'keep-alive',
2025-04-15T18:36:41.018409Z ? createSubscription: 'access-control-allow-credentials': 'true',
2025-04-15T18:36:41.018413Z ? createSubscription: 'access-control-allow-methods': 'GET, HEAD, PUT, PATCH, POST, DELETE',
2025-04-15T18:36:41.018416Z ? createSubscription: 'access-control-allow-origin': '*',
2025-04-15T18:36:41.018420Z ? createSubscription: 'access-control-expose-headers': 'Request-Id, Stripe-Manage-Version, Stripe-Should-Retry, X-Stripe-External-Auth-Required, X-Stripe-Privileged-Session-Required',
2025-04-15T18:36:41.018423Z ? createSubscription: 'access-control-max-age': '300',
2025-04-15T18:36:41.018427Z ? createSubscription: 'cache-control': 'no-cache, no-store',
2025-04-15T18:36:41.018431Z ? createSubscription: 'content-security-policy': "base-uri 'none'; default-src 'none'; form-action 'none'; frame-ancestors 'none'; img-src 'self'; script-src 'self' 'report-sample'; style-src 'self'; worker-src 'none'; upgrade-insecure-requests; report-uri https://q.stripe.com/csp-violation?q=5BoLZUJ-9qKTofu7tXwxZG_B3WJANChUyxQ1GVBSIW96Glq-Agjym0q7J_oDcz20oDKMgwBs-UlN6rd0",
2025-04-15T18:36:41.018435Z ? createSubscription: 'idempotency-key': 'stripe-node-retry-62eff8ac-d841-4ef1-b523-9aa98e49ac11',
2025-04-15T18:36:41.018439Z ? createSubscription: 'original-request': 'req_dw8R4bpRVyy7KI',
2025-04-15T18:36:41.018443Z ? createSubscription: 'request-id': 'req_dw8R4bpRVyy7KI',
2025-04-15T18:36:41.018446Z ? createSubscription: 'stripe-should-retry': 'false',
2025-04-15T18:36:41.018449Z ? createSubscription: 'stripe-version': '2025-03-31.basil',
2025-04-15T18:36:41.018452Z ? createSubscription: vary: 'Origin',
2025-04-15T18:36:41.018456Z ? createSubscription: 'x-stripe-priority-routing-enabled': 'true',
2025-04-15T18:36:41.018459Z ? createSubscription: 'x-stripe-routing-context-priority-tier': 'livemode-critical',
2025-04-15T18:36:41.018462Z ? createSubscription: 'x-wc': 'ABGHI',
2025-04-15T18:36:41.018465Z ? createSubscription: 'strict-transport-security': 'max-age=63072000; includeSubDomains; preload'
2025-04-15T18:36:41.018468Z ? createSubscription: },
2025-04-15T18:36:41.018471Z ? createSubscription: requestId: 'req_dw8R4bpRVyy7KI',
2025-04-15T18:36:41.018475Z ? createSubscription: statusCode: 400,
2025-04-15T18:36:41.018478Z ? createSubscription: userMessage: undefined,
2025-04-15T18:36:41.018481Z ? createSubscription: charge: undefined,
2025-04-15T18:36:41.018484Z ? createSubscription: decline_code: undefined,
2025-04-15T18:36:41.018488Z ? createSubscription: payment_intent: undefined,
2025-04-15T18:36:41.018491Z ? createSubscription: payment_method: undefined,
2025-04-15T18:36:41.018494Z ? createSubscription: payment_method_type: undefined,
2025-04-15T18:36:41.018497Z ? createSubscription: setup_intent: undefined,
2025-04-15T18:36:41.018500Z ? createSubscription: source: undefined
2025-04-15T18:36:41.018503Z ? createSubscription: }
2025-04-15T18:36:41.020633398Z D createSubscription: Function execution took 2076 ms, finished with status code: 500