Here is example of Google Recaptcha which I made into custom form element.
Recaptcha.php
namespace Frontend\Forms\lib;
use Phalcon\Forms\Element;
class Recaptcha extends Element
{
public function render($attributes = null)
{
$config = loadConfigFile('config');
$language = \Phalcon\DI::getDefault()->getSession()->language;
$html = '<script src="https://www.google.com/recaptcha/api.js?hl='. $language .'"></script>';
$html.= '<script>function recaptchaCallback() { document.getElementById("recaptchaTemp").setAttribute("value", "checked") }</script>';
$html.= '<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="'. $config->sensitive->recaptcha->publicKey .'"></div>';
$html.= '<input type="hidden" name="recaptchaTemp" id="recaptchaTemp" value=""/>';
return $html;
}
}
RecaptchaValidator.php
namespace Frontend\Forms\lib;
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)
{
$config = loadConfigFile('config');
$params = [
'secret' => $config->sensitive->recaptcha->privateKey,
'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;
}
}
Usage in form class
$recaptcha = new lib\Recaptcha($name);
$recaptcha->addValidator(new lib\RecaptchaValidator([
'message' => $this->translations->public->validation->recaptcha
]));
return $recaptcha;
You can see the folder structure by the namespaces.