本文将详细介绍如何在网站中集成Google reCAPTCHA v3,通过实战代码演示其集成和验证过程,帮助开发者提升网站的安全性,同时优化用户体验。
实例研究地址
访问Google reCAPTCHA官方文档获取更多信息:https://developers.google.com/recaptcha/docs/v3
步骤一:前端集成
-
引入reCAPTCHA v3脚本:
在HTML中引入Google reCAPTCHA v3的脚本,并指定你的site key。
<script src="https://www.google.com/recaptcha/api.js?render=your_site_key"></script>
-
前端请求验证码:
在需要进行验证的操作中,调用reCAPTCHA v3 API获取token。
grecaptcha.ready(function() { grecaptcha.execute('your_site_key', {action: 'submit'}).then(function(token) { // 将token添加到表单中 document.getElementById('g-recaptcha-response').value = token; }); });
在表单中添加一个隐藏的输入字段,用于提交token:
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">
步骤二:后端验证
在用户提交表单后,后端需要验证token。
-
验证token:
使用您的secret key和用户的token,请求Google的API以验证响应。
import requests from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): secret_key = "your_secret_key" token = request.form.get('g-recaptcha-response') recaptcha_response = requests.post('https://www.google.com/recaptcha/api/siteverify', data={ 'secret': secret_key, 'response': token }) result = recaptcha_response.json() if result['success']: # 验证成功的操作 return jsonify({'message': 'Verification successful'}), 200 else: # 验证失败的操作 return jsonify({'message': 'Verification failed'}), 400 if __name__ == '__main__': app.run()
更多内容可以联系Q:1436423940或直接访问www.ttocr.com测试对接(免费得哈)