Wordpress

Woocommerce Basic E-mail Verification (Without Plugin)

Woocommerce Basic E-mail Verification (Without Plugin)

Merhaba arkadaşlar bu yazımızda Woocommerce e-ticaret sitemizde müşterilerimizin eklenti olmadan e-mail doğrulama (E-mail Verification) nasıl yapılır onu göstereceğim. Keyifli okumalar.

Öncelikle e-mail doğrulaması iki farklı yöntem ile doğrulama sağlayabiliriz; birinci yöntem, kullanıcılara bir kod göndererek ve bu kodu form ile doğrulama yapabiliriz. ikinci yöntem, kullanıcılara doğrulama bağlantısı göndererek ve bu bağlantıya tıklandığında doğrulama gerçekleşmiş olur. Yazımızda her iki yöntemi de kullanacağız, hangisini kullanmak sizin tercihinize bağlı.

Woocommerce müşteri e-posta doğrulama için kodları Görünüm > Tema düzenleyici > function.php sayfasının en alt satırına aşağıdaki kodları adımları takip ederek işlemi tamamlayabilirsiniz.

wordpress görünüm tema düzenleyici funciton php

Nasıl Çalışır

Woocommerce e-ticaret sitelerine kayıt olan müşterilerin e-mail doğrulama (e-mail Verification) yapılması 2 yöntem var.

  1. Müşterinin e-posta adresine bir doğrulama kodu gönderilerek ve bu doğrulama kodunu hesabım panelinde girerek doğrulama işlemi gerçekleştirilmektedir.
  2. Müşterinin e-posta adresine bir doğrulama bağlantısı gönderilerek ve bu bağlantıya tıkladığında hesabım paneline yönlendirilerek hesap doğrulaması sağlanmaktadır.

Her iki yöntemde sık kullanılan bir yöntemdir, her iki yöntemi de kullanmakta kişisel bir tercih meselesidir.
Daha gelişmiş bir doğrulama için Customer Email Verification for WooCommerce kullanabilirsiniz.

Kod ile doğrulama

Hesabı oluşturmak için kullandığınız e-posta adresine bir doğrulama kodu gönderilerek hesap oluşturma işlemi gerçekleşir.

Bkz: wc_light_or_dark, wc_hex_darker

Woocommerce e-mail settings
WooCommerce e-postalarını özelleştirme

1. Adım: E-posta Gönderim Şablon Fonksiyonu

Müşterilerimize e-posta gönderme fonksiyonu aşağıdadır. Müşterilere gönderilen e-mail’leri özelleştirmek istiyorsanız WordPress admin panelinde WooCommerce > Ayarlar > E-postalar takip ederek özelleştirebilirsiniz.

function send_verification_mail($email, $verify)
{
	$base         = get_option('woocommerce_email_base_color');
	$base_text    = wc_light_or_dark($base, '#202020', '#ffffff');
	$text         = get_option('woocommerce_email_text_color');
	$link_color   = wc_hex_is_light($base) ? $base : $base_text;


	$headers = array('Content-Type: text/html; charset=UTF-8', 'From: ' . get_bloginfo('name') . ' <' . sanitize_email($email) . '>');
	$to = sanitize_email($email);
	$subject = get_bloginfo('name') . " - E-posta Adresinizi Doğrulayın";
	$heading = "Neredeyse tamamladınız!";

	$message = <<<HTML
			<b>Merhaba</b><br>
			<p>E-posta adresinizi doğrulamak için lütfen aşağıdaki kodu kullanın.</p>
			<h3 style="background:{$base}; color: {$base_text}; padding: .5em; width: auto; text-align:center;display:inline-block">{$verify}</h3>
			<p>Bu kodun kullanım süresi 24 saattir.</p>
			<hr>
			<p>Bu talebi siz yapmadıysanız, lütfen bu e-postayı dikkate almayın. Yardım için, <a href="">Yardım merkezimiz</a> aracılığıyla bizimle iletişime geçin.</p>
			<p>Saygılarımızla</p>
	HTML;


	// Get woocommerce mailer from instance
	$mailer = WC()->mailer();

	// Wrap message using woocommerce html email template
	$wrapped_message = $mailer->wrap_message($heading, $message);

	// Create new WC_Email instance
	$wc_email = new WC_Email;

	// Style the wrapped message with woocommerce inline styles
	$html_message = $wc_email->style_inline($wrapped_message);

	// Send the email using wordpress mail function
	$mailer->send($to, $subject, $html_message, $headers);
}

