A
A
Alexander Stepanov2019-04-17 06:45:43
Yii
Alexander Stepanov, 2019-04-17 06:45:43

Why does captcha return "Incorrect verification code"?

Created a blog with a "margin" on the portfolio. Everything worked perfectly on LAN, but uploading git to google cloud on forms with captcha is always the same answer "Wrong verification code".
I noticed this after I reinstalled the system and now it's the same on the LAN (also from the git)
There are no errors anywhere in the logs.
View:

<?php $form = ActiveForm::begin(['id' => 'contact-form']); ?>

        <?= $form->field($model, 'name')->textInput(['placeholder' => 'Пожалуйста представьтесь'])->label(false) ?>

        <?= $form->field($model, 'email')->input('email', ['placeholder' => 'Ваш email для ответа'])->label(false) ?>

        <?= $form->field($model, 'subject')->textInput(['placeholder' => 'Тема сообщения'])->label(false) ?>

        <?= $form->field($model, 'body')->textarea(['rows' => 6, 'placeholder' => 'Текст сообщения'])->label(false) ?>

        <?= $form->field($model, 'verifyCode')->widget(Captcha::class, [
            'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
        ])->label('Введите проверочный код') ?>

        <div class="form-group">
            <?= Html::submitButton('Отправить', ['class' => 'btn formBtn', 'name' => 'contact-button']) ?>
        </div>

        <?php ActiveForm::end(); ?>

Controller:
use src\forms\ContactForm;
use src\services\ContactService;
use Yii;
use yii\web\Controller;

class ContactController extends Controller
{
    private $service;

    public function __construct($id, $module, ContactService $service, $config = [])
    {
        parent::__construct($id, $module, $config);
        $this->service = $service;
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                'backColor' => 0xF1F1F1,
                'foreColor' => 0xEE7600,
            ],
        ];
    }

    /**
     * @return mixed
     */
    public function actionIndex()
    {
        $form = new ContactForm();
        if ($form->load(Yii::$app->request->post()) && $form->validate()) {
            try {
                $this->service->send($form);
                Yii::$app->session->setFlash('success', 'Спасибо, что написали мне. Я отвечу Вам при первой возможности.');
                return $this->goHome();
            } catch (\Exception $e) {
                Yii::$app->errorHandler->logException($e);
                Yii::$app->session->setFlash('error', 'Извините. Возникла какая-то ошибка отправки сообщения.');
            }

            return $this->refresh();
        }
        return $this->render('index', [
            'model' => $form,
        ]);
    }

}

Model/shape:
use Yii;
use yii\base\Model;
use yii\helpers\Url;

/**
 * ContactForm is the model behind the contact form.
 */
class ContactForm extends Model
{
    public $name;
    public $email;
    public $subject;
    public $body;
    public $verifyCode;


    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // name, email, subject and body are required
            [['name', 'email', 'subject', 'body'], 'required'],
            // email has to be a valid email address
            ['email', 'email'],
            // verifyCode needs to be entered correctly
//            ['verifyCode', 'captcha'],
            ['verifyCode', 'captcha', 'captchaAction' => Url::to(['/contact/captcha']), 'when'=>function($model) {
                return Yii::$app->user->isGuest;
            }],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => 'Имя',
            'email' => 'Email',
            'subject' => 'Темя',
            'body' => 'Текст сообщения',
            'verifyCode' => 'Проверочный код',
        ];
    }
}

Service:
use src\forms\ContactForm;
use yii\mail\MailerInterface;

class ContactService
{
    private $adminEmail;
    private $mailer;

    public function __construct($adminEmail, MailerInterface $mailer)
    {
        $this->adminEmail = $adminEmail;
        $this->mailer = $mailer;
    }

    /**
     * @param \src\forms\ContactForm $form
     */
    public function send(ContactForm $form): void
    {
        $sent = $this->mailer->compose()
            ->setTo($this->adminEmail)
            ->setSubject($form->subject)
            ->setTextBody($form->body)
            ->send();

        if (!$sent) {
            throw new \RuntimeException('Sending error.');
        }
    }
}

It was done using Dmitry Eliseev's non-standard technology (I'll earn money and charge him for the course - I downloaded it from the torrent).
Everything works on another site - a slightly modified store at its rate, but ... I
found similar questions on Google, but none of them suited me.
I would like to understand

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question