一个验证服务平台,为其他应用提供防止机器人自动化访问的验证能力
此处填入在平台申请的应用ID和应用密钥(请勿泄漏线上环境的密钥);初始化验证码时所需要的签名应在后台服务器中实现,此处仅仅方便演示所以签名通过前端生成
// 引入SDK /js/hm-captcha.js
<script src="/js/hm-captcha.js"></script>
// 初始化验证码
const captcha = new HMCaptcha({
appId: 'your-app-id',
type: 'text', // 'text', 'slide', 'click', 'image-select'
container: '#captcha-container',
timestamp: timestamp, // 时间戳
nonce: nonce, // 随机字符串
signature: signature, // 签名
useCustomUI: false, // 是否使用自定义UI,开启是可通过onLoad方法中返回的captcha对象调用自定义UI方法
captchaConfig: {
// 文字验证码的配置,可选,若未提供则会根据创建应用时填写的默认配置
textSize: 4, // 文字验证码的文字个数
textWidth: 150, // 文字验证码的宽度
textHeight: 75, // 文字验证码的高度
// 滑块验证码的配置,可选,若未提供则会根据创建应用时填写的默认配置
sliderViewWidth: 300, // 滑块验证码的宽度
sliderViewHeight: 200, // 滑块验证码的高度
sliderWidth: 60, // 滑块验证码的滑块宽度
sliderHeight: 40, // 滑块验证码的滑块高度
sliderRadius: 8, // 滑块验证码的滑块圆角
// 点选验证码的配置,可选,若未提供则会根据创建应用时填写的默认配置
clickViewWidth: 350, // 点选验证码的宽度
clickViewHeight: 100 // 点选验证码的高度
//
},
getSignature: async function () {
// 这里需要调用后端接口获取签名
// 然后将新的签名/随机数/时间戳返回
return {
timestamp: '',
nonce: '',
signature: ''
}
},
onLoad: function (captcha) {
// 此回调可用于使用自定义UI的场景
console.log('验证码加载完成:', captcha)
},
onSuccess: function (token) {
console.log('验证成功,令牌:', token)
},
onError: function (error) {
console.error('验证失败:', error)
},
onClose: function () {
// 对象销毁时会触发
console.log('验证码销毁')
}
})