在前段时间的训练中,我偶尔接触到谷歌提供的收费人机验证服务 reCAPTCHA,在一番学习后已将它接入到我的 Vue 练习我的项目中。上面将介绍我的接入过程与踩过的坑。
reCAPTCHA v2
首先,你须要在 ./public/index.html
中增加上面这段代码:
<script src="https://www.google.com/recaptcha/api.js?render=explicit" async defer></script>
这里须要阐明一下,在中国请用 www.recaptcha.net
替换 www.google.com
:
<script src="https://www.recaptcha.net/recaptcha/api.js?render=explicit" async defer></script>
点击复选框来验证
创立一个 vue 组件,残缺代码如下:
<template> <!-- 增加一个 div 用作容器 --> <div id="grecaptcha"></div></template><script>export default { data() { return { sitekey: "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI" }; }, methods: { submit: function(token) { console.log(token); }, loaded() { setTimeout(() => { window.grecaptcha.render("grecaptcha", { sitekey: this.sitekey, callback: this.submit }); }, 200); } }, mounted() { this.loaded(); }};</script>
阐明:
data() { return { sitekey: "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI" }},
此 sitekey
为测试专用 key
,你须要注册一个本人的 sitekey
用在生产环境中。
注册地址(迷信上网):https://www.google.com/recaptcha/admin/create
注册胜利后失去两个密钥:
第一个密钥即是 sitekey
。
setTimeout(() => { window.grecaptcha.render("grecaptcha", { sitekey: this.sitekey, callback: this.submit });}, 200);
grecaptcha 的渲染 API,延时 200ms 防止报以下谬误:
this.submit
为回调函数,接管返回的 token
用于后端验证。
除了 sitekey
和 callback
外,还有其余的参数,具体请看:这里
将接管到的 token
传到后端即可。
this.axios .get("http://localhost:3000/login", { params: { token: token } }) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); });
后端验证
let res = await axios.get("https://recaptcha.net/recaptcha/api/siteverify", { params: { secret: "6LdFp74UXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXX", response: ctx.query.token }});ctx.body = res.data;
参数:
secret
为失去的第二个密钥response
为接管到的token
返回:
失去 success: true
示意通过验证。
(写于2019年11月)