CognxSafeTrack commited on
Commit Β·
d3a9684
1
Parent(s): 3078897
feat: finalize Embedded Signup flow and add webhook simulator
Browse filesFiles changed (4)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import React, { useEffect, useState } from 'react';import { initMetaSDK, launchEmbeddedSignup } from '../lib/meta-signup';import { api } from '../lib/api';import { useParams } from 'react-router-dom';
export const WhatsAppConnectButton: React.FC = () => { const { orgId } = useParams<{ orgId: string }>(); const [loading, setLoading] = useState(false); const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle');
useEffect(() => { initMetaSDK(); }, []);
const handleConnect = async () => { if (!orgId) return; setLoading(true); setStatus('idle');
try { // 1. Launch Meta Popup const result = await launchEmbeddedSignup(); // 2. Send IDs and Code/Token to our Backend await api.post(`/v1/organizations/${orgId}/whatsapp-setup`, { wabaId: result.waba_id, accessToken: result.accessToken || result.code, // Can be token or code depending on Meta config phoneNumberId: result.phone_number_id, phoneNumber: '' // Meta doesn't always send the phone number string in the event });
setStatus('success'); console.log("[SETUP] WhatsApp connecté avec succès !"); } catch (err) { console.error("[SETUP] Erreur lors de la configuration:", err); setStatus('error'); } finally { setLoading(false); } };
return ( <div className="p-4 border rounded-lg bg-white shadow-sm"> <h3 className="text-lg font-semibold mb-2">Configuration WhatsApp Business</h3> <p className="text-sm text-gray-600 mb-4"> Connectez votre compte WhatsApp Business pour commencer Γ envoyer des messages pΓ©dagogiques. </p> <button onClick={handleConnect} disabled={loading} className={`px-6 py-2 rounded-md font-medium text-white transition-all ${ loading ? 'bg-gray-400 cursor-not-allowed' : 'bg-blue-600 hover:bg-blue-700' }`} > {loading ? 'Connexion en cours...' : 'Connecter WhatsApp'} </button>
{status === 'success' && ( <p className="mt-2 text-sm text-green-600 font-medium">β
WhatsApp connectΓ© avec succΓ¨s !</p> )} {status === 'error' && ( <p className="mt-2 text-sm text-red-600 font-medium">β Γchec de la configuration. RΓ©essayez.</p> )} </div> );};68 unmodified lines69707172737475767778798081828384858687888968 unmodified lineswindow.FB.login((response: any) => {if (response.authResponse) {const accessToken = response.authResponse.accessToken;// We wait for the WA_EMBEDDED_SIGNUP_EVENT to get the IDs// We resolve with the token; the IDs will come from the event listenerresolve({ accessToken });} else {window.removeEventListener('message', sessionHandler);reject(new Error("Connexion Facebook Γ©chouΓ©e ou annulΓ©e."));}}, {scope: 'whatsapp_business_management,whatsapp_business_messaging',extras: {feature: 'whatsapp_embedded_signup',setup: {business: { name: 'XamlΓ© Cloud' }}}});});68 unmodified lines6970717273747576777879808182838485868768 unmodified lineswindow.FB.login((response: any) => {if (response.authResponse) {const code = response.authResponse.code;resolve({ code });} else {window.removeEventListener('message', sessionHandler);reject(new Error("Connexion Facebook Γ©chouΓ©e ou annulΓ©e."));}}, {config_id: import.meta.env.VITE_META_CONFIG_ID || '', // Requested config_idresponse_type: 'code', // Requested response_typeoverride_default_response_type: true, // Requested overridescope: 'whatsapp_business_management,whatsapp_business_messaging',extras: {feature: 'whatsapp_embedded_signup'}});});
144 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174144 unmodified lineslogger.info(`[WHATSAPP-SETUP] Processing connection for Org: ${id}, WABA: ${wabaId}`);try {// 1. Encrypt and store Meta credentialsawait prisma.organization.update({where: { id },data: encryptSecrets({systemUserToken: accessToken,wabaId})});// 2. Synchronize Phone Number record if providedif (phoneNumberId) {await (prisma as any).whatsAppPhoneNumber.upsert({where: { id: phoneNumberId },update: {phoneNumber: phoneNumber || '',organizationId: id},create: {id: phoneNumberId,phoneNumber: phoneNumber || '',organizationId: id}});}// 3. Invalidate Redis cache to let Worker pick up new config immediatelyawait invalidateOrganizationCache(id, phoneNumberId);144 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176144 unmodified lineslogger.info(`[WHATSAPP-SETUP] Processing connection for Org: ${id}, WABA: ${wabaId}`);try {await prisma.$transaction(async (tx) => {// 1. Encrypt and store Meta credentialsawait tx.organization.update({where: { id },data: encryptSecrets({systemUserToken: accessToken,wabaId})});// 2. Synchronize Phone Number record if providedif (phoneNumberId) {await (tx as any).whatsAppPhoneNumber.upsert({where: { id: phoneNumberId },update: {phoneNumber: phoneNumber || '',organizationId: id},create: {id: phoneNumberId,phoneNumber: phoneNumber || '',organizationId: id}});}});// 3. Invalidate Redis cache to let Worker pick up new config immediatelyawait invalidateOrganizationCache(id, phoneNumberId);
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import fetch from 'node-fetch';
/** * WhatsApp Webhook Simulator * * Usage: npx tsx apps/api/src/scripts/simulate-webhook.ts [phoneNumberId] [fromPhone] [text] */
const targetUrl = 'http://localhost:8080/v1/whatsapp/webhook';const phoneNumberId = process.argv[2] || '1029384756';const fromPhone = process.argv[3] || '33612345678';const text = process.argv[4] || 'Hello from simulation!';
async function runSimulation() { console.log(`π Simulating message to ${targetUrl}...`); console.log(`π± Phone ID: ${phoneNumberId}`); console.log(`π€ From: ${fromPhone}`); console.log(`π¬ Text: "${text}"`);
const payload = { object: 'whatsapp_business_account', entry: [ { id: 'WHATSAPP_BUSINESS_ACCOUNT_ID', changes: [ { value: { messaging_product: 'whatsapp', metadata: { display_phone_number: '123456789', phone_number_id: phoneNumberId }, contacts: [{ profile: { name: 'Test User' }, wa_id: fromPhone }], messages: [ { from: fromPhone, id: `wamid.HBgLMzM2MzA0Nzg0MDYVAgARGBI1NjI5RkZCMEY3OUM2ODRDOTQA`, timestamp: Math.floor(Date.now() / 1000).toString(), type: 'text', text: { body: text } } ] }, field: 'messages' } ] } ] };
try { const response = await fetch(targetUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', // We simulate the Meta HMAC signature if needed, or disable it in dev 'x-hub-signature-256': 'sha256=fake-signature-for-local-test' }, body: JSON.stringify(payload) });
const data = await response.json(); console.log(`\nβ
Response (${response.status}):`, JSON.stringify(data, null, 2)); if (data.status === 'forwarded') { console.log("\nπ‘ The message was successfully FORWARDED to the internal worker."); } else if (data.status === 'received') { console.log("\nπ₯ The message was successfully QUEUED for local processing."); }
} catch (err: any) { console.error("\nβ Simulation failed:", err.message); }}
runSimulation();apps/admin/src/components/WhatsAppConnectButton.tsxAdded+67
apps/admin/src/lib/meta-signup.ts+6-8
apps/api/src/routes/organizations.ts+25-23
apps/api/src/scripts/simulate-webhook.tsAdded+76