Antoine
Antoine

Reputation: 5691

How to integrate Google's reCAPTCHA in a React Native app?

I haven't found any React Native library to help with reCAPTCHA, and the only Android library I found is Android-Lib-reCAPTCHA but it uses the old API (showing a cypher instead of a checkbox).

I have tried to show the Javascript reCAPTCHA using react-native-webview-bridge but I couldn't make it work and it's very slow and unstable. Besides sometimes the captcha needs more space to display pictures when it's not just a checkbox.

Do you know any other way than a WebView? I also checked out native Android captcha systems but they are all too old/complicated (cyphers).

Also, what is the frequency of robots installing apps and subscribing through? Maybe I don't need a captcha but just a secret key/CSRF token?

Upvotes: 7

Views: 6281

Answers (2)

Jeffrey
Jeffrey

Reputation: 377

You can try using webview component like this:

first create recaptcha keys at https://www.google.com/recaptcha/admin/create

then you create an new component like this:

const GetRecaptcha = (props) => {
const onMessage = (data) => {

    console.log('recaptcha', data.nativeEvent.data)
    //here you can put your action to perform(check validation on your server or somthing)
    props.action(data.nativeEvent.data);

};

return <View style={{}}>

    <WebView
        style={{height: 0}}
        onMessage={async (e) => await onMessage(e)}
        containerStyle={{height: 0}}
        source={{
            html: `
            <!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://www.google.com/recaptcha/api.js?render=RECAPTCHA-KEY"></script>
        <script>
        function onLoad(e) {
         
            grecaptcha.ready(function () {
                grecaptcha.execute('RECAPTCHA-KEY', {action: 'submit'}).then((token) => {
                    window.ReactNativeWebView.postMessage(token);
                });
            }) 
        }
        </script>
        </head>
        <body onload="onLoad()">
        </body>
        </html>`
        , baseUrl: 'your-url',
    }}/>


</View>;
};

you could use this component from other component as this example:

const action=(token)=>{
   // validate key on server
   if(token){
    //do some action
   }else{
   //do some action
   }
  }
  const App=()=>{
  return <GetRecaptcha action={action}/>
  }
 

Upvotes: 1

Alex
Alex

Reputation: 631

For the case of web or mobile web application there are a bunch of react wrappers for google captcha. For example github/react-grecaptcha worked for me like a charm.

Upvotes: 2

Related Questions