先日、Laravel + Vue.jsでSPAサイトを作っていて、Google reCAPTCHAを実装する方法の情報があまりなくて苦労しました。
今回の記事では、Laravel + Vue.jsでGoogle reCAPTCHAを実装する方法について紹介します。
今回のチュートリアルでは、chitranu/google-recaptchaを使用して、Laravel + Vue.jsでGoogle reCAPTCHAを実装します。
reCAPTCHA を利用するには v2 または v3 のどちらのバージョンの場合も reCAPTCHA を使用するサイトを登録して API キー(reCAPTCHA の API を使用するためのキー)を取得する必要があります。(今回の記事ではv3が対象)
サイトの登録には Google のユーザーアカウントが必要です。
Contents
サイトキーとシークレットキーの取得
サイトの登録及び API キーの管理などは https://www.google.com/recaptcha/admin/site/ で行うことができます。
新しいサイトの登録は https://www.google.com/recaptcha/admin/create から行えます。
登録画面では、必要事項を入力します。
ラベル:キャプチャを識別するための名前です。自分でわかりやすい名前を付けます。
reCAPTCHA タイプ:利用するタイプを選択します。
ドメイン:reCAPTCHA を使用するドメインを指定します。
オーナー:Google アカウントのメールアドレスを指定します。
「reCAPTCHA 利用条件に同意する」にチェックを入れて「送信」をクリックして登録します。
入力に問題がなければ、API キー(サイトキーとシークレットキー)が表示されるのでコピーしておきます。API キーは https://www.google.com/recaptcha/admin/siteで後から確認することができます。
Site Key:reCAPTCHA を表示する際に使用するサイトのキー
Secret Key:検証で使用する秘密のキーで公開してはいけません。
Laravelでのサーバーサイドでの設定
.envファイルに下記の内容を追記します。
//YOUR_RECAPTCHA_SECRET_KEYの部分はご自身のシークレットキーに書き換えてください。 GOOGLE_RECAPTCHA_SECRETKEY=YOUR_RECAPTCHA_SECRET_KEY
まず、composerを使用してchitranu/google-recaptchaパッケージをインストールします。プロジェクトディレクトリで次のコマンドを実行します。
$ composer require chitranu/google-recaptcha
パッケージをインストールした後、受け取ったトークンを検証するために、以下に示す検証ルールのvalidationを更新処理をするコントローラにを追加する必要があります。
$request->validate([ '...' // other fields 'recaptcha-token' => 'required|recaptcha' ]);
大量のスパム送信を受け取っている場合は、0.1〜1.0の値を設定することで、検証ルールを指定しながらスコアのしきい値を設定することを利用できます。グーグル公式ガイドでスコアしきい値について参照できます。(参照)
$request->validate([ '...' // other fields 'recaptcha-token' => 'required|recaptcha:0.5' // Specify threshhold ]);
サーバーサイドで行うことはこれで全てです。
フロントエンド Using vue-recaptcha-v3
Nuxt.jsまたはVue.jsプロジェクトディレクトリで次のコマンドを実行して、vue-recaptcha-v3ライブラリをインストールします。シンプルで使いやすいreCAPTCHA(v3のみ)ライブラリです。
$ npm install vue-recaptcha-v3
$ yarn add vue-recaptcha-v3
Vue.jsの使い方
Vue.jsを使用している場合は、main.jsファイル内に次のコードを追加する必要があります。
import Vue from 'vue'; import { VueReCaptcha } from 'vue-recaptcha-v3'; Vue.use(VueReCaptcha, { siteKey: 'ADD_HERE_GOOGLE_SITE_KEY', loaderOptions: { autoHideBadge: true } })
<template> <form @submit.prevent="onFormSubmit()" ref="contactform"> <input type="text" name="name" placeholder="Your Name" /> <input type="email" name="email" placeholder="Your Email" /> <textarea name="message" placeholder="Your Message"></textarea> <p> This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply. </p> <button type="submit">Submit</button> </form> </template> <script> export default { methods: { async onFormSubmit() { // Wait until recaptcha has been loaded. await this.$recaptchaLoaded(); // Execute reCAPTCHA with action "login". const token = await this.$recaptcha('login'); // Prepare form data let formData = new FormData(this.$refs.contactform); // Appended token in formData formData.append('recaptcha-token', token); // Make an ajax request to your Laravel endpoint. axios.post('/your-form-endpoint', formData).then( (response) => { // handle response }, (error) => { // handle errors } ); }, }, }; </script>
Nuxt.jsの使い方
Nuxt.jsを使用している場合は、新しいプラグインを作成する必要があります。そのためには、/plugins/vue-recaptcha.jsに新しいファイルを作成し、次のコードを追加します。
import Vue from 'vue' import; { VueReCaptcha } from 'vue-recaptcha-v3'; Vue.use(VueReCaptcha, { siteKey: 'ADD_HERE_GOOGLE_SITE_KEY', loaderOptions: { autoHideBadge: true } })
次に、nuxt.config.jsにファイルパスを追加します
export default { plugins: ['~/plugins/vue-recaptcha'] }
<template> <form @submit.prevent="onFormSubmit()" ref="contactform"> <input type="text" name="name" placeholder="Your Name" /> <input type="email" name="email" placeholder="Your Email" /> <textarea name="message" placeholder="Your Message"></textarea> <p> This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply. </p> <button type="submit">Submit</button> </form> </template> <script> export default { methods: { async onFormSubmit() { // Wait until recaptcha has been loaded. await this.$recaptchaLoaded(); // Execute reCAPTCHA with action "login". const token = await this.$recaptcha('login'); // Prepare form data let formData = new FormData(this.$refs.contactform); // Appended token in formData formData.append('recaptcha-token', token); // Make an ajax request to your Laravel endpoint. this.$axios.$post('/your-form-endpoint', formData).then( (response) => { // handle response }, (error) => { // handle errors } ); }, }, }; </script>
今回は、vue + laravelでグーグルGoogle reCAPTCHA3を実装する方法について紹介しました。
[参照]:How to integrate Google reCAPTCHA in your Laravel project