The send_otp_email_notification
function sends an email notification when a One-Time Password (OTP) is generated. It retrieves user information based on a provided phone number, constructs an email message with the OTP details, and sends it to the user’s email address.
Parameters
- $otp (string): The generated OTP code.
- $phoneNumber (string): The phone number associated with the OTP.
- $agent (string): The agent associated with the OTP.
Code Example
/**
* Sends an email notification when an OTP is generated.
*
* @param string $otp The generated OTP code.
* @param string $phoneNumber The phone number associated with the OTP.
* @param string $agent The agent associated with the OTP.
*/
function send_otp_email_notification($otp, $phoneNumber, $agent) {
// Get the user information by phone number
$user = \WP_SMS\Helper::getUserByPhoneNumber($phoneNumber);
// Get the current user's email
if (is_user_logged_in()) {
$current_user = wp_get_current_user();
$email = $current_user->user_email;
} elseif ($user) {
// Use the email from the user fetched by phone number
$email = $user->user_email;
} else {
// If no user is found, handle accordingly (e.g., log an error, skip sending email)
error_log('No user found with the given phone number.');
return;
}
$subject = 'Your OTP Code';
$message = "Hello,
Your OTP code is: $otp
Phone Number: $phoneNumber
Agent: $agent
Thank you.";
// Optional: Set additional headers.
$headers = array(
'Content-Type: text/plain; charset=UTF-8',
'From: [email protected]',
'Reply-To: [email protected]'
);
// Send the email using wp_mail.
wp_mail($email, $subject, $message, $headers);
}
// Hook the function to the custom action.
add_action('wp_sms_otp_generated', 'send_otp_email_notification', 10, 3);
Usage
To use this function, ensure that the wp_sms_otp_generated
action is triggered whenever an OTP is generated. The function will handle sending the email notification to the appropriate user based on the provided phone number and the logged-in status of the user.