Skip to content

Commit

Permalink
litening especifics event from stripe
Browse files Browse the repository at this point in the history
  • Loading branch information
Luciano-Ferreira committed Jul 8, 2021
1 parent 9200401 commit 6b3437c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 9 deletions.
30 changes: 24 additions & 6 deletions src/pages/api/_lib/manageSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import { stripe } from '../../../services/stripe';

export async function saveSubscription(
subscriptionId: string,
customerId: string
customerId: string,
createAction = false,
) {
const userRef = await fauna.query(
q.Select(
Expand All @@ -28,10 +29,27 @@ export async function saveSubscription(

}

await fauna.query(
q.Create(
q.Collection('subscriptions'),
{ data: subscriptionData }
if (createAction) {
await fauna.query(
q.Create(
q.Collection('subscriptions'),
{ data: subscriptionData }
)
)
} else {
await fauna.query(
q.Replace(
q.Select(
"ref",
q.Get(
q.Match(
q.Index('subscription_by_id'),
subscriptionId,
)
)
),
{ data: subscriptionData }
)
)
)
}
}
18 changes: 15 additions & 3 deletions src/pages/api/webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export const config = {
}

const relevantEvents = new Set([
'checkout.session.completed'
'checkout.session.completed',
'customer.subscriptions.updated',
'customer.subscriptions.deleted'
])

export default async function (req: NextApiRequest, res: NextApiResponse) {
Expand All @@ -44,12 +46,22 @@ export default async function (req: NextApiRequest, res: NextApiResponse) {
if (relevantEvents.has(type)) {
try {
switch (type) {
case 'customer.subscription.updated':
case 'customer.subscription.deleted':
const subscription = event.data.object as Stripe.Subscription;
await saveSubscription(
subscription.id,
subscription.customer.toString(),
false
)
console.log(subscription.customer.toString())
break;
case 'checkout.session.completed':

const checkoutSession = event.data.object as Stripe.Checkout.Session
await saveSubscription(
checkoutSession.subscription.toString(),
checkoutSession.customer.toString()
checkoutSession.customer.toString(),
true
)

break;
Expand Down

0 comments on commit 6b3437c

Please sign in to comment.