Server-side Validation of CloudFlare Turnstile For Laravel

Server-side Validation of CloudFlare Turnstile For Laravel cover image

CloudFlare’s Turnstile Laravel is an amazing package to facilitate the server-side validation of CloudFlare’s Turnstile captcha service.

Configuration

First you’ll need an account CloudFlare and Turnstile setup for your website.

https://developers.cloudflare.com/turnstile/

Installation

Install via composer

composer require derekcodes/turnstile-laravel 

Adding your secret key in the .env file

TURNSTILE_SECRET_KEY="0x4AAAAAAAXXXXXXXXXXXXXX"

Create a config/turnstile.php

<?php
    return [
        'secret_key' => env('TURNSTILE_SECRET_KEY', null),
    ];

Usage

Add the use statement at the top of your file

use DerekCodes\TurnstileLaravel\TurnstileLaravel;

Initiate the TursileLaravel object and call the validate method passing the client response Turnstile’s JavaScript provides

$turnstile = new TurnstileLaravel;
$response = $turnstile->validate($request->get('cf-turnstile-response'));

Ensure the response is valid

if ($response['status'] == true) {
  // TODO: add success code here
}

Responses

Example success response

{
  "status": 1
}
Example error response

{
  "status": 0,
  "turnstile_response": {
    "success": false,
    "error-codes": [
      "invalid-input-response"
    ],
    "messages": []
  }
}

For more detail and source code please visit Github.

Written by

Rizwan Aslam

Founder and CEO of CodeBrisk, with years of experience building web applications with Laravel and leading a team of expert developers.

More about Rizwan
Book a free call
Book a free call with CodeBrisk Open in new tab