@@ -93,19 +93,32 @@ export async function onSubscriptionUpdated(
9393 const subscriptionUpdated = event . data . object as Stripe . Subscription ;
9494 const priceId = subscriptionUpdated . items . data [ 0 ] . price . id ;
9595 const plan = await getPlanByPriceId ( options , priceId ) ;
96- const stripeId = subscriptionUpdated . id ;
97- const subscription = await ctx . context . adapter . findOne < Subscription > ( {
96+
97+ const referenceId = subscriptionUpdated . metadata ?. referenceId ;
98+ const subscriptionId = subscriptionUpdated . id ;
99+ const customerId = subscriptionUpdated . customer . toString ( ) ;
100+ let subscription = await ctx . context . adapter . findOne < Subscription > ( {
98101 model : "subscription" ,
99- where : [
100- {
101- field : "stripeSubscriptionId" ,
102- value : stripeId ,
103- } ,
104- ] ,
102+ where : referenceId
103+ ? [ { field : "referenceId" , value : referenceId } ]
104+ : subscriptionId
105+ ? [ { field : "stripeSubscriptionId" , value : subscriptionId } ]
106+ : [ ] ,
105107 } ) ;
106108 if ( ! subscription ) {
107- return ;
109+ const subs = await ctx . context . adapter . findMany < Subscription > ( {
110+ model : "subscription" ,
111+ where : [ { field : "stripeCustomerId" , value : customerId } ] ,
112+ } ) ;
113+ if ( subs . length > 1 ) {
114+ logger . warn (
115+ `Stripe webhook error: Multiple subscriptions found for customerId: ${ customerId } and no referenceId or subscriptionId is provided` ,
116+ ) ;
117+ return ;
118+ }
119+ subscription = subs [ 0 ] ;
108120 }
121+
109122 const seats = subscriptionUpdated . items . data [ 0 ] . quantity ;
110123 await ctx . context . adapter . update ( {
111124 model : "subscription" ,
@@ -125,8 +138,8 @@ export async function onSubscriptionUpdated(
125138 } ,
126139 where : [
127140 {
128- field : "stripeSubscriptionId " ,
129- value : subscriptionUpdated . id ,
141+ field : "referenceId " ,
142+ value : subscription . referenceId ,
130143 } ,
131144 ] ,
132145 } ) ;
@@ -170,7 +183,7 @@ export async function onSubscriptionUpdated(
170183 }
171184 }
172185 } catch ( error : any ) {
173- logger . error ( `Stripe webhook failed. Error: ${ error . message } ` ) ;
186+ logger . error ( `Stripe webhook failed. Error: ${ error } ` ) ;
174187 }
175188}
176189
@@ -217,6 +230,6 @@ export async function onSubscriptionDeleted(
217230 }
218231 }
219232 } catch ( error : any ) {
220- logger . error ( `Stripe webhook failed. Error: ${ error . message } ` ) ;
233+ logger . error ( `Stripe webhook failed. Error: ${ error } ` ) ;
221234 }
222235}
0 commit comments