-
-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add script to sync with stripe subscriptions
- Loading branch information
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { getStripe } from '../../../integrations/stripe'; | ||
import { getDatabase } from '../../../../data_layer'; | ||
import Stripe from 'stripe'; | ||
|
||
const stripe = getStripe(); | ||
|
||
const updateStripeSubscriptions = async () => { | ||
let hasMore = true; | ||
let startingAfter: string | undefined = undefined; | ||
const database = getDatabase(); | ||
|
||
while (hasMore) { | ||
const subscriptions: Stripe.ApiList<Stripe.Subscription> = | ||
await stripe.subscriptions.list({ | ||
limit: 100, | ||
status: 'active', | ||
starting_after: startingAfter, | ||
}); | ||
|
||
for (const subscription of subscriptions.data) { | ||
if (typeof subscription.customer === 'string') { | ||
const customer = await stripe.customers.retrieve(subscription.customer); | ||
|
||
if ('email' in customer) { | ||
const sub = await database | ||
.table('subscriptions') | ||
.where({ email: customer.email }) | ||
.first(); | ||
|
||
if (sub && !sub.active) { | ||
console.info('Updating customer', customer.id); | ||
await database | ||
.table('customers') | ||
.where({ email: customer.email }) | ||
.update({ active: true }); | ||
} else { | ||
console.info('Customer already active', customer.id); | ||
} | ||
} else { | ||
console.warn('Customer does not have an email'); | ||
} | ||
} | ||
} | ||
|
||
hasMore = subscriptions.has_more; | ||
if (hasMore) { | ||
startingAfter = subscriptions.data[subscriptions.data.length - 1].id; | ||
} | ||
} | ||
}; | ||
|
||
if (require.main === module) { | ||
updateStripeSubscriptions().catch(console.error); | ||
} |