Google reCAPTCHA V2未验证解决方案问题:如何实现正确验证?
Hey there, let's fix that reCAPTCHA validation issue you're hitting. The error you're seeing happens because you're only handling the client-side part—Google requires you to verify the reCAPTCHA response on your backend too, not just grab it with grecaptcha.getResponse(). Here's the complete, correct implementation:
1. 前端部分(补充你的现有代码)
You've already got the widget rendering right, but you need to send the response token to your backend instead of stopping at client-side retrieval:
- First, make sure the reCAPTCHA script is loaded:
<script src="https://www.google.com/recaptcha/api.js" async defer></script> - Render the widget in your form (replace
YOUR_SITE_KEYwith your actual site key):<form id="submit-form"> <!-- Your form fields here --> <div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div> <button type="submit">Submit</button> </form> - Handle form submission to send the token to your backend:
document.getElementById("submit-form").addEventListener("submit", async (e) => { e.preventDefault(); // Get the reCAPTCHA response token const recaptchaToken = grecaptcha.getResponse(); // Validate user completed the challenge if (!recaptchaToken) { alert("Please complete the reCAPTCHA verification first"); return; } // Package form data + token and send to backend const formData = new FormData(e.target); formData.append("recaptcha_token", recaptchaToken); try { const response = await fetch("/api/verify-recaptcha", { method: "POST", body: formData }); const result = await response.json(); if (result.success) { // Proceed with your business logic (e.g., save form data) alert("Verification passed!"); e.target.reset(); grecaptcha.reset(); } else { alert("reCAPTCHA verification failed. Please try again."); grecaptcha.reset(); } } catch (err) { console.error("Request error:", err); alert("Something went wrong. Please try later."); } });
2. 后端部分(The Missing Piece)
This is the critical step you skipped. You must validate the token with Google's API using your secret key (never expose this key in frontend code!).
Example with Node.js/Express
const express = require("express"); const axios = require("axios"); const app = express(); app.use(express.urlencoded({ extended: true })); // Replace with your actual reCAPTCHA secret key const RECAPTCHA_SECRET = "YOUR_SECRET_KEY"; app.post("/api/verify-recaptcha", async (req, res) => { try { const { recaptcha_token } = req.body; // Call Google's verification API const verification = await axios.post( "https://www.google.com/recaptcha/api/siteverify", null, { params: { secret: RECAPTCHA_SECRET, response: recaptcha_token, remoteip: req.ip // Optional: adds extra security by checking user IP } } ); const { success, error-codes } = verification.data; if (success) { res.json({ success: true, message: "reCAPTCHA verified" }); // Run your backend logic here (e.g., save to database) } else { console.error("Verification failed:", error-codes); res.json({ success: false, message: "Invalid reCAPTCHA token" }); } } catch (err) { console.error("Verification request error:", err); res.status(500).json({ success: false, message: "Server error" }); } }); app.listen(3000, () => console.log("Server running on port 3000"));
Core Logic for Other Languages
No matter if you're using PHP, Python, or Java, the steps are the same:
- Receive the
recaptcha_tokenfrom the frontend - Send a POST request to
https://www.google.com/recaptcha/api/siteverifywith your secret key and the token - Check if the
successfield in the response istrue
3. Key Notes
- Never expose your secret key: Keep it strictly in your backend environment variables, never in frontend code.
- Reset the widget on failure: Use
grecaptcha.reset()to let users retry the challenge if verification fails. - Optional IP check: Including
remoteiphelps Google better detect suspicious activity.
内容的提问来源于stack exchange,提问作者jeirueda

