Код: Выделить всё
'use client';
import { auth, db } from '@/firebaseConfig';
import type { FirebaseApp } from 'firebase/app';
// make sure db is exported here
import { addDoc, collection, onSnapshot } from 'firebase/firestore';
import { getFunctions, httpsCallable } from 'firebase/functions';
import { logger } from '@/lib/default-logger';
const PRICE_ID = process.env.NEXT_PUBLIC_STRIPE_METERED_PRICE!;
const CLOUD_RUN_ROOT = process.env.NEXT_PUBLIC_CLOUD_RUN_ROOT!;
/**
* Creates a Checkout Session document in
* stripe_customers/{uid}/checkout_sessions
* and waits for the extension to fill in `url`.
*/
export async function getCheckoutUrl(): Promise {
const user = auth.currentUser;
if (!user) throw new Error('Must be signed-in first');
// 1️⃣ Create the Checkout-Session request doc
const sessionRef = await addDoc(collection(db, 'stripe_customers', user.uid, 'checkout_sessions'), {
price: PRICE_ID, // single-price subscription
mode: 'subscription',
success_url: window.location.href,
cancel_url: window.location.href,
metadata: { storeId: user.uid },
});
// 2️⃣ Listen for the extension to populate `url` or `error`
return new Promise((resolve, reject) => {
const unsubscribe = onSnapshot(
sessionRef,
(snap) => {
const data = snap.data();
if (!data) return;
if (data.error) {
unsubscribe();
logger.error('Stripe ext error', data.error);
reject(new Error(data.error.message ?? 'Stripe extension failed'));
}
if (data.url) {
unsubscribe();
resolve(data.url as string);
}
},
(err) => {
unsubscribe();
reject(err);
}
);
setTimeout(() => {
unsubscribe();
reject(new Error('Timed out waiting for Stripe Checkout URL'));
}, 60_000);
});
}Подробнее здесь: https://stackoverflow.com/questions/796 ... ed-pricing