Skip to content

Commit 478bcc0

Browse files
waleedlatif1claude
andcommitted
fix(meta-ads): exchange short-lived token for long-lived token on OAuth connect
Meta's auth code flow returns a short-lived token (~1-2h) with no refresh token. Add fb_exchange_token call in account.create.after hook to exchange for a long-lived token (~60 days), following the same pattern as Salesforce's post-connect token handling. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent b339b48 commit 478bcc0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

apps/sim/lib/auth/auth.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,39 @@ export const auth = betterAuth({
323323
}
324324
}
325325

326+
if (account.providerId === 'meta-ads' && account.accessToken) {
327+
try {
328+
const exchangeUrl = new URL('https://graph.facebook.com/v24.0/oauth/access_token')
329+
exchangeUrl.searchParams.set('grant_type', 'fb_exchange_token')
330+
exchangeUrl.searchParams.set('client_id', env.META_ADS_CLIENT_ID as string)
331+
exchangeUrl.searchParams.set('client_secret', env.META_ADS_CLIENT_SECRET as string)
332+
exchangeUrl.searchParams.set('fb_exchange_token', account.accessToken)
333+
334+
const exchangeResponse = await fetch(exchangeUrl.toString())
335+
if (exchangeResponse.ok) {
336+
const exchangeData = await exchangeResponse.json()
337+
const longLivedToken = exchangeData.access_token
338+
const expiresIn = exchangeData.expires_in ?? 5_184_000
339+
340+
await db
341+
.update(schema.account)
342+
.set({
343+
accessToken: longLivedToken,
344+
accessTokenExpiresAt: new Date(Date.now() + expiresIn * 1000),
345+
})
346+
.where(eq(schema.account.id, account.id))
347+
348+
logger.info('Exchanged Meta short-lived token for long-lived token', { expiresIn })
349+
} else {
350+
logger.warn('Failed to exchange Meta token for long-lived token', {
351+
status: exchangeResponse.status,
352+
})
353+
}
354+
} catch (error) {
355+
logger.error('Error exchanging Meta token', { error })
356+
}
357+
}
358+
326359
if (isMicrosoftProvider(account.providerId)) {
327360
await db
328361
.update(schema.account)

0 commit comments

Comments
 (0)