← back to Costa Rica

scripts/whatsapp-golive.js

53 lines

'use strict';
// WhatsApp go-live wiring — runs ONCE after Steve provides WHATSAPP_TOKEN +
// WHATSAPP_PHONE_ID (see docs/whatsapp-golive-runbook.md). Verifies the token,
// registers the webhook, and sends a test template. Does nothing destructive.
//
// Usage:
//   WHATSAPP_TOKEN=... WHATSAPP_PHONE_ID=... [TEST_TO=506xxxxxxxx] \
//     node scripts/whatsapp-golive.js
require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') });

const TOKEN = process.env.WHATSAPP_TOKEN;
const PHONE_ID = process.env.WHATSAPP_PHONE_ID;
const APP_ID = process.env.META_APP_ID || process.env.WHATSAPP_APP_ID;
const VER = process.env.WHATSAPP_API_VERSION || 'v21.0';
const TEST_TO = process.env.TEST_TO;

if (!TOKEN || !PHONE_ID) {
  console.error('BLOCKED: set WHATSAPP_TOKEN and WHATSAPP_PHONE_ID first (see runbook).');
  process.exit(1);
}
const G = (p) => `https://graph.facebook.com/${VER}/${p}`;

(async () => {
  // 1. Verify token + number
  let r = await fetch(G(`${PHONE_ID}?fields=verified_name,display_phone_number,quality_rating`),
    { headers: { Authorization: `Bearer ${TOKEN}` } });
  let j = await r.json();
  if (!r.ok) { console.error('token/phone verify FAILED:', JSON.stringify(j).slice(0, 300)); process.exit(1); }
  console.log(`✅ verified: ${j.verified_name} (${j.display_phone_number}) quality=${j.quality_rating}`);

  // 2. Subscribe the app to the WABA webhooks (idempotent)
  r = await fetch(G(`${PHONE_ID}/subscribed_apps`), { method: 'POST', headers: { Authorization: `Bearer ${TOKEN}` } });
  console.log(r.ok ? '✅ subscribed_apps ok' : `⚠️ subscribe: ${(await r.text()).slice(0, 200)}`);

  console.log('\nNext (Meta portal, one-time): set webhook callback');
  console.log('  URL   https://costarica.agentabrams.com/webhooks/whatsapp');
  console.log(`  Verify token: ${process.env.WHATSAPP_VERIFY_TOKEN || '(set WHATSAPP_VERIFY_TOKEN in .env)'}`);
  console.log('  Fields: messages');

  // 3. Optional test template send
  if (TEST_TO) {
    r = await fetch(G(`${PHONE_ID}/messages`), {
      method: 'POST', headers: { Authorization: `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ messaging_product: 'whatsapp', to: TEST_TO, type: 'template',
        template: { name: 'hello_world', language: { code: 'en_US' } } }),
    });
    j = await r.json();
    console.log(r.ok ? `✅ test template sent to ${TEST_TO} (id ${j.messages?.[0]?.id})`
                     : `⚠️ test send: ${JSON.stringify(j).slice(0, 200)}`);
  }
  console.log('\nDone. Then: pm2 restart costa-rica --update-env  → lib/whatsapp.js liveMode=true');
})();