Untitled

 avatar
unknown
plain_text
2 months ago
1.7 kB
6
Indexable
import React from 'react';
import { GoogleReCaptchaProvider, useGoogleReCaptcha } from 'react-google-recaptcha-v3';

const DEFAULT_RECAPTCHA_SITE_KEY = '6Lek0NgsAAAAAJgF_333a91vpRe5wY3GRGjggvrN';

export const RecaptchaProvider = ({ children }) => {
  const configuredSiteKey = import.meta.env.VITE_RECAPTCHA_SITE_KEY;
  const siteKey =
    configuredSiteKey && configuredSiteKey !== 'your-recaptcha-site-key-here'
      ? configuredSiteKey
      : DEFAULT_RECAPTCHA_SITE_KEY;

  if (!siteKey) {
    console.warn('VITE_RECAPTCHA_SITE_KEY is not configured. reCAPTCHA will not work.');
    return <>{children}</>;
  }

  return (
    <GoogleReCaptchaProvider
      reCaptchaKey={siteKey}
      scriptProps={{
        async: true,
        defer: true,
        appendTo: 'head',
      }}
    >
      {children}
    </GoogleReCaptchaProvider>
  );
};

export const useRecaptchaToken = () => {
  const { executeRecaptcha } = useGoogleReCaptcha();
  const configuredSiteKey = import.meta.env.VITE_RECAPTCHA_SITE_KEY;
  const siteKey =
    configuredSiteKey && configuredSiteKey !== 'your-recaptcha-site-key-here'
      ? configuredSiteKey
      : DEFAULT_RECAPTCHA_SITE_KEY;
  const isConfigured = Boolean(siteKey);

  const getToken = async () => {
    if (!executeRecaptcha) {
      console.error('reCAPTCHA not yet available');
      return null;
    }

    try {
      const token = await executeRecaptcha('submit_form');
      console.log('reCAPTCHA token generated successfully');
      return token;
    } catch (error) {
      console.error('Error generating reCAPTCHA token:', error);
      return null;
    }
  };

  return { getToken, isConfigured };
};
Editor is loading...
Leave a Comment