<?php
namespace geetest;
use think\facade\Cache;
use think\facade\Log;
use helper\URL;

class CheckGeetestStatus
{
    const HTTP_TIMEOUT_DEFAULT = 5; // 单位：秒
    const BYPASS_URL = "https://bypass.geetest.com/v1/bypass_status.php";
    const GEETEST_STATUS_KEY = "REDIS_CHECK_GEETEST_STATUS_KEY";

    /**
     * 请求极验 bypass 接口, 将极验云服务状态记录到 redis 中
     */
    public static function checkStatus()
    {
        $url = self::BYPASS_URL;
        $params = ["gt" => config('xy_geetest.id')];
        try {
            $resBody = URL::get($url, $params);
            Log::info("gtlog: checkStatus(): 发送bypass请求, 返回body=" . $resBody);
            $res_array = json_decode($resBody, true);
            $status = $res_array["status"];
        } catch (\Exception $e) {
            $status = "fail";
        }
        if($status != null && $status != ""){
            Cache::set(self::GEETEST_STATUS_KEY, $status);
        }else{
            Cache::set(self::GEETEST_STATUS_KEY, "fail");
        }
    }

    /**
     * 获取 redis 中的极验云服务状态
     */
    public static function getGeetestStatus()
    {
        $status = Cache::get(self::GEETEST_STATUS_KEY);
        Log::info("gtlog: getsGeetestStatus(): 获取redis中缓存的极验云状态, status=" . $status);
        if(strcmp($status,"success")==0){
            return true;
        }else{
            return false;
        }
    }
}