CSRF token from HTML sending to API

I need to send email in my mobile app via phpmaker custom endpoint .

i found a way to make a custom page return json .

<?php

namespace PHPMaker2024\smartportalent;

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;

use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/../vendor/autoload.php'; // Adjust path if needed

header('Content-Type: application/json');

// Handle POST request

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

$input = json_decode(file_get_contents('php://input'), true);



// Validate input

if (!isset($input['memoTitle'], $input['memoContent'], $input['recipients'])) {

    http_response_code(400);

    echo json_encode(['success' => false, 'message' => 'Missing required fields']);

    exit;

}



//$memoId = $input['memoId'];

$memoTitle = $input['memoTitle'];

$memoContent = $input['memoContent'];

$recipients = $input['recipients'];

$sender = $input['sender'] ?? 'support@smartmastry.com';



$failedRecipients = [];

$successCount = 0;



foreach ($recipients as $recipient) {

    if (filter_var($recipient, FILTER_VALIDATE_EMAIL)) {

        $emailSent = sendMemoEmail($recipient, $memoTitle, $memoContent, $sender);

        if ($emailSent) {

            $successCount++;

        } else {

            $failedRecipients[] = $recipient;

        }

    } else {

        $failedRecipients[] = $recipient;

    }

}





if (count($failedRecipients) > 0) {

    echo json_encode([

        'success' => true,

        'message' => "Emails sent to {$successCount} recipients, but failed for: " . implode(', ', $failedRecipients)

    ]);

} else {

    echo json_encode([

        'success' => true,

        'message' => "Emails successfully sent to all {$successCount} recipients"

    ]);

}

exit;

}

// Function to send memo via PHPMailer
function sendMemoEmail($to, $subject, $content, $from)
{

$mail = new PHPMailer(true);

try {

    // Server settings

    // $mail->SMTPDebug = SMTP::DEBUG_SERVER;

    $mail->isSMTP();

    $mail->Host = 'mail.smartmastry.com';

    $mail->SMTPAuth = true;

    $mail->Username = 'support@smartmastry.com';

    $mail->Password = '*******';

    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

    $mail->Port = 465;



    // Recipients

    $mail->setFrom('support@smartmastry.com', ' EMEMO');

    $mail->addAddress($to);

    $mail->addReplyTo('support@smartmastry.com', ' EMEMO');



    // Content

    $mail->isHTML(true);

    $mail->Subject = $subject;



    $mail->Body = "

    <!DOCTYPE html>

    <html>

    <head>

        <title>" . htmlspecialchars($subject) . "</title>

        <style>

            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }

            .memo-container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 5px; }

            .memo-header { background-color: #911f0f; color: white; padding: 15px; border-radius: 5px 5px 0 0;text-align:center; display: flex; justify-content: center; align-items: center;}

            .memo-content { padding: 20px; background-color: #f9f9f9; }

            .memo-footer { padding: 15px; text-align: center; font-size: 12px; color: #777; }

        </style>

    </head>

    <body>

        <div class='memo-container'>

            <div class='memo-header'>

                <img src='img/elogo.png' alt=' Logo' style='max-width: 100px;'>

                <h2>" . htmlspecialchars($subject) . "</h2>

            </div>

            <div class='memo-content'>

                {$content}

            </div>

            <div class='memo-footer'>

                <p>This is an automated message from  Memorandum System. Please do not reply to this email.

All correspondence should be addressed to the Memorandum System.</p>

            </div>

        </div>

    </body>

    </html>";



    return $mail->send();

} catch (Exception $e) {

    return false;

}


}

exit;

?>

This works well in my phpmaker web app . i only have issues when i use in the mobile app . This is my request:

 // After successful submission, call the email sending endpoint

      try {

        const emailResponse = await fetch(`${API_BASE_URL}/sendmemoemails`, {

          method: 'POST',

          headers: {

            'Content-Type': 'application/json',

            'X-Authorization': `Bearer ${jwtToken}`

          },

          body: JSON.stringify({

            memoRef: document.querySelector('input[name="Ref"]').value,

            memoTitle: document.querySelector('input[name="memoTitle"]').value,

            memoTo: document.getElementById('memoToHidden').value,

            memoFrom: document.querySelector('input[name="memoFrom"]').value,

            memoContent: document.getElementById('memoContent').value,

            memotype: document.querySelector('input[name="memotype"]:checked').value,

            copy1: Array.from(ccManagement).map(cb => cb.value),

            copy2: staffTags ? staffTags.split(',') : []

          })

        });

        

        if (emailResponse.ok) {

          const emailResult = await emailResponse.json();

          if (emailResult.success) {

            showToast('Notification emails sent successfully!', 'success');

          } else {

            showToast('Memo saved but email notifications failed', 'warning');

          }

        } else {

          showToast('Memo saved but email service unavailable', 'warning');

        }

      } catch (emailError) {

        console.error('Error sending emails:', emailError);

        showToast('Memo saved but email service encountered an error', 'warning');

      } 

I keep getting 400 Bad Request . i am sure its coz of CSRF token from PHPMaker missing. How do i fix this ?

i figure it out

<?php

namespace PHPMaker2024\ememoupdate;

header('Content-Type: application/json');

// Return JSON response

echo json_encode([
"csrf_name" => $TokenName,

"csrf_value" => $TokenValue
]);

exit;

this returns a valid JSON and i can use the values via GET and calling the endpoint .