Как реализовать форму подписку на новости?

Доброго дня, подскажите пожалуйста, что я делаю не так?

Логика такая:
- есть форма подписки на сайте:
<form class="footer__form" id="subscribe-form" action="<?php echo get_template_directory_uri();?>/subscribe-news/subscribe-handler.php" method="POST">
        <input class="subs_email" type="email" id="email" name="email" placeholder="Email *" required>
        <input type="text" class="subs_name" name="name" placeholder="name">
        <input type="text" class="subs_city" name="city" placeholder="city">
        <input type="date" class="subs_birthday" name="birthday" placeholder="birthday">
        <input type="button" class="subs_submit" value="Subscribe" onclick="validateAndSubmit()">
</form>
<div id="subscribe-message"></div>


Далее AJAX обработка отправки
function validateAndSubmit() {
                  let emailInput = document.getElementById("email");
                  let email = emailInput.value;

                  // Email validation using a regular expression
                  let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                  
                  if (!emailRegex.test(email)) {
                    alert("Please enter a valid email address.");
                    return;
                  }

                  let form = document.getElementById("subscribe-form");
                  let formData = new FormData(form);

                  fetch("/wp-content/themes/theme/subscribe-news/subscribe-handler.php", {
                    method: "POST",
                    body: formData
                  })
                  .then(response => response.text())
                  .then(data => {
                    document.getElementById("subscribe-message").innerHTML = data;
                  })
                  .catch(error => console.error("Error:", error));
                }


Далее в файле subscribe-handler.php подключение к базе данных, создание токена и запись его в таблицу "confirmation_tokens", далее отправка письма на указанный адрес через PHPMailer должна быть, но письмо не отравляется (токен в таблице создается). Предполагаю что я что-то не так делаю на стадии настройки PHPMailer или неправильно настраиваю SMTP яндекса (пробовал через бегет, там еще сложнее)
<?php
require 'php-mailer/Exception.php';
require 'php-mailer/PHPMailer.php';
require 'php-mailer/SMTP.php';
include 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST['email'];

    // Generate a random confirmation token
    $token = bin2hex(random_bytes(16));

    // Save the token and email to a confirmation table in the database
    $sql = "INSERT INTO confirmation_tokens (email, token) VALUES ('$email', '$token')";
    $conn->query($sql);

    // Send confirmation email using PHPMailer
    $mail = new PHPMailer(true);

    try {
        // Server settings
        $mail->isSMTP();
        $mail->Host = 'smtp.yandex.com'; // Change this to your SMTP server
        $mail->SMTPAuth = true;
        $mail->Username = 'mailer@yandex.ru'; // Your SMTP username
        $mail->Password = '89fP-43nY-2345-3211'; // Your SMTP password
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;

        // Recipients
        $mail->setFrom('mailer@yandex.ru', 'Stannis');
        $mail->addAddress($email);

        $mail->SMTPDebug = 2; // Enable verbose debugging

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Confirm Your Subscription';
        $mail->Body = "Click the following link to confirm your subscription: <a href='http://yourdomain.com/confirm.php?token=$token'>Confirm</a>";

        $mail->send();
        echo "A confirmation email has been sent. Please check your inbox to confirm your subscription.";
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }
}

$conn->close();
?>


Далее по идее должно быть так что приходит письмо с линком подтверждения и пользователь записыватся в базу
<?php
include 'db_connection.php';

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['token'])) {
    $token = $_GET['token'];

    // Check if the token exists in the confirmation table
    $result = $conn->query("SELECT email FROM confirmation_tokens WHERE token='$token'");

    if ($result->num_rows > 0) {
        // Token is valid, remove it from the confirmation table
        $row = $result->fetch_assoc();
        $email = $row['email'];
        $conn->query("DELETE FROM confirmation_tokens WHERE token='$token'");

        // Save user data to the subscribed_users table
        $conn->query("INSERT INTO subscribed_users (email) VALUES ('$email')");

        echo "Subscription confirmed successfully!";
    } else {
        echo "Invalid token or token has expired.";
    }
}

$conn->close();
?>


Буду благодарен за любую информацию!
  • Вопрос задан
  • 28 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы