-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstripe.ts
More file actions
77 lines (69 loc) · 2.43 KB
/
stripe.ts
File metadata and controls
77 lines (69 loc) · 2.43 KB
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
import Stripe from "stripe";
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error("Stripe secret key is not configured.");
}
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export default stripe;
/**
* Finds a Stripe customer by their user ID.
*
* @param userId - The user ID associated with the customer.
* @returns A promise that resolves to the Stripe customer object if found, or null if not found.
*/
export async function findCustomerByUserId(
userId: string,
): Promise<Stripe.Customer | null> {
const customers = await stripe.customers.search({
query: `metadata['userId']: '${userId}'`,
});
return customers.data.length > 0 && customers.data[0]
? customers.data[0]
: null;
}
/**
* Retrieves all subscriptions for a given customer and returns them sorted by creation date.
*
* @param customerId - The ID of the customer whose subscriptions are to be retrieved.
* @returns A promise that resolves to an array of subscriptions for the customer.
*/
async function getCustomerSubscriptions(
customerId: string,
): Promise<Stripe.Subscription[]> {
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
status: "all", // To get all subscription statuses
expand: ["data.latest_invoice.payment_intent"],
});
// Sort subscriptions by creation date in descending order (most recent first)
subscriptions.data.sort((a, b) => b.created - a.created);
return subscriptions.data;
}
/**
* Finds the most recent valid subscription for a given array of subscriptions.
*
* @param subscriptions - An array of subscriptions to search through.
* @returns The most recent valid subscription with a valid payment intent, or null if none found.
*/
function findExistingSubscription(
subscriptions: Stripe.Subscription[],
): Stripe.Subscription | null {
return (
subscriptions.find(
(sub) =>
typeof sub.latest_invoice === "object" &&
sub.latest_invoice?.payment_intent,
) || null
);
}
/**
* Finds the most recent subscription for a given user ID.
*
* @param userId - The user ID associated with the customer.
* @returns A promise that resolves to the most recent valid subscription for the user, or null if not found.
*/
export async function findExistingSubscriptionByCustomerId(
customerId: string,
): Promise<Stripe.Subscription | null> {
const subscriptions = await getCustomerSubscriptions(customerId);
return findExistingSubscription(subscriptions);
}