11import { toastStore } from '@codingcatdev/blackcatui' ;
2-
3-
42import { initializeApp , getApps , FirebaseError } from 'firebase/app' ;
53import { getAuth , setPersistence , browserSessionPersistence , signInWithEmailAndPassword , signInWithPopup , type AuthProvider , GoogleAuthProvider } from 'firebase/auth' ;
4+ import { getFirestore , collection , doc , addDoc , onSnapshot } from 'firebase/firestore' ;
65
76import {
87 PUBLIC_FB_API_KEY ,
@@ -28,11 +27,12 @@ export let app = getApps().at(0);
2827if ( ! app ) {
2928 app = initializeApp ( firebaseConfig ) ;
3029}
30+
31+ /* AUTH */
3132export const auth = getAuth ( app ) ;
3233// As httpOnly cookies are to be used, do not persist any state client side.
3334setPersistence ( auth , browserSessionPersistence ) ;
3435
35- /* AUTH */
3636const setCookie = ( idToken : string ) => {
3737 document . cookie = '__ccdlogin=' + idToken + ';max-age=3600' ;
3838}
@@ -66,4 +66,29 @@ export const ccdSignInWithPopUp = async (provider: AuthProvider) => {
6666 }
6767 }
6868 }
69- }
69+ }
70+
71+ /* DB */
72+ export const db = getFirestore ( app ) ;
73+
74+ export const addSubscription = async ( price : string ) => {
75+ const userDoc = doc ( collection ( db , 'stripe-customers' ) , auth . currentUser ?. uid )
76+ const docRef = await addDoc ( collection ( userDoc , 'checkout_sessions' ) , {
77+ price,
78+ success_url : window . location . href ,
79+ cancel_url : window . location . href ,
80+ } )
81+ onSnapshot ( docRef , ( snap ) => {
82+ const { error, url } = snap . data ( ) as { error : Error , url : string } ;
83+ if ( error ) {
84+ toastStore . trigger ( {
85+ message : error . message ,
86+ background : 'variant-filled-error'
87+ } )
88+ }
89+ if ( url ) {
90+ // We have a Stripe Checkout URL, let's redirect.
91+ window . location . assign ( url ) ;
92+ }
93+ } ) ;
94+ } ;
0 commit comments