-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstripePayment.ts
83 lines (75 loc) · 2.3 KB
/
stripePayment.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use client";
import { FirebaseApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import {
addDoc,
collection,
getFirestore,
onSnapshot,
} from "firebase/firestore";
import { getFunctions, httpsCallable } from "firebase/functions";
export const getCheckoutUrl = async (
app: FirebaseApp,
priceId: string
): Promise<string> => {
const auth = getAuth(app);
const userId = auth.currentUser?.uid;
if (!userId) throw new Error("User is not authenticated");
const db = getFirestore(app);
const checkoutSessionRef = collection(
db,
"customers",
userId,
"checkout_sessions"
);
const docRef = await addDoc(checkoutSessionRef, {
price: priceId,
success_url: window.location.origin,
cancel_url: window.location.origin,
});
return new Promise<string>((resolve, reject) => {
const unsubscribe = onSnapshot(docRef, (snap) => {
const { error, url } = snap.data() as {
error?: { message: string };
url?: string;
};
if (error) {
unsubscribe();
reject(new Error(`An error occurred: ${error.message}`));
}
if (url) {
console.log("Stripe Checkout URL:", url);
unsubscribe();
resolve(url);
}
});
});
};
export const getPortalUrl = async (app: FirebaseApp): Promise<string> => {
const auth = getAuth(app);
const user = auth.currentUser;
let dataWithUrl: any;
try {
const functions = getFunctions(app, "us-east1");
const functionRef = httpsCallable(
functions,
"ext-firestore-stripe-payments-createPortalLink"
);
const { data } = await functionRef({
customerId: user?.uid,
returnUrl: window.location.origin,
});
// Add a type to the data
dataWithUrl = data as { url: string };
console.log("Reroute to Stripe portal: ", dataWithUrl.url);
} catch (error) {
console.error(error);
}
return new Promise<string>((resolve, reject) => {
if (dataWithUrl.url) {
resolve(dataWithUrl.url);
} else {
reject(new Error("No url returned"));
}
});
};