Files

66 lines
1.6 KiB
PHP

<?php
namespace App\Services\Auth;
use App\Models\OtpCode;
use App\Services\Sms\IranPayamakService;
class OtpService
{
protected IranPayamakService $iranPayamakService;
public function __construct(IranPayamakService $iranPayamakService)
{
$this->iranPayamakService = $iranPayamakService;
}
public function generateCode(): string
{
return (string) random_int(1000, 9999);
}
public function sendForPhone(string $phone, int $minutes = 3): OtpCode
{
$code = $this->generateCode();
$expiresAt = now()->addMinutes($minutes);
$otpCode = OtpCode::updateOrCreate(
['phone' => $phone],
['code' => $code, 'expires_at' => $expiresAt]
);
$this->sendSms($phone, $code);
return $otpCode;
}
public function verifyCode(string $phone, string $code): bool
{
$deleted = OtpCode::where('phone', $phone)
->where('code', $code)
->where('expires_at', '>', now())
->delete();
return (bool) $deleted;
}
public function existsValid(string $phone, string $code): bool
{
return OtpCode::where('phone', $phone)
->where('code', $code)
->where('expires_at', '>', now())
->exists();
}
private function sendSms(string $phone, string $code): void
{
try {
$this->iranPayamakService->sendPattern($phone, 'verify_code', [
'otp' => $code,
'status' => 'بازنشانی رمز عبور',
]);
} catch (\Exception $e) {
}
}
}