diff --git a/AGENTS.md b/AGENTS.md
index b365455..d18dae6 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -42,7 +42,7 @@ bun --filter @gruperly/web icons # regenera los iconos PWA de apps/web
- **Prisma 7**: requiere `apps/backend/.env` (con `DATABASE_URL`). El CLI lee `apps/backend/prisma.config.ts` (datasource `url` vía `env('DATABASE_URL')`); el schema es **multi-archivo**: `prisma/schema.prisma` (generator con output `../generated/prisma` + datasource simple) que incluye `prisma/models/*.prisma` (`auth.prisma`, `domain.prisma`). El cliente se regenra con `bun --filter @gruperly/backend db:generate` y se importa desde `@generated/prisma/client` (alias → `generated/prisma`, gitignoreado); se instancia con `@prisma/adapter-pg`. Sin `.env` el CLI falla; copia desde `apps/backend/.env.example`.
- **Tests (bun test)**: viven en `apps/backend/test/`. Mockean el módulo `@/lib/prisma` con `mock.module` (si el mock se comparte como `tx`, declara la const fuera del mock; `vi` de `bun:test` NO tiene `vi.mocked`). Los use-cases ponen el db mockable en `constructor(deps)`. Los tests NO pasan por `sessionAuthMiddleware`; si el route lee `c.get('user')`, inyecta un usuario con un middleware en el harness.
- **Payments (`modules/payments/`)**: el batch crea primero las filas `Payment` (fuente de verdad) y después una preferencia de Checkout Pro por alumno; una preferencia que falla deja su fila `PENDING` sin link y el profesor lo reintenta con `POST /payments/:id/renew` (idempotente). La moneda sale de `user.country` (onboarding, default `AR` → `ARS`; `shared/schemas/country.ts`). No hay webhook: la reconciliación es por polling (`GET /v1/payments/search` con `external_reference`, marca `PAID` solo si `status === 'approved'`), y `CreateFirstGroupSchema` reusa el form de grupo web, por eso `country` lleva `.default(DEFAULT_COUNTRY)` (un POST de grupo sin `country` daba 400). Cuidado en los tests: los `mock.module('@/modules/mp'…)'` se filtran entre archivos de test en la suite completa (workers reutilizados) — no mockear los namespaces de MP: inyectar fakes por constructor deps (`getToken`, `createPreference`, `search`) o usar los módulos reales. `vi.clearAllMocks()` no borra implementaciones (`mockResolvedValue` persiste), los valores `…Once` se consumen antes que la implementación default, y el problema real de "no conectado" es `mpNotConnectedProblem()` → **409 conflict**.
-- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
+- **WhatsApp (`modules/whatsapp/`)**: proveedor intercambiable detrás del puerto `MessagingProvider` (`providers/messaging-provider.ts`); OpenWA (MVP: QR o código por número de teléfono —`requestPairingCode`, opcional en el puerto—, texto libre, no oficial) o Kapso (Meta: setup link, templates), elegido con `WHATSAPP_PROVIDER`. Ojo con esto:
1. El dominio, los jobs y la UI **nunca** importan un adaptador: todo pasa por `getMessagingProvider()`. Lo específico de un proveedor vive solo en `providers//`.
2. `POST /whatsapp/webhooks/openwa|kapso` es **público** (está en `isPublicApiRequest`). Se autentica con HMAC-SHA256 sobre el **raw body** (`c.req.text()`), deduplica en `whatsapp_webhook_events` y, si aplicar el evento falla, borra la clave de deduplicación para que el reintento del proveedor entre.
3. El callback de Kapso no confía en la query: exige el `setupLinkId` guardado y que Kapso confirme que el número es del customer del profesor.
diff --git a/README.md b/README.md
index e92038a..2bcc883 100644
--- a/README.md
+++ b/README.md
@@ -157,7 +157,7 @@ Las dos se prenden por grupo (ficha del grupo → "Mensajes automáticos por Wha
El envío pasa por un proveedor intercambiable (`WHATSAPP_PROVIDER`):
-- **`openwa`** (MVP, default): gateway self-hosted. El profesor escanea un QR y los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
+- **`openwa`** (MVP, default): gateway self-hosted. El profesor lo vincula escaneando un QR o, desde el teléfono, con un código para su número; los mensajes son texto libre. No es oficial y hay riesgo de bloqueo del número.
- **`kapso`**: API oficial de Meta. La vinculación es un setup link y los mensajes usan templates aprobados.
El código vive en `apps/backend/src/modules/whatsapp/`.
diff --git a/apps/backend/src/http/problem-builders.ts b/apps/backend/src/http/problem-builders.ts
index d70fba2..cdf8ae3 100644
--- a/apps/backend/src/http/problem-builders.ts
+++ b/apps/backend/src/http/problem-builders.ts
@@ -139,6 +139,29 @@ export function whatsappNumberInUseProblem(): ProblemDetails {
});
}
+export function whatsappLinkingNotStartedProblem(): ProblemDetails {
+ return conflictProblem({
+ detail: 'Empezá la vinculación de WhatsApp antes de pedir el código.',
+ code: 'whatsapp_linking_not_started',
+ });
+}
+
+/** The provider links by QR or redirect only (Kapso). */
+export function whatsappPairingUnsupportedProblem(): ProblemDetails {
+ return conflictProblem({
+ detail: 'Este proveedor de WhatsApp no permite vincular con el número de teléfono.',
+ code: 'whatsapp_pairing_unsupported',
+ });
+}
+
+/** The session is not ready to hand out a code yet; retryable in seconds. */
+export function whatsappPairingNotReadyProblem(): ProblemDetails {
+ return conflictProblem({
+ detail: 'WhatsApp todavía está preparando la vinculación. Intentá de nuevo en unos segundos.',
+ code: 'whatsapp_pairing_not_ready',
+ });
+}
+
/** The WhatsApp gateway refused the request, or could not be reached. */
export function whatsappProviderErrorProblem(): ProblemDetails {
return {
diff --git a/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts b/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts
new file mode 100644
index 0000000..69f1b01
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/pairing-code/route.ts
@@ -0,0 +1,21 @@
+import type { WhatsappPairingCode } from '@gruperly/shared';
+import { WhatsappPairingCodeSchema } from '@gruperly/shared';
+import { Hono } from 'hono';
+import { problemJson, resultJson, unauthorizedProblem } from '@/http/problem-details';
+import { validate } from '@/http/validate';
+import { RequestWhatsappPairingCode } from './use-case';
+
+const route = new Hono();
+
+route.post('/', validate.json(WhatsappPairingCodeSchema), async (c) => {
+ const user = c.get('user');
+ if (!user) return problemJson(c, unauthorizedProblem(c.req.path));
+
+ const { phoneNumber } = c.req.valid('json') as WhatsappPairingCode;
+
+ const useCase = new RequestWhatsappPairingCode();
+ const result = await useCase.execute(user.id, phoneNumber);
+ return resultJson(c, result);
+});
+
+export default route;
diff --git a/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts b/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts
new file mode 100644
index 0000000..47ddeb3
--- /dev/null
+++ b/apps/backend/src/modules/whatsapp/features/pairing-code/use-case.ts
@@ -0,0 +1,63 @@
+import type { PrismaClient } from '@generated/prisma/client';
+import type { ProblemDetails, Result, WhatsappPairingCodeDto } from '@gruperly/shared';
+import { countryCodeSchema, err, ok, toWhatsappE164 } from '@gruperly/shared';
+import {
+ validationProblem,
+ whatsappLinkingNotStartedProblem,
+ whatsappPairingUnsupportedProblem,
+} from '@/http/problem-builders';
+import prisma from '@/lib/prisma';
+import { getMessagingProvider } from '../../providers';
+import type { MessagingProvider } from '../../providers/messaging-provider';
+
+type RequestWhatsappPairingCodeDeps = {
+ db?: Pick;
+ provider?: MessagingProvider;
+};
+
+/**
+ * Links the teacher's WhatsApp by phone number instead of QR: WhatsApp shows a
+ * prompt on that phone and the teacher types the code we return. It is what
+ * makes linking possible from the phone the app is running on.
+ *
+ * The linking must have been started with `POST /whatsapp/connect` (the account
+ * is PENDING with a live session); the code completes that same linking, so the
+ * status polling and the webhook finish it as with a QR.
+ */
+export class RequestWhatsappPairingCode {
+ constructor(private readonly deps: RequestWhatsappPairingCodeDeps = {}) {}
+
+ async execute(
+ ownerId: string,
+ phoneNumber: string,
+ ): Promise> {
+ const providerResult = this.deps.provider ? ok(this.deps.provider) : getMessagingProvider();
+ if (!providerResult.ok) return providerResult;
+ const provider = providerResult.value;
+ if (!provider.requestPairingCode) return err(whatsappPairingUnsupportedProblem());
+
+ const db = this.deps.db ?? prisma;
+ const account = await db.whatsappAccount.findUnique({ where: { ownerId } });
+ if (!account || account.provider !== provider.id || account.status !== 'PENDING') {
+ return err(whatsappLinkingNotStartedProblem());
+ }
+
+ // Typed the way people write their own number (`11 2345-6789`): the
+ // teacher's country settles the calling code, as for the attendees.
+ const owner = await db.user.findUnique({ where: { id: ownerId }, select: { country: true } });
+ const country = countryCodeSchema.safeParse(owner?.country);
+ const e164 = toWhatsappE164(phoneNumber, country.success ? country.data : null);
+ if (!e164) {
+ return err(
+ validationProblem({
+ detail: 'Revisá el número: escribilo con el código de área.',
+ errors: { phoneNumber: ['Número inválido'] },
+ }),
+ );
+ }
+
+ const code = await provider.requestPairingCode(account, e164.slice(1));
+ if (!code.ok) return code;
+ return ok({ pairingCode: code.value });
+ }
+}
diff --git a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts
index 680d610..235cebc 100644
--- a/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts
+++ b/apps/backend/src/modules/whatsapp/providers/messaging-provider.ts
@@ -129,6 +129,17 @@ export interface MessagingProvider {
account: WhatsappAccountRecord,
): Promise>;
+ /**
+ * Asks for a code to link by phone number instead of scanning the QR, for a
+ * linking already started with `startConnection`. `phoneDigits` is the
+ * teacher's number in international format, digits only. Only providers that
+ * link a WhatsApp Web session (OpenWA) implement it.
+ */
+ requestPairingCode?(
+ account: WhatsappAccountRecord,
+ phoneDigits: string,
+ ): Promise>;
+
/**
* Finishes a redirect-based linking from the callback query. Only providers
* whose `startConnection` answers `redirect` implement it.
diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/http.ts b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts
index ba2f25a..ee1d8c4 100644
--- a/apps/backend/src/modules/whatsapp/providers/openwa/http.ts
+++ b/apps/backend/src/modules/whatsapp/providers/openwa/http.ts
@@ -83,6 +83,15 @@ export class OpenWaClient {
return response.qrCode ?? null;
}
+ requestPairingCode(
+ sessionId: string,
+ phoneNumber: string,
+ ): Promise<{ pairingCode: string; status?: string }> {
+ return this.request('POST', `/sessions/${encodeURIComponent(sessionId)}/pairing-code`, {
+ phoneNumber,
+ });
+ }
+
createWebhook(
sessionId: string,
body: { url: string; events: string[]; secret: string; retryCount: number },
diff --git a/apps/backend/src/modules/whatsapp/providers/openwa/index.ts b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts
index 0638de5..fe04dce 100644
--- a/apps/backend/src/modules/whatsapp/providers/openwa/index.ts
+++ b/apps/backend/src/modules/whatsapp/providers/openwa/index.ts
@@ -1,7 +1,8 @@
import type { ProblemDetails, Result, WhatsappReadiness } from '@gruperly/shared';
import { err, ok } from '@gruperly/shared';
-import { whatsappProviderErrorProblem } from '@/http/problem-builders';
+import { whatsappPairingNotReadyProblem, whatsappProviderErrorProblem } from '@/http/problem-builders';
import { logger } from '@/logger';
+import { sleep } from '../../lib/dispatch';
import { verifyHmacSha256 } from '../../lib/hmac';
import { renderMessage } from '../../lib/render-message';
import type {
@@ -34,6 +35,14 @@ const WEBHOOK_RETRY_COUNT = 3;
/** The global throttler's 429 carries no `retryAfterSeconds`; it clears in seconds. */
const DEFAULT_RATE_LIMIT_MS = 60_000;
+/**
+ * Right after `start` the session is still `initializing` and OpenWA answers a
+ * pairing-code request with 409 until it reads `qr_ready` (on Baileys also for
+ * up to 30 s while a socket closes). Retried here so the teacher's click works.
+ */
+const PAIRING_ATTEMPTS = 6;
+const PAIRING_RETRY_MS = 2_000;
+
const PENDING_STATUSES = new Set(['created', 'initializing', 'qr_ready', 'authenticating']);
/** One OpenWA session per teacher. Names allow letters, digits and hyphens (3-50). */
@@ -41,7 +50,7 @@ export function openWaSessionName(ownerId: string): string {
return `gruperly-${ownerId.replace(/[^a-zA-Z0-9-]/g, '')}`.slice(0, 50);
}
-type OpenWaProviderDeps = { fetch?: OpenWaFetch };
+type OpenWaProviderDeps = { fetch?: OpenWaFetch; sleep?: (ms: number) => Promise };
/**
* OpenWA (self-hosted, unofficial WhatsApp Web gateway) for the MVP.
@@ -54,12 +63,14 @@ type OpenWaProviderDeps = { fetch?: OpenWaFetch };
export class OpenWaProvider implements MessagingProvider {
readonly id = 'OPENWA' as const;
private readonly client: OpenWaClient;
+ private readonly sleep: (ms: number) => Promise;
constructor(
private readonly config: OpenWaConfig,
deps: OpenWaProviderDeps = {},
) {
this.client = new OpenWaClient(config, deps.fetch);
+ this.sleep = deps.sleep ?? sleep;
}
async startConnection(
@@ -138,6 +149,29 @@ export class OpenWaProvider implements MessagingProvider {
}
}
+ async requestPairingCode(
+ account: WhatsappAccountRecord,
+ phoneDigits: string,
+ ): Promise> {
+ if (!account.externalId) return err(whatsappProviderErrorProblem());
+
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const response = await this.client.requestPairingCode(account.externalId, phoneDigits);
+ return ok(response.pairingCode);
+ } catch (error) {
+ const notReady = error instanceof OpenWaApiError && error.status === 409;
+ if (notReady && attempt < PAIRING_ATTEMPTS) {
+ await this.sleep(PAIRING_RETRY_MS);
+ continue;
+ }
+ if (notReady) return err(whatsappPairingNotReadyProblem());
+ logger.warn({ err: describe(error) }, 'OpenWA pairing code request failed');
+ return err(whatsappProviderErrorProblem());
+ }
+ }
+ }
+
async disconnect(account: WhatsappAccountRecord): Promise> {
if (!account.externalId) return ok(undefined);
const sessionId = account.externalId;
diff --git a/apps/backend/src/modules/whatsapp/routes.ts b/apps/backend/src/modules/whatsapp/routes.ts
index 83d3230..79fb1fb 100644
--- a/apps/backend/src/modules/whatsapp/routes.ts
+++ b/apps/backend/src/modules/whatsapp/routes.ts
@@ -2,6 +2,7 @@ import { Hono } from 'hono';
import callbackRoute from './features/callback/route';
import connectRoute from './features/connect/route';
import disconnectRoute from './features/disconnect/route';
+import pairingCodeRoute from './features/pairing-code/route';
import statusRoute from './features/status/route';
import webhookRoute from './features/webhook/route';
@@ -11,6 +12,7 @@ const routes = new Hono();
// it on `/connect` gives the RESTful `DELETE /whatsapp/connect`.
routes.route('/connect', connectRoute);
routes.route('/connect', disconnectRoute);
+routes.route('/connect/pairing-code', pairingCodeRoute);
routes.route('/status', statusRoute);
routes.route('/callback', callbackRoute);
routes.route('/webhooks', webhookRoute);
diff --git a/apps/backend/test/whatsapp-core.test.ts b/apps/backend/test/whatsapp-core.test.ts
index e0f120e..0bc2942 100644
--- a/apps/backend/test/whatsapp-core.test.ts
+++ b/apps/backend/test/whatsapp-core.test.ts
@@ -3,6 +3,7 @@ import { ok } from '@gruperly/shared';
import { CompleteWhatsappSetup } from '@/modules/whatsapp/features/callback/use-case';
import { StartWhatsappConnection } from '@/modules/whatsapp/features/connect/use-case';
import { DisconnectWhatsapp } from '@/modules/whatsapp/features/disconnect/use-case';
+import { RequestWhatsappPairingCode } from '@/modules/whatsapp/features/pairing-code/use-case';
import { GetWhatsappStatus } from '@/modules/whatsapp/features/status/use-case';
import { UpdateGroupAutomationsUseCase } from '@/modules/whatsapp/features/update-automations/use-case';
import { HandleWhatsappWebhook } from '@/modules/whatsapp/features/webhook/use-case';
@@ -73,6 +74,9 @@ function makeDb() {
findUnique: mock(),
update: mock(),
},
+ user: {
+ findUnique: mock(async () => ({ country: 'AR' })),
+ },
};
}
@@ -279,6 +283,67 @@ describe('status', () => {
});
});
+describe('pairing code', () => {
+ const withPairing = () =>
+ fakeProvider({ requestPairingCode: mock(async () => ok('ABCD1234')) });
+
+ it('normalizes the number with the teacher country and returns the code', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+ const provider = withPairing();
+
+ const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
+ ownerId,
+ '011 15 2345-6789',
+ );
+
+ expect(result).toEqual({ ok: true, value: { pairingCode: 'ABCD1234' } });
+ expect(provider.requestPairingCode).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'wa-1' }),
+ '5491123456789',
+ );
+ });
+
+ it('needs a linking in progress with the active provider', async () => {
+ for (const current of [null, account({ status: 'ACTIVE' }), account({ provider: 'KAPSO' })]) {
+ db.whatsappAccount.findUnique.mockResolvedValue(current);
+ const provider = withPairing();
+
+ const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
+ ownerId,
+ '1123456789',
+ );
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('whatsapp_linking_not_started');
+ expect(provider.requestPairingCode).not.toHaveBeenCalled();
+ }
+ });
+
+ it('rejects a number it cannot normalize', async () => {
+ db.whatsappAccount.findUnique.mockResolvedValue(account());
+ const provider = withPairing();
+
+ const result = await new RequestWhatsappPairingCode({ db: db as never, provider }).execute(
+ ownerId,
+ '12345',
+ );
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.status).toBe(400);
+ expect(provider.requestPairingCode).not.toHaveBeenCalled();
+ });
+
+ it('answers 409 when the provider only links by QR or redirect', async () => {
+ const result = await new RequestWhatsappPairingCode({
+ db: db as never,
+ provider: fakeProvider(),
+ }).execute(ownerId, '1123456789');
+
+ expect(result.ok).toBe(false);
+ if (!result.ok) expect(result.error.code).toBe('whatsapp_pairing_unsupported');
+ });
+});
+
describe('disconnect', () => {
it('unlinks on the provider and frees the number locally', async () => {
db.whatsappAccount.findUnique.mockResolvedValue(account({ status: 'ACTIVE' }));
diff --git a/apps/backend/test/whatsapp-providers.test.ts b/apps/backend/test/whatsapp-providers.test.ts
index 907a7cf..25224f9 100644
--- a/apps/backend/test/whatsapp-providers.test.ts
+++ b/apps/backend/test/whatsapp-providers.test.ts
@@ -262,6 +262,47 @@ describe('OpenWA provider', () => {
expect(openWaSessionName('cmh1x2y3z0000abcd')).toBe('gruperly-cmh1x2y3z0000abcd');
expect(openWaSessionName('weird_id.with@chars')).toBe('gruperly-weirdidwithchars');
});
+
+ it('asks OpenWA for a pairing code with the digits of the number', async () => {
+ const { fn, calls } = fakeFetch([
+ {
+ method: 'POST',
+ path: '/sessions/sess-1/pairing-code',
+ status: 201,
+ body: { pairingCode: 'ABCD1234', status: 'qr_ready' },
+ },
+ ]);
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn });
+
+ const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
+
+ expect(result).toEqual({ ok: true, value: 'ABCD1234' });
+ expect(calls[0]?.body).toEqual({ phoneNumber: '5491123456789' });
+ });
+
+ it('waits while the session is not ready for a code, then gives up with 409', async () => {
+ let answered = 0;
+ const fn = mock(async () => {
+ answered += 1;
+ return answered < 3
+ ? new Response(JSON.stringify({ statusCode: 409 }), { status: 409 })
+ : new Response(JSON.stringify({ pairingCode: 'WXYZ9876' }), { status: 201 });
+ });
+ const sleep = mock(async () => {});
+ const provider = new OpenWaProvider(openWaConfig, { fetch: fn, sleep });
+
+ const result = await provider.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
+
+ expect(result).toEqual({ ok: true, value: 'WXYZ9876' });
+ expect(sleep).toHaveBeenCalledTimes(2);
+
+ const busy = mock(async () => new Response(JSON.stringify({ statusCode: 409 }), { status: 409 }));
+ const stuck = new OpenWaProvider(openWaConfig, { fetch: busy, sleep });
+ const failed = await stuck.requestPairingCode(openWaAccount({ status: 'PENDING' }), '5491123456789');
+
+ expect(failed.ok).toBe(false);
+ if (!failed.ok) expect(failed.error.code).toBe('whatsapp_pairing_not_ready');
+ });
});
const kapsoConfig = {
diff --git a/apps/web/src/features/onboarding/WhatsappStep.tsx b/apps/web/src/features/onboarding/WhatsappStep.tsx
index 7ea0386..01fe903 100644
--- a/apps/web/src/features/onboarding/WhatsappStep.tsx
+++ b/apps/web/src/features/onboarding/WhatsappStep.tsx
@@ -6,7 +6,7 @@ import {
linksWithQr,
useStartWhatsappConnection,
useWhatsappStatus,
- WhatsappQrModal,
+ WhatsappLinkModal,
whatsappCallbackErrorMessage,
whatsappStatusBadgeVariant,
whatsappStatusErrorMessage,
@@ -80,7 +80,7 @@ export function WhatsappStep({ feedback, onNext, onBack }: WhatsappStepProps) {
) : (
{usesQr
- ? 'Vas a escanear un código QR desde WhatsApp, como cuando usás WhatsApp Web.'
+ ? 'Lo vinculás con tu número de teléfono o escaneando un código QR, como WhatsApp Web.'
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}{' '}
Los envíos automáticos los prendés después en cada grupo.
) : null}
- void
+ /** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
+ initialQrCode: string | null
+}
+
+const METHOD_LABELS: Record = {
+ phone: 'Con tu número',
+ qr: 'Con código QR',
+}
+
+/**
+ * Vinculación de WhatsApp como "dispositivo vinculado", por QR o con el número
+ * de teléfono. En el teléfono arranca por el número (no se puede escanear la
+ * propia pantalla) y en desktop por el QR; las dos opciones quedan a mano.
+ *
+ * El estado se consulta cada 2 s mientras está pendiente: el QR se renueva y el
+ * modal se cierra solo al vincularse, sea cual sea el método.
+ */
+export function WhatsappLinkModal({ isOpen, onClose, initialQrCode }: WhatsappLinkModalProps) {
+ const toast = useToast()
+ const isMobile = useIsMobile()
+ const statusQuery = useWhatsappStatus({ enabled: isOpen })
+ const status = statusQuery.data?.status
+ const qrCode = statusQuery.data?.qrCode ?? initialQrCode
+ const canUsePhone = statusQuery.data ? linksWithPairingCode(statusQuery.data.provider) : true
+ const [method, setMethod] = useState(() => defaultLinkMethod(isMobile))
+
+ useEffect(() => {
+ if (isOpen) setMethod(defaultLinkMethod(isMobile))
+ }, [isOpen, isMobile])
+
+ useEffect(() => {
+ if (!isOpen) return
+ if (status === 'active') {
+ toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
+ onClose()
+ } else if (status === 'disconnected') {
+ toast.error('La vinculación no se completó. Volvé a intentarlo.')
+ onClose()
+ }
+ }, [isOpen, status, onClose, toast])
+
+ const activeMethod = canUsePhone ? method : 'qr'
+ const methods: WhatsappLinkMethod[] = isMobile ? ['phone', 'qr'] : ['qr', 'phone']
+
+ return (
+
+
+ 2. Tocá Dispositivos vinculados y
+ después Vincular un dispositivo.
+
+
3. Apuntá la cámara a este código.
+
+ >
+ )}
+
+
+
+ Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
+ Ajustes o desde tu teléfono.
+
+
+
+ )
+}
diff --git a/apps/web/src/features/whatsapp/WhatsappPairingCodePanel.tsx b/apps/web/src/features/whatsapp/WhatsappPairingCodePanel.tsx
new file mode 100644
index 0000000..8cefe66
--- /dev/null
+++ b/apps/web/src/features/whatsapp/WhatsappPairingCodePanel.tsx
@@ -0,0 +1,106 @@
+import { Check, Copy, KeyRound, Loader2 } from 'lucide-react'
+import { type FormEvent, useState } from 'react'
+import { Button, Input, Label } from '../../components/ui'
+import { formatPairingCode } from './copy'
+import { useRequestWhatsappPairingCode } from './useRequestWhatsappPairingCode'
+
+/**
+ * Vinculación con el número de teléfono: el profesor escribe su número,
+ * WhatsApp le avisa en ese teléfono y ahí ingresa el código que mostramos. Es
+ * la forma de vincular desde el mismo teléfono en el que usa Gruperly.
+ */
+export function WhatsappPairingCodePanel() {
+ const { requestCode, pairingCode, isRequesting, error, reset } = useRequestWhatsappPairingCode()
+ const [phoneNumber, setPhoneNumber] = useState('')
+ const [copied, setCopied] = useState(false)
+
+ const handleSubmit = (event: FormEvent) => {
+ event.preventDefault()
+ if (phoneNumber.trim()) requestCode(phoneNumber)
+ }
+
+ const handleCopy = async (code: string) => {
+ try {
+ await navigator.clipboard.writeText(code)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ } catch {
+ // Sin permiso de portapapeles: el código igual está a la vista.
+ }
+ }
+
+ if (pairingCode) {
+ return (
+
+
+
+ {formatPairingCode(pairingCode)}
+
+
+
+
+
+ 1. Abrí WhatsApp. Te va a llegar una notificación para vincular un dispositivo:
+ tocala.
+
+
+ 2. Si no te llega, tocá Dispositivos vinculados{' '}
+ → Vincular un dispositivo →{' '}
+ Vincular con el número de teléfono.
+
+
3. Ingresá este código. Esta pantalla se actualiza sola.
+
+
+
+
+ Esperando el código…
+
+
+
+
+ )
+ }
+
+ return (
+
+ )
+}
diff --git a/apps/web/src/features/whatsapp/WhatsappQrModal.tsx b/apps/web/src/features/whatsapp/WhatsappQrModal.tsx
deleted file mode 100644
index 3cec500..0000000
--- a/apps/web/src/features/whatsapp/WhatsappQrModal.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { Loader2, Smartphone } from 'lucide-react'
-import { useEffect } from 'react'
-import { Modal, useToast } from '../../components/ui'
-import { useWhatsappStatus } from './useWhatsappStatus'
-
-type WhatsappQrModalProps = {
- isOpen: boolean
- onClose: () => void
- /** QR de la respuesta de `connect`; se reemplaza por el del estado apenas llega. */
- initialQrCode: string | null
-}
-
-/**
- * Vinculación por QR: el profesor lo escanea desde su teléfono como un
- * "dispositivo vinculado". El estado se consulta cada 2 s mientras está
- * pendiente, así que el QR se renueva y el modal se cierra solo al vincularse.
- */
-export function WhatsappQrModal({ isOpen, onClose, initialQrCode }: WhatsappQrModalProps) {
- const toast = useToast()
- const statusQuery = useWhatsappStatus({ enabled: isOpen })
- const status = statusQuery.data?.status
- const qrCode = statusQuery.data?.qrCode ?? initialQrCode
-
- useEffect(() => {
- if (!isOpen) return
- if (status === 'active') {
- toast.success('¡Listo! Tu WhatsApp quedó vinculado.')
- onClose()
- } else if (status === 'disconnected') {
- toast.error('La vinculación no se completó. Volvé a intentarlo.')
- onClose()
- }
- }, [isOpen, status, onClose, toast])
-
- return (
-
-
-
- {qrCode ? (
-
- ) : (
-
- )}
-
-
-
1. Abrí WhatsApp en tu teléfono.
-
- 2. Tocá Dispositivos vinculados y
- después Vincular un dispositivo.
-
-
3. Apuntá la cámara a este código.
-
-
-
- Los mensajes van a salir desde tu número. Podés desvincularlo cuando quieras desde
- Ajustes o desde tu teléfono.
-
-
-
- )
-}
diff --git a/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx b/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
index ad1aa8c..a50d218 100644
--- a/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
+++ b/apps/web/src/features/whatsapp/WhatsappStatusCard.tsx
@@ -14,7 +14,7 @@ import {
import { useDisconnectWhatsapp } from './useDisconnectWhatsapp'
import { useStartWhatsappConnection } from './useStartWhatsappConnection'
import { useWhatsappStatus } from './useWhatsappStatus'
-import { WhatsappQrModal } from './WhatsappQrModal'
+import { WhatsappLinkModal } from './WhatsappLinkModal'
/**
* WhatsApp en Ajustes: vincular el número desde el que salen los recordatorios
@@ -120,7 +120,7 @@ export function WhatsappStatusCard() {
{linksWithQr(data.provider)
- ? 'Escaneás un código QR desde WhatsApp, como en WhatsApp Web.'
+ ? 'Lo vinculás con tu número o con un código QR, como WhatsApp Web.'
: 'Te llevamos a Meta para conectar tu cuenta de WhatsApp Business.'}
@@ -145,7 +145,7 @@ export function WhatsappStatusCard() {
{connection.error}
) : null}
- mutation.mutate(phoneNumber),
+ pairingCode: mutation.data?.pairingCode ?? null,
+ isRequesting: mutation.isPending,
+ error: mutation.error ? mutation.error.message || 'No pudimos pedir el código.' : null,
+ reset: mutation.reset,
+ }
+}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index b133839..739fd05 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -58,6 +58,7 @@ import type {
WhatsappConnectResultDto,
WhatsappDisconnectResultDto,
WhatsappReturnTo,
+ WhatsappPairingCodeDto,
WhatsappStatusDto,
} from '@gruperly/shared'
@@ -138,6 +139,12 @@ export const startWhatsappConnection = (returnTo: WhatsappReturnTo) =>
body: JSON.stringify({ returnTo }),
})
+export const requestWhatsappPairingCode = (phoneNumber: string) =>
+ apiFetch('/api/v1/whatsapp/connect/pairing-code', {
+ method: 'POST',
+ body: JSON.stringify({ phoneNumber }),
+ })
+
export const getWhatsappStatus = () => apiFetch('/api/v1/whatsapp/status')
export const disconnectWhatsapp = () =>
diff --git a/apps/web/test/whatsapp-copy.test.ts b/apps/web/test/whatsapp-copy.test.ts
index 4cd670a..bb7a3f1 100644
--- a/apps/web/test/whatsapp-copy.test.ts
+++ b/apps/web/test/whatsapp-copy.test.ts
@@ -2,6 +2,9 @@ import type { WhatsappStatusDto } from '@gruperly/shared'
import { describe, expect, test } from 'bun:test'
import {
automationBlockedReason,
+ defaultLinkMethod,
+ formatPairingCode,
+ linksWithPairingCode,
linksWithQr,
readinessLabel,
readWhatsappCallbackFeedback,
@@ -90,3 +93,21 @@ describe('whatsappStatusErrorMessage', () => {
expect(whatsappStatusErrorMessage(null)).not.toContain('error')
})
})
+
+describe('vinculación con el número', () => {
+ test('solo OpenWA ofrece el código', () => {
+ expect(linksWithPairingCode('OPENWA')).toBe(true)
+ expect(linksWithPairingCode('KAPSO')).toBe(false)
+ })
+
+ test('en el teléfono arranca por el número; en desktop, por el QR', () => {
+ expect(defaultLinkMethod(true)).toBe('phone')
+ expect(defaultLinkMethod(false)).toBe('qr')
+ })
+
+ test('muestra el código en dos grupos de cuatro', () => {
+ expect(formatPairingCode('abcd1234')).toBe('ABCD-1234')
+ expect(formatPairingCode('ABCD-1234')).toBe('ABCD-1234')
+ expect(formatPairingCode('XYZ')).toBe('XYZ')
+ })
+})
diff --git a/docs/whatsapp.md b/docs/whatsapp.md
index 75c0a54..b21305d 100644
--- a/docs/whatsapp.md
+++ b/docs/whatsapp.md
@@ -12,7 +12,7 @@ El envío pasa por un **proveedor intercambiable**:
| | **OpenWA** (MVP, default) | **Kapso** (fase 2) |
| --- | --- | --- |
| Qué es | Gateway self-hosted ([rmyndharis/OpenWA](https://github.com/rmyndharis/OpenWA), MIT) sobre WhatsApp Web | Plataforma sobre la **API oficial** de WhatsApp Cloud (Meta) |
-| Vinculación | El profesor escanea un **QR** dentro de Gruperly ("dispositivo vinculado") | El profesor va a un **setup link** de Meta (Facebook login + verificación del número) y vuelve |
+| Vinculación | "Dispositivo vinculado": el profesor escanea un **QR** dentro de Gruperly o ingresa en WhatsApp un **código** que le damos para su número (lo único que funciona desde el mismo teléfono) | El profesor va a un **setup link** de Meta (Facebook login + verificación del número) y vuelve |
| Mensajes | Texto libre | **Templates** aprobados por Meta por cada cuenta |
| Costo | Infraestructura propia | Plan de Kapso + tarifa de Meta por mensaje (la paga el profesor) |
| Riesgo | **No oficial**: viola los términos de WhatsApp; el número se puede bloquear | Ninguno de ToS |
@@ -39,6 +39,7 @@ apps/backend/src/modules/whatsapp/
│ ├── hmac.ts, period.ts, format.ts
├── features/
│ ├── connect/ # POST /whatsapp/connect → { start: qr | redirect }
+│ ├── pairing-code/ # POST /whatsapp/connect/pairing-code → { pairingCode } (solo OpenWA)
│ ├── status/ # GET /whatsapp/status (hace polling al proveedor si está PENDING)
│ ├── disconnect/ # DELETE /whatsapp/connect
│ ├── callback/ # GET /whatsapp/callback (solo Kapso; siempre 302)
@@ -53,6 +54,7 @@ apps/backend/src/modules/whatsapp/
| --- | --- | --- |
| `startConnection` | Crea/adopta la sesión `gruperly-`, registra su webhook, la arranca y devuelve `{ type: 'qr' }` | Crea el customer (una vez) y un setup link `customer_managed`; devuelve `{ type: 'redirect' }` |
| `refreshConnection` | `GET /sessions/:id` (QR nuevo, `ready`, `failed`) | No hay QR: `pending` hasta el callback o el webhook |
+| `requestPairingCode` (opcional) | `POST /sessions/:id/pairing-code` con el número en dígitos; reintenta el `409` mientras la sesión arranca | — (no lo implementa) |
| `completeRedirect` | — | Valida `setup_link_id` y que el número sea del customer del profesor |
| `onConnected` | — | Suscribe el webhook del número y envía los templates a Meta |
| `readiness(kind)` | `ready` si la cuenta está activa | `ready` solo con el template `APPROVED` |
@@ -79,6 +81,13 @@ OpenWA (QR)
qr_ready → QR nuevo · ready → ACTIVE (se cierra el modal)
(en paralelo, si hay webhook: session.authenticated → ACTIVE)
+OpenWA (número de teléfono, la opción por defecto en mobile)
+ mismo POST /whatsapp/connect (la sesión queda arrancada) y el modal muestra "Con tu número"
+ POST /whatsapp/connect/pairing-code { phoneNumber } ─▶ toWhatsappE164 (país del profesor)
+ ─▶ OpenWA POST /sessions/:id/pairing-code ─▶ { pairingCode: 'ABCD1234' }
+ el profesor toca la notificación de WhatsApp (o Dispositivos vinculados → Vincular con el número
+ de teléfono) e ingresa el código; el status y el webhook terminan igual que con el QR
+
Kapso (redirect)
POST /whatsapp/connect ─▶ Kapso: customer + setup link ─▶ { start: { type: 'redirect', url } }
navegador ─▶ Meta (login + verificación) ─▶ GET /whatsapp/callback?setup_link_id&phone_number_id…
@@ -268,6 +277,7 @@ Kapso reintenta si no recibe un 200 en 10 s.
| Endpoint | Qué hace |
| --- | --- |
| `POST /api/v1/whatsapp/connect` | Body `{ returnTo: 'onboarding' \| 'settings' }`. Responde `{ start: { type: 'qr', qrCode } \| { type: 'redirect', url } }` |
+| `POST /api/v1/whatsapp/connect/pairing-code` | Solo OpenWA, con una vinculación `PENDING`. Body `{ phoneNumber }` (nacional o internacional; se normaliza con el país del profesor). Responde `{ pairingCode }`. `409 whatsapp_linking_not_started` sin `connect` previo, `409 whatsapp_pairing_not_ready` si la sesión no arrancó tras ~10 s, `409 whatsapp_pairing_unsupported` con Kapso, `400` si el número no se puede normalizar |
| `GET /api/v1/whatsapp/status` | `{ status, provider, displayPhoneNumber, connectedAt, qrCode, readiness: { PAYMENT_REMINDER, REENGAGEMENT } }`. Con la cuenta `PENDING` consulta al proveedor (para el modal del QR) |
| `DELETE /api/v1/whatsapp/connect` | Desvincula: con OpenWA hace logout del teléfono y borra la sesión. Localmente la fila queda `DISCONNECTED`, sin número |
| `GET /api/v1/whatsapp/callback` | Solo Kapso. Siempre responde `302` |
@@ -284,8 +294,9 @@ Kapso reintenta si no recibe un 200 en 10 s.
1. Levantar OpenWA (`docker run`, ver **Local**), crear la key OPERATOR y cargar `OPENWA_*` en `apps/backend/.env`. Después `bun dev`.
2. **Onboarding**:
- - Cuenta nueva → paso "WhatsApp" → "Vincular WhatsApp" abre el QR.
- - Escanearlo desde WhatsApp → Dispositivos vinculados.
+ - Cuenta nueva → paso "WhatsApp" → "Vincular WhatsApp" abre el modal: en desktop arranca por el QR, en el teléfono por "Con tu número".
+ - QR: escanearlo desde WhatsApp → Dispositivos vinculados.
+ - Número: escribirlo, "Obtener código" e ingresar el código en WhatsApp (notificación, o Dispositivos vinculados → Vincular con el número de teléfono).
- El modal se cierra solo y el paso muestra el número.
- "Lo hago después" deja seguir sin vincular.
3. **Ajustes → WhatsApp**: muestra "Vinculado", el número y "Listo para enviar" en los dos mensajes. "Desvincular" pide confirmación y el dispositivo desaparece del teléfono.
@@ -325,7 +336,9 @@ Kapso reintenta si no recibe un 200 en 10 s.
**Con OpenWA (hoy):**
1. En Gruperly: Ajustes → WhatsApp → **Vincular** (o el paso "WhatsApp" del onboarding).
-2. En el teléfono: WhatsApp → **Dispositivos vinculados** → **Vincular un dispositivo** → escanear el código.
+2. Elegí cómo vincular:
+ - **Con tu número** (si usás Gruperly desde el mismo teléfono): escribí tu número, tocá **Obtener código** y abrí WhatsApp. Tocá la notificación para vincular un dispositivo (o **Dispositivos vinculados** → **Vincular un dispositivo** → **Vincular con el número de teléfono**) e ingresá el código.
+ - **Con código QR** (desde la computadora): en el teléfono, WhatsApp → **Dispositivos vinculados** → **Vincular un dispositivo** → escanear el código.
3. En cada grupo, prender los mensajes automáticos que quieras. Salen los lunes a las 10:00, desde tu número, y las respuestas de tus alumnos te llegan a tu WhatsApp de siempre.
4. Para cortar: Ajustes → WhatsApp → Desvincular, o quitar el dispositivo desde el teléfono.
diff --git a/packages/shared/src/schemas/whatsapp.ts b/packages/shared/src/schemas/whatsapp.ts
index 7aa8385..d324510 100644
--- a/packages/shared/src/schemas/whatsapp.ts
+++ b/packages/shared/src/schemas/whatsapp.ts
@@ -49,6 +49,22 @@ export const WhatsappConnectResultDtoSchema = z.object({
});
export type WhatsappConnectResultDto = z.output;
+// Linking by phone number instead of QR (OpenWA): the teacher types their own
+// number and enters the code WhatsApp asks for on that phone. It is the only
+// way to link from the same phone the app is running on, where a QR cannot be
+// scanned. National or international format; the server normalizes it with the
+// teacher's country.
+export const WhatsappPairingCodeSchema = z.strictObject({
+ phoneNumber: z.string().trim().min(6, 'Ingresá tu número de WhatsApp').max(30),
+});
+export type WhatsappPairingCode = z.output;
+
+export const WhatsappPairingCodeDtoSchema = z.object({
+ // 8 characters, as WhatsApp shows them (e.g. `ABCD1234`).
+ pairingCode: z.string(),
+});
+export type WhatsappPairingCodeDto = z.output;
+
export const WhatsappStatusDtoSchema = z.object({
status: whatsappAccountStatusSchema,
provider: whatsappProviderSchema,