2. Adım: E-posta Gönderme

Müşteri kayıt işlemi sırasında doğrulama e-postası otomatik bir şekilde gönderilmektedir.

//üyelik kaydı sırasında doğrulama e-postası gönderme 
add_action('woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3);

function action_woocommerce_created_customer($customer_id, $new_customer_data)
 {
	$characters = "ABCDEFGHJKMNPQRSTUVWXYZ1234567890";
	$charLength = "6"; //karakter uzunluğu
	$randomCode = substr(str_shuffle($characters), 0, $charLength); // Rasgele kod oluşturur
	$nowDate    = wp_date('Y-m-d H:i:s'); //bugünün tarihi

	$metaData = array('activationKey' => $randomCode, 'verificationStatus' => 0, 'sendTime' => $nowDate); // müşteri datası => [aktivasyon kodu, doğrulama durumu, tarih] bilgilerini saklar.

	update_user_meta($customer_id, 'email_verification', $metaData); //$metaData verisini ve müşteri ID'i ile birlikte saklar.

	send_verification_mail($new_customer_data['user_email'], $randomCode); //e-postayı gönder
}

3. Adım: Doğrulama

add_action('woocommerce_account_content', 'email_verification_form', 0);

function email_verification_form()
 {
	$current_user = wp_get_current_user();
	$emailVerification = get_user_meta($current_user->ID, 'email_verification', true);
	$nowDate = wp_date('Y-m-d H:i:s');

	$sendAgainForm = <<<HTML
					<form method="post" action = "">
						<div style="border:1px solid;padding:5px; display:flex;flex-direction:row;justify-content: space-between;align-items:baseline;gap:20px">
							<p>Henüz e-posta adresiniz doğrulanmadı</p>
							<input type="submit" name="reaffirmation" class="button" value="Tekrar Doğrulama Gönder" />
						</div>
					</form>
	HTML;


	//e-posta doğrulama işlemi [kod] 
	if ($emailVerification && $emailVerification['verificationStatus'] == 0) {
		echo <<<HTML
			<form method="post" >
				<div style="display:flex;flex-direction:row;justify-content: space-between;gap:20px">
						
					<input type="text" style="flex:1" name="verificationKey" id="verificationKey">
					
					<button type="submit" name="verificationSend">Doğrula</button>
				</div>
			</form>
		HTML;

		if (isset($_POST['verificationSend']) && absint($_POST['verificationSend']) == 1) {

			if (sanitize_text_field($_POST['verificationKey']) == $emailVerification['activationKey']) {
				$timeDiff = strtotime($nowDate) - strtotime($emailVerification['sendTime']);
				if ($timeDiff < 86400) {
					wc_print_notice(__("E-posta Doğrulama başarılı", "woocommerce"), "success");
					$emailVerification['verificationStatus'] = 1;

					update_user_meta($current_user->ID, 'email_verification', $emailVerification);
					header("Refresh:0");
				} else {
					wc_print_notice(__("Doğrulama kodu zaman aşamına uğramıştır.", "woocommerce"), "error");
				}
			} else {
				echo "doğrulamadı";
				echo $sendAgainForm;
			}
		} else {
			echo $sendAgainForm;
		}
	}

	//yeniden dorğulama kodu gönderme işlemi
	if (array_key_exists('reaffirmation', $_POST)) {
		$filtPost = filter_input(INPUT_POST, 'reaffirmation', FILTER_SANITIZE_SPECIAL_CHARS);
		if ($filtPost) {
			action_woocommerce_created_customer($current_user->ID, array('user_email' => $current_user->user_email));
			wc_print_notice(__("Tektar E-posta Doğrulama Gönderildi", "woocommerce"), "success");
		}
	}
}
woocommerce e-mail verification

4. Adım: Doğrulanmış Kullanıcıyı Alışverişe açma

Kullanıcı e-posta adresini doğrulamış ise alışveriş yapabilecektir.

add_filter('woocommerce_is_purchasable', 'email_verified_user_purchasable', 9999, 2);

function email_verified_user_purchasable($is_purchasable, $product)
{
	$is_purchasable = true;
	$emailVerificationGet = get_user_meta(get_current_user_id(), 'email_verification', true);
	if (is_user_logged_in()) {
		if ($emailVerificationGet && $emailVerificationGet['verificationStatus'] == 0) {
			$is_purchasable = false;
		}
	}
	return $is_purchasable;
}

5. Adım: Sonuç

Woocommerce Email verfication

Link ile doğrulama

Kullanıcılarımız e-posta adreslerini doğrulama için kod yerine şifrelenmiş bir bağlantı göndererek e-posta adresini doğrulamış oluyoruz.

1. Adım: E-posta Gönderim Şablon Fonksiyonu

function send_verification_mail($email, $verify)
{
	$base         = get_option('woocommerce_email_base_color');
	$base_text    = wc_light_or_dark($base, '#202020', '#ffffff');
	$text         = get_option('woocommerce_email_text_color');
	$link_color   = wc_hex_is_light($base) ? $base : $base_text;

	$accountLink = wc_get_account_endpoint_url('dashboard') . "?verify=" . hash_hmac('sha1', $verify, 'vonobilisim');
	$directRouting = wp_nonce_url($accountLink, 'vono-bilisim');
	//  http://www.example.com/hesabim/?verify=4be2e0a54ee570abae80b753bb1e1729b463da2f&_wpnonce=cc34317fba


	$headers = array('Content-Type: text/html; charset=UTF-8', 'From: ' . get_bloginfo('name') . ' <' . sanitize_email($email) . '>');
	$to = sanitize_email($email);
	$subject = get_bloginfo('name') . " - E-posta Adresinizi Doğrulayın";
	$heading = "Neredeyse tamamladınız!";

	$message = <<<HTML
			<b>Merhaba</b><br>
			<p>E-posta adresinizi doğrulamak için lütfen aşağıdaki butona tıkayın.</p>
			<a href="{$directRouting}" target="_blank" style="background:{$base}; color: {$base_text}; padding: .5em; width: auto; text-align:center;display:inline-block; border-radius:5px">E-posta Adresimi Doğrula</a>
			<p>Bu bağlantının kullanım süresi 24 saattir.</p>
			<hr>
			<p>Bu talebi siz yapmadıysanız, lütfen bu e-postayı dikkate almayın. Yardım için, <a href="">Yardım merkezimiz</a> aracılığıyla bizimle iletişime geçin.</p>
			<p>Saygılarımızla</p>
	HTML;


	// Get woocommerce mailer from instance
	$mailer = WC()->mailer();

	// Wrap message using woocommerce html email template
	$wrapped_message = $mailer->wrap_message($heading, $message);

	// Create new WC_Email instance
	$wc_email = new WC_Email;

	// Style the wrapped message with woocommerce inline styles
	$html_message = $wc_email->style_inline($wrapped_message);

	// Send the email using wordpress mail function
	$mailer->send($to, $subject, $html_message, $headers);
}

2. Adım: E-posta Gönderme

//üyelik kaydı sırasında doğrulama e-postası gönderme 
add_action('woocommerce_created_customer', 'action_woocommerce_created_customer', 10, 3);
function action_woocommerce_created_customer($customer_id, $new_customer_data)
 {
	$characters = "ABCDEFGHJKMNPQRSTUVWXYZ1234567890";
	$charLength = "15"; //karakter uzunluğu
	$randomCode = substr(str_shuffle($characters), 0, $charLength); // Rasgele kod oluşturur
	$nowDate    = wp_date('Y-m-d H:i:s'); //bugünün tarihi

	$metaData = array('activationKey' => $randomCode, 'verificationStatus' => 0, 'sendTime' => $nowDate); // müşteri datası => [aktivasyon kodu, doğrulama durumu, tarih] bilgilerini saklar.

	update_user_meta($customer_id, 'email_verification', $metaData); //$metaData verisini ve müşteri ID'i ile birlikte saklar.

	send_verification_mail($new_customer_data['user_email'], $randomCode); //e-postayı gönder
}

3. Adım: Doğrulama

Kullanıcılar link ile doğrulamada e-postasına gönderilen bağlantıya tıklayarak WooCommerce müşteri paneline yönlendirilerek doğrulama işlemi sağlanmış olur, herhangi bir işlem yapmasına gerekmemektedir.

add_action('woocommerce_account_content', 'email_verification_form', 0);

function email_verification_form()
{
	$current_user = wp_get_current_user();

	$emailVerification = get_user_meta($current_user->ID, 'email_verification', true);
	$nowDate = wp_date('Y-m-d H:i:s');

	$sendAgainForm = <<<HTML
					<form method="post" action = "">
						<div style="border:1px solid;padding:5px; display:flex;flex-direction:row;justify-content: space-between;align-items:baseline;gap:20px">
							<p>Henüz e-posta adresiniz doğrulanmadı</p>
							<input type="submit" name="reaffirmation" class="button" value="Tekrar Doğrulama Gönder" />
						</div>
					</form>
	HTML;



	//e-posta doğrulama işlemi [link] 
	if ($emailVerification && $emailVerification['verificationStatus'] == 0) {
		$verify = isset($_GET['verify']) ? sanitize_text_field($_GET['verify']) : "";
		$wpnonceV = isset($_GET['_wpnonce']) ? sanitize_text_field($_GET['_wpnonce']) : "";

		if (!empty($verify) && wp_verify_nonce($wpnonceV, 'vono-bilisim')) {
			if (hash_hmac('sha1', $emailVerification['activationKey'], 'vonobilisim')  == $verify) {
				$timeDiff = strtotime($nowDate) - strtotime($emailVerification['sendTime']);
				if ($timeDiff < 86400) {
					wc_print_notice(__("E-posta Doğrulama başarılı", "woocommerce"), "success");
					$emailVerification['verificationStatus'] = 1;

					update_user_meta($current_user->ID, 'email_verification', $emailVerification);
					header("Refresh:0");
				} else {
					wc_print_notice(__("Doğrulama kodu zaman aşamına uğramıştır.", "woocommerce"), "error");
				}
			} else {
				echo $sendAgainForm;
			}
		} else {
			echo $sendAgainForm;
		}
	}

	//yeniden dorğulama kodu gönderme işlemi
	if (array_key_exists('reaffirmation', $_POST)) {
		$filtPost = filter_input(INPUT_POST, 'reaffirmation', FILTER_SANITIZE_SPECIAL_CHARS);
		if ($filtPost) {
			action_woocommerce_created_customer($current_user->ID, array('user_email' => $current_user->user_email));
			wc_print_notice(__("Tekrar E-posta Doğrulama Gönderildi", "woocommerce"), "success");
		}
	}
}

4. Adım: Doğrulanmış Kullanıcıyı Alışverişe açma

Kullanıcı e-posta adresini doğrulamış ise alışveriş yapabilecektir.

add_filter('woocommerce_is_purchasable', 'email_verified_user_purchasable', 9999, 2);

function email_verified_user_purchasable($is_purchasable, $product)
{
	$is_purchasable = true;
	$emailVerificationGet = get_user_meta(get_current_user_id(), 'email_verification', true);
	if (is_user_logged_in()) {
		if ($emailVerificationGet && $emailVerificationGet['verificationStatus'] == 0) {
			$is_purchasable = false;
		}
	}
	return $is_purchasable;
}

5. Adım: Sonuç

Woocommerce Email Verification

Arkadaşlar yazımızda hata ve önerileriniz olursa lütfen yorum yapmayı unutmayın.
Unutmayın! Paylaşmak; kazanmanın en hızlı ve kolay yoludur. Bir sonraki makalede görüşmek dileğiyle esen kalın.

İçeriğimi beğendin mi? Bana destek olup bir kahve ısmarlayabilirsiniz. Çok teşekkür ederim!

Bu makale yardımcı oldu mu?
EvetHayır

Paylaş

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir