thinkphp整合極驗驗證碼,寫下自己的筆記,其實很簡單。
首先第一步是下載代碼
注冊之后獲得最新的ID和KEY,然后和PHP版的服務器代碼
第二步就是代碼整理
下載后的代碼是:
官方有對類庫的說明寫的很詳細,這里不就不多說了。
在配置中添加配置項:
然后對核心類庫添加命名空間:
然后修改名稱為:GeetestLib.class.php
然后就是在公共類中添加驗證碼初始化的方法(其實就是官方提供的稍微修改下)
public function getVerify(){
$GtSdk?=?new?GeetestLib(C('GEE_ID'),?C('GEE_KEY'));
$user_id?=?"web";
$status?=?$GtSdk->pre_process($user_id);
session('gtserver',$status);
session('user_id',$user_id);
echo?$GtSdk->get_response_str();
}
然后在頁面上處理下極驗。
Title
body?{
margin:?50px?0;
text-align:?center;
}
.inp?{
border:?1px?solid?gray;
padding:?0?10px;
width:?200px;
height:?30px;
font-size:?18px;
}
.btn?{
border:?1px?solid?gray;
width:?100px;
height:?30px;
font-size:?18px;
cursor:?pointer;
}
#embed-captcha?{
width:?300px;
margin:?0?auto;
}
.show?{
display:?block;
}
.hide?{
display:?none;
}
#notice?{
color:?red;
}
嵌入式Demo,使用表單形式提交二次驗證所需的驗證結果值
用戶名:
密? ? 碼:
正在加載驗證碼......
請先拖動驗證碼到相應位置
var?handlerEmbed?=?function?(captchaObj)?{
$("#embed-submit").click(function?(e)?{
var?validate?=?captchaObj.getValidate();
if?(!validate)?{
$("#notice")[0].className?=?"show";
setTimeout(function?()?{
$("#notice")[0].className?=?"hide";
},?2000);
e.preventDefault();
}
});
//?將驗證碼加到id為captcha的元素里
captchaObj.appendTo("#embed-captcha");
captchaObj.onReady(function?()?{
$("#wait")[0].className?=?"hide";
});
//?更多接口參考:http://www.geetest.com/install/sections/idx-client-sdk.html
};
$.ajax({
//?獲取id,challenge,success(是否啟用failback)
url:?"{:U('Home/Index/getVerify',array('t'=>time()))}",?//?加隨機數防止緩存
type:?"get",
dataType:?"json",
success:?function?(data)?{
//?使用initGeetest接口
//?參數1:配置參數
//?參數2:回調,回調的第一個參數驗證碼對象,之后可以使用它做appendTo之類的事件
initGeetest({
gt:?data.gt,
challenge:?data.challenge,
product:?"float",?//?產品形式,包括:float,embed,popup。注意只對PC版驗證碼有效
offline:?!data.success?//?表示用戶后臺檢測極驗服務器是否宕機,一般不需要關注
},?handlerEmbed);
}
});
初始化完成之后的提交時前段會自動驗證,然后提交給后臺之后處理方法是:
public function test()
{
$GtSdk?=?new?GeetestLib(C('GEE_ID'),?C('GEE_KEY'));
$user_id?=?session('user_id');
if?($_SESSION['gtserver']?==?1)?{
$result?=?$GtSdk->success_validate($_POST['geetest_challenge'],?$_POST['geetest_validate'],?$_POST['geetest_seccode'],?$user_id);
if?($result)?{
echo?'Yes!';
}?else{
echo?'No';
}
}else{
if?($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode']))?{
echo?"yes";
}else{
echo?"no";
}
}
}
由于這里的類庫是直接實例化的,所以在頭部需要use下對應的類庫
然后在頁面上就可以看到效果了。
這里有個坑需要注意了,現在申請的ID和KEY才能用到最新版的。我之前申請的ID和KEY死活不通過,后來換新的就好了。過幾天把這個驗證碼替換到博客上。
參考地址:http://www.loveteemo.com/article-134.html