tangniyuqi 2018-09-27 17:45:51 3921次浏览 1条回复 1 0 0
namespace api\modules\v1\actions\captcha;
use Yii;
use micsay\captcha\CaptchaBuilder;

class IndexAction extends \yii\rest\Action
{
    public $width = 76;

    public $height = 38;

    public $foreColor = 0x2299EE; //0x2040A0

    public $transparent = true;

    /**
     * @inheritdoca
     */
    public function run()
    {
        $captcha = new CaptchaBuilder();
        $captcha->fixedVerifyCode = YII_ENV_TEST ? 'testme' : null;
        $captcha->width = $this->width;
        $captcha->height = $this->height;
        //$captcha->backColor = 0x000000;
        //$captcha->padding = 5;
        //$captcha->offset = 4;
        $captcha->minLength = 4;
        $captcha->maxLength = 4;
        $captcha->foreColor = $this->foreColor;
        $captcha->transparent = $this->transparent;
        $captcha->testLimit = 3;
        $base64 = $captcha->base64();

        $code = $captcha->getPhrase();
        $code = strtolower($code);
        Yii::$app->cache->set($this->generateCacheKey($code), $code, 60);

        return $base64;
    }

    /**
     * @param string $code
     * @return bool
     * @throws Exception
     */
    public function validate($code)
    {
        if (Yii::$app->cache->get($this->generateCacheKey($code)) === $code) {
            Yii::$app->cache->delete($this->generateCacheKey($code));

            return true;
        }

        return false;
    }

    /**
     * @return string
     */
    private function generateCacheKey($code)
    {
        return base64_encode(Yii::$app->request->getRemoteIP().Yii::$app->request->getUserAgent().$code);
    }
}
您需要登录后才可以回复。登录 | 立即注册