Forem

Cover image for Laravel send OTP using Vue js (beta) and whatsapp
Gagang
Gagang

Posted on

Laravel send OTP using Vue js (beta) and whatsapp

Penggunaan Laravel dan Vue js untuk fungsi send OTP pada saat akses panel auth.

masih terkendala session yang kurang stabil. paling tidak ku simpan dulu lah.

<?php
class auth {
public function akses_nomor_kirim_otp($nomor)
{
// Logic
$kode = rand(1000,9999);
$user = $this->userRepo->findDataPhone($nomor);
$this->userRepo->updateOTP($nomor, $kode);
$this->notifService->kirimNotifWa($user->phone_code.ltrim($user->phone_number, '0'), $this->formatPesanAksesWa($kode));
$this->successSendOTP($nomor);
return response()->json([
'status' => 'success',
'message' => 'OTP sent successfully',
]);
}
public function akses_nomor_kirim_otp_sesi_waktu_mulai($nomor)
{
// Get current time
$currentTime = Carbon::now()->timestamp;
// Set session
Session::put($nomor.'startTime', $currentTime);
Session::put($nomor.'remainingTime', 60);
return response()->json([
'startTime' => Session::get($nomor.'startTime'),
'remainingTime' => Session::get($nomor.'remainingTime')
]);
}
public function akses_nomor_kirim_otp_sesi_waktu_batas($nomor)
{
// Get remaining time from session
$startTime = Session::get($nomor.'startTime', 0);
$remainingTime = Session::get($nomor.'remainingTime', 0);
// Calculate remaining time
$elapsedTime = time() - $startTime;
$remainingTime = max(0, $remainingTime - $elapsedTime);
return response()->json(['remainingTime' => $remainingTime]);
}
}

dan component vue js -nya ini jujur aja masih ga terlalu paham. yang penting jalan lah

<template>
<div class="text-center">
<!-- Tombol link untuk mengirim OTP -->
<div class="my-4">
<a class="rounded-lg text-sm px-4 py-2 mt-5 outline outline-offset-2 outline-1 outline-primary-800 text-primary-700 hover:text-primary-900" href="#" @click.prevent="sendOTP" v-if="!countdownStarted">
Kirim Kode OTP
</a>
</div>
<!-- Penampil waktu mundur -->
<div id="countdown" class="block">
<div class="text-xs text-gray-500" v-if="countdownStarted" >{{ countdownText }}</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
phoneNumber: null,
countdownSeconds: null,
countdownInterval: null,
countdownStarted: false,
};
},
computed: {
countdownText() {
var minutes = Math.floor(this.countdownSeconds / 60);
var remainingSeconds = this.countdownSeconds % 60;
return 'Dapat mengirim lagi dalam waktu: ' + minutes + ' menit ' + remainingSeconds + ' detik';
}
},
methods: {
sendOTP() {
console.log('Mengirim kode OTP ke nomor handphone:', this.phoneNumber);
var apiUrl = 'localhost.test/akses/kirim-otp/' + encodeURIComponent(this.phoneNumber);
fetch(apiUrl)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Gagal mengirim OTP');
}
})
.then(data => {
console.log('Respons dari server:', data);
this.getRemainingTimeFromServer();
this.startCountdown();
})
.catch(error => {
console.error('Terjadi kesalahan:', error);
});
},
startCountdown() {
this.requestTimeStart();
this.countdownStarted = true;
this.countdownInterval = setInterval(() => {
if (this.countdownSeconds > 0) {
this.countdownSeconds--;
} else {
clearInterval(this.countdownInterval);
this.countdownStarted = false;
}
}, 1000);
},
getRemainingTimeFromServer() {
var apiUrl = 'localhost.test/akses/kirim-otp/' + encodeURIComponent(this.phoneNumber) + '/sesi-waktu-batas';
fetch(apiUrl)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Gagal mendapatkan sisa waktu dari server');
}
})
.then(data => {
console.log('Sisa waktu dari server:', data.remainingTime);
// Update countdownSeconds with the remaining time from the server
this.countdownSeconds = data.remainingTime;
// Start the countdown
if (this.countdownSeconds > 0) {
this.startCountdown();
}
})
.catch(error => {
console.error('Terjadi kesalahan:', error);
});
},
requestTimeStart() {
var apiUrl = 'localhost.test/akses/kirim-otp/' + encodeURIComponent(this.phoneNumber) + '/sesi-waktu-mulai';
fetch(apiUrl)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error('Gagal membuat sesi waktu mulai ke server');
}
})
.catch(error => {
console.error('Terjadi kesalahan:', error);
});
}
},
created() {
const pathSegments = window.location.pathname.split('/');
const phoneIndex = pathSegments.indexOf('akses');
if (phoneIndex !== -1 && pathSegments[phoneIndex + 1] && /^\d+$/.test(pathSegments[phoneIndex + 1])) {
this.phoneNumber = pathSegments[phoneIndex + 1];
} else {
console.error('Nomor handphone tidak valid atau tidak ditemukan dalam path URL.');
}
// Mengambil sisa waktu dari server setelah komponen dibuat
this.getRemainingTimeFromServer();
},
beforeDestroy() {
// Menyimpan waktu mulai ke server saat komponen dihancurkan
// Anda mungkin ingin menyimpan waktu yang tersisa juga
// Untuk kesederhanaan, contoh ini hanya menyimpan waktu mulai
var apiUrl = 'localhost.test/akses/kirim-otp/' + encodeURIComponent(this.phoneNumber) + '/sesi-waktu-mulai';
fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
startTime: new Date().getTime(),
}),
})
.then(response => {
if (!response.ok) {
throw new Error('Gagal menyimpan waktu mulai ke server');
}
})
.catch(error => {
console.error('Terjadi kesalahan:', error);
});
}
};
</script>
<style>
/* Gaya CSS komponen di sini */
</style>

nah, kalo ini dimodif dikit pake redis

<?php
use Illuminate\Support\Facades\Cache;
class auth
{
public function akses_nomor_kirim_otp_sesi_waktu_mulai($nomor)
{
// Get current time
$currentTime = Carbon::now()->timestamp;
// Set session using Redis
Cache::put($nomor.'startTime', $currentTime, 60); // Expires in 60 seconds
Cache::put($nomor.'remainingTime', 60, 60); // Expires in 60 seconds
return response()->json([
'startTime' => Cache::get($nomor.'startTime'),
'remainingTime' => Cache::get($nomor.'remainingTime')
]);
}
public function akses_nomor_kirim_otp_sesi_waktu_batas($nomor)
{
// Get remaining time from session
$startTime = Cache::get($nomor.'startTime', 0);
$remainingTime = Cache::get($nomor.'remainingTime', 0);
// Calculate remaining time
$elapsedTime = time() - $startTime;
$remainingTime = max(0, $remainingTime - $elapsedTime);
return response()->json(['remainingTime' => $remainingTime]);
}
}

Top comments (0)