Skip to main content

usePinAuth

Hook principal que orquesta todo el flujo de autenticación por PIN.

Uso

import { usePinAuth } from "@camarauth/sdk/react";

function LoginComponent() {
  const auth = usePinAuth({
    apiUrl: "http://localhost:3001",
    whatsappNumber: "+1234567890",
    onSuccess: (user) => console.log("Autenticado:", user),
  });

  // Usar auth...
}

Parámetros

options
PinAuthOptions
required
Opciones de configuración

PinAuthOptions

apiUrl
string
required
URL del backend de Camarauth
whatsappNumber
string
required
Número de WhatsApp para enviar el PIN
pinLength
number
default:"6"
Longitud del PIN a generar
expiresIn
number
default:"180"
Segundos antes de que expire el PIN
maxAutoRegenerations
number
default:"3"
Máximo de regeneraciones automáticas
autoGenerate
boolean
default:"false"
Generar PIN automáticamente al conectar
messagePrefix
string
default:"'PIN:'"
Prefijo del mensaje de WhatsApp
onPinGenerated
(pin: string, emojis: string[]) => void
Callback cuando se genera un PIN
onSuccess
(user: User) => void
Callback cuando la autenticación es exitosa
onError
(error: CamarauthError) => void
Callback cuando hay un error
onExpire
() => void
Callback cuando el PIN expira
onMaxRegenerationsReached
() => void
Callback cuando se alcanza el máximo de regeneraciones

Valor de retorno

Retorna un objeto PinAuthState:
pin
string | null
PIN actual
emojis
string[]
Array de emojis del PIN
emojiString
string
PIN como string de emojis
timeLeft
number
Segundos restantes
formattedTime
string
Tiempo formateado (MM:SS)
isExpired
boolean
Si el PIN expiró
regenerationCount
number
Número de regeneraciones
hasReachedMaxRegenerations
boolean
Si se alcanzó el máximo
status
AuthStatus
Estado actual: ‘idle’ | ‘polling’ | ‘success’ | ‘error’ | ‘expired’
isLoading
boolean
Si está cargando o conectando
user
User | null
Datos del usuario autenticado
error
CamarauthError | null
Error actual si existe
Link de WhatsApp con mensaje
qrCodeUrl
string | null
URL del QR code
fullMessage
string
Mensaje completo para WhatsApp

Métodos

generate
() => void
Generar un nuevo PIN
cancel
() => void
Cancelar autenticación actual
reset
() => void
Resetear todo el estado

Ejemplo completo

import { usePinAuth } from "@camarauth/sdk/react";

function LoginPage() {
  const auth = usePinAuth({
    apiUrl: "http://localhost:3001",
    whatsappNumber: "+1234567890",
    onSuccess: (user) => {
      // Redirigir al dashboard
      window.location.href = "/dashboard";
    },
    onError: (error) => {
      console.error("Error:", error.message);
    },
  });

  if (auth.status === "success") {
    return <div>¡Bienvenido, {auth.user?.name}!</div>;
  }

  return (
    <div className="login-container">
      <h1>Iniciar sesión</h1>

      {!auth.pin ? (
        <button onClick={auth.generate} disabled={auth.isLoading}>
          {auth.isLoading ? "Conectando..." : "Generar código"}
        </button>
      ) : (
        <div className="auth-display">
          <div className="emojis">
            {auth.emojis.map((emoji, i) => (
              <span key={i} className="emoji">
                {emoji}
              </span>
            ))}
          </div>

          <p>Expira en: {auth.formattedTime}</p>

          {auth.qrCodeUrl && (
            <img
              src={auth.qrCodeUrl}
              alt="Escanear para WhatsApp"
              className="qr-code"
            />
          )}

          <a
            href={auth.whatsappLink}
            target="_blank"
            rel="noopener noreferrer"
            className="whatsapp-btn"
          >
            Abrir WhatsApp
          </a>

          <button onClick={auth.cancel}>Cancelar</button>
        </div>
      )}

      {auth.error && <div className="error">{auth.error.message}</div>}
    </div>
  );
}

Véase también