Google reCaptcha 自定義驗證元件

use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;

class RecaptchaValidator extends Validator implements ValidatorInterface
{
    public function validate(\Phalcon\Validation $validation, $attribute)
    {
        $value = $validation->getValue('g-recaptcha-response');
        $ip = $validation->request->getClientAddress();
        if (!$this->verify($value, $ip)) {
            $validation->appendMessage(new Message($this->getOption('message'), $attribute, 'Recaptcha'));
            return false;
        }
        return true;
    }
    
    protected function verify($value, $ip)
    {
        $params = [
            'secret' => 'YOUR_RECAPTCHA_SECRET_KEY',
            'response' => $value,
            'remoteip' => $ip
        ];
        $response = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?' . http_build_query($params)));
        return (bool) $response->success;
    }
}

Phalcon 形式的示例用法:

$reCaptchaField->addValidator(new \RecaptchaValidator([
    'message' => 'Your reCaptcha error message'
]));