|
| 1 | +import { PrismaClient } from '@prisma/client'; |
| 2 | +import axios from 'axios'; |
| 3 | +import { createIntegrationAccount } from 'integrations/utils'; |
| 4 | + |
| 5 | +const prisma = new PrismaClient(); |
| 6 | + |
| 7 | +export const integrationCreate = async ( |
| 8 | + userId: string, |
| 9 | + workspaceId: string, |
| 10 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 11 | + data: any, |
| 12 | +) => { |
| 13 | + const { oauthResponse, personal, integrationDefinition, oauthParams } = data; |
| 14 | + const integrationConfiguration = { |
| 15 | + access_token: oauthResponse.access_token, |
| 16 | + access_expires_in: oauthResponse.expires_at, |
| 17 | + }; |
| 18 | + |
| 19 | + console.log(oauthResponse, oauthParams); |
| 20 | + const appData = await axios.get( |
| 21 | + `https://graph.facebook.com/v22.0/debug_token?input_token=${oauthParams.code}`, |
| 22 | + ); |
| 23 | + |
| 24 | + const businessManagementScope = appData.data.data.granular_scopes.find( |
| 25 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 26 | + (scope: any) => scope.scope === 'whatsapp_business_management', |
| 27 | + ); |
| 28 | + |
| 29 | + console.log(businessManagementScope); |
| 30 | + const accountId = businessManagementScope?.target_ids[0]; |
| 31 | + |
| 32 | + if (!accountId) { |
| 33 | + throw new Error('No WhatsApp Business Account ID found'); |
| 34 | + } |
| 35 | + |
| 36 | + // Subscribe the app to the WhatsApp Business Account |
| 37 | + await axios.post( |
| 38 | + `https://graph.facebook.com/v22.0/${accountId}/subscribed_apps`, |
| 39 | + {}, |
| 40 | + { |
| 41 | + headers: { |
| 42 | + Authorization: `Bearer ${integrationConfiguration.access_token}`, |
| 43 | + }, |
| 44 | + }, |
| 45 | + ); |
| 46 | + |
| 47 | + // Update the integration account with the new configuration in the database |
| 48 | + const integrationAccount = await createIntegrationAccount(prisma, { |
| 49 | + userId, |
| 50 | + accountId, |
| 51 | + config: integrationConfiguration, |
| 52 | + workspaceId, |
| 53 | + integrationDefinitionId: integrationDefinition.id, |
| 54 | + personal, |
| 55 | + }); |
| 56 | + |
| 57 | + return { |
| 58 | + message: `Created integration account ${integrationAccount.id}`, |
| 59 | + }; |
| 60 | +}; |
0 commit comments