How to compare otp number without reload page which send in sms? - laravel

I want to compare otp numbers, which i type in textbox and sms otp sent to the number through api calling controller in laravel.
i use laravel5.6 and php 7.2.3
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
i want to compare textbox otp number and sms otp number sent through api calling and redirect with another controller in laravel5.6

The thing is you must store your otp in database or in session variable.
(Documentation: https://laravel.com/docs/5.8/eloquent)
You can store otp in database like
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
User::where('phone_number',$req->txtnumber)->update(['otp'=>$otp]);
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it using eloquent in Laravel using
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = User::where('phone_number', $phone_number)->first()->otp;
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
after entering the correct otp clear that in database.
Or you can use session.you can use session in two ways
1.php default session
2.Laravel Session
let us see php default session
(documentation:https://www.php.net/manual/en/book.session.php)
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
session_start();
$_SESSION['otp'] = $otp
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
session_start();
$otp = $_SESSION['otp']
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}
let us use laravel session
(documentation: https://laravel.com/docs/5.2/session)
//important
use Illuminate\Support\Facades\Session;
public function makeRequest(Request $req)
{
$client = new Client();
$otp=rand(10000,4);
// $data=
$data = array('adhar'=>$req->txtadharnumber,'drp'=>$req->drpcode,'mobilenumber'=>$req->txtnumber);
//CHANGES
Session::put('otp',$otp)
$response = $client->request('POST','http://192.168.1.9/jaincountapi/public/api/otpsms',[
'form_params'=>[
'adharcardnumber'=>$req->txtadharnumber,
'mobilecode'=>$req->drpcode,
'mobilenumber'=>$req->txtnumber,
'otp'=>$otp
]
]);
$response = $response->getBody();
return json_decode($response,true);
}
you can retrieve it by
//important
use Illuminate\Support\Facades\Session;
public function otpverify(Request $req)
{
$otpenter=$req->txtotp;
//CHANGES
$otp = Session::get('otp') //best way to use is flash. see the full documentation
if ($otpenter==$otp)
{
return redirect()->action('JaincountController#create')
}
else
{
return view('jaincount_user/verification');
}
}

Related

send an email in Laravel on a create function

send an email in Laravel on a create function but not able to do
this is my store function
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}
// use this
use Illuminate\Support\Facades\Mail;
// send mail via mail
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
By extraInfo you can pass values to the mail template as you want.
// for your code
public function store()
{
$input = $request->all();
$user = \AUTH::guard()->user();
$input['created_by'] = $user->id;
\Log::info('$input'.json_encode([$input]));
$bulkLabSample = $this->bulkLabSampleRepository->create($input);
Mail::send('your-view-blade', ['extraInfo' => $extraInfo], function ($message) {
$message->to('email#email.com');
$message->subject('your subject here');
});
Flash::success(__('messages.saved', ['model' => __('models/bulkLabSamples.singular')]));
return redirect(route('bulkLabSamples.index'));
}

Limit Queued Job in Laravel

I have an email service that allows me to send only 60 emails per hour (1/minute).
So that is why i m trying to write an application that respect the service provider's restrictions,
I m dispatching emails to bulk users at once via queue jobs,Please take a look at the code
public function sendEmails(CreateEmailRequest $request)
{
$data = [];
$users = User::find($request->to);
$subject = $request->subject;
$body = $this->fileUpload($request->body);
foreach ($users as $user) {
$vars = array(
"{{name}}" => $user->name,
"{{email}}" => $user->email,
);
$body = strtr($body, $vars);
$data['body'] = $body;
$data['user'] = $user;
$data['subject'] = $subject;
dispatch(new SendEmailJob($data))->onQueue('mail');
}
Flash::success('Email sent successfully.');
return redirect(route('emails.index'));
}
here is SendEmailJob Class code
public function handle()
{
$data = $this->data;
$body = $data['body'];
$user = $data['user'];
$subject = $data['subject'];
// list($body, $user, $subject) = $this->data;
Mail::send('mail.email', ['body' => $body], function ($m) use ($user, $subject) {
$m->to($user->email)->subject($subject);
});
}
public function middleware()
{
return Limit::perMinute(1);
}
when I run php artisan queue:work it process all jobs at once..
can you please tell me how can I achieve this?
I can not use spatie/laravel-rate-limited-job-middleware because my server does not support Redis.
Can you please tell me i m doing wrong ?
You can use Job Middleware with a rate limiting
in the boot method of your AppServiceProvider
RateLimiter::for('emails', function($job) {
return Limit::perMinute(1);
});
and add middleware to the job:
use Illuminate\Queue\Middleware\RateLimited;
public function middleware()
{
return [new RateLimited('emails')];
}

Laravel Create a request internally Resolved

I need to recreate a resquest so that it behaves like a call via api to go through the validator, but my $request->input('rps.number') always arrives empty, although I can see the data in the debug
I also couldn't get it to go through the laravel validator
I can't use a technique to make an http call, because I need to put this call in a transaction
<?php
$nota = new stdClass();
$rps = new stdClass();
$rps->numero = (int)$xml->Rps->IdentificacaoRps->Numero;
$rps->serie = (string)$xml->Rps->IdentificacaoRps->Serie;
$rps->tipo = (int)$xml->Rps->IdentificacaoRps->Tipo;
$nota->rps = $rps;
$controller = new NotaController(new Nota());
$content = new StoreNotaRequest();
$content->request->add($nota);
$result = $controller->store($content);
StoreNotaRequest
<?php
class StoreNotaRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
$request = $this->request;
return [
'rps.numero' => 'required_with:rps|numeric|between:1,999999999999999',
'rps.serie' => 'required_with:rps|string|min:1|max:5',
'rps.tipo' => 'required_with:rps|integer|in:1,2,3'
];
}
}
NotaController
<?php
class NotaController extends Controller
{
private Nota $nota;
public function __construct(Nota $nota)
{
$this->nota = $nota;
}
public function store(StoreNotaRequest $request): JsonResponse
{
// $validated = $request->validated();
try {
$nota = DB::transaction(function () use ($request) {
$request->input('rps.numero');
});
return response()->json($nota);
} catch (Throwable $e) {
return response()->json($data, 409);
}
}
}
Solution
the solution was a little too verbose, I believe it is possible to solve with less code.
more does what it needs to go through the validation of the data contained in the StoreNotaRequest
and it returns an http response, in addition to being able to put all these isolated calls in a single transaction
DB::beginTransaction();
$errors = [];
foreach ($itens as $item) {
$controller = new NotaController(new Nota());
$request = new StoreNotaRequest();
$request->setMethod('POST');
$request->request->add($nota);
$request
->setContainer(app())
->setRedirector(app(Redirector::class))
->validateResolved();
$response = $controller->store($request);
if ($response->statusText() !== 'OK') {
$errors[$item->id] = 'ERROR';
}
}
if (count($errors) === 0) {
DB::commit();
} else {
DB::rollBack();
}

Laravel cannot create cookie from other function

I have this function
function setAuth(){
if(Cookie::has('accesstoken')){
$value = Cookie::get('accesstoken');
echo 'tokense';
return $value;
}
else{
echo 'no token';
$client= new Client();
$response= $client->post('getToken'
]);
$res= json_decode($response->getBody()->getContents()) ;
Cookie::queue(Cookie::make('accesstoken',$res->access_token,10));
return $res->access_token;
}
}
If I call this function like http://localhost:8000/setAuth, this can create cookie.
But in Other function I want to use it like this
function order(Request $request)
{
$client= new Client();
//if get cookie
$token= $this->setAuth();
}
calling order function can't create cookie, Where am I missing.
Queued cookies don't get sent by Laravel until you return a response of some kind.
function order(Request $request)
{
$client= new Client();
//if get cookie
$token= $this->setAuth();
// here we go!
return 'ok';
}

Google Client API setAccessToken() before isAccessTokenExpired() results in invalid credentials

I am working with the Google Client API in Laravel to allow my users to sync their calendars with Google. Everything works, but the issue I am running into is when their tokens expire they are getting an "Invalid Credentials" error, in order to fix it they have to log out and log back in which I am trying to avoid.
I don't understand why setAccessToken() is to be called before isAccessTokenExpired().
I need to check if the access token is expired before I set it but if I do it this way then isAccessTokenExpired() always returns true.
Any ideas would be helpful. Thanks!
Here is my code:
GoogeServiceController.php
class GoogleServiceController extends Controller
{
protected $client;
protected $service;
public function __construct()
{
$client = new Google_Client();
$client->setAuthConfig(Config::get('google_config.web'));
$client->setAccessType('offline');
$client->addScope(Google_Service_Calendar::CALENDAR);
$service = new Google_Service_Calendar($client);
$this->client = $client;
$this->service = $service;
}
public function oauth(Request $request)
{
if (App::environment('local')) {
$this->client->setRedirectUri('http://esm.development.com/oauth');
} else {
$this->client->setRedirectUri('https://essentialstudiomanager.com/oauth');
}
if (is_null($request->user()->refresh_token)) {
$this->client->setApprovalPrompt("force");
}
if (!$request->has('code')) {
$auth_url = $this->client->createAuthUrl();
$filtered_url = filter_var($auth_url, FILTER_SANITIZE_URL);
return redirect($filtered_url);
} else {
$this->client->authenticate($request->code);
if (is_null($request->user()->refresh_token)) {
$refresh_token = $this->client->getRefreshToken();
$user = $request->user();
$user->refresh_token = $refresh_token;
$user->save();
}
$request->session()->put('access_token', $this->client->getAccessToken());
$notification = ['message' => 'Your calendar is now synced with your Google Calendar.', 'alert-type' => 'success'];
return redirect()->route('home')->with($notification);
}
}
}
GoogleEventController.php
public function updateGoogleEvent($request, $event, $title, $description, $start, $end)
{
if ($request->session()->has('access_token')) {
$this->client->setAccessToken(session('access_token'));
if ($this->client->isAccessTokenExpired()) {
$this->client->refreshToken($request->user()->refresh_token);
$request->session()->put('access_token', $this->client->getAccessToken());
$this->client->setAccessToken(session('access_token'));
}
} else {
return redirect()->route('oauthCallBack');
}
$users_calendar = $this->service->calendars->get('primary');
$get_event = $this->service->events->get('primary', $event->google_event_id);
$get_event->setSummary($title);
$get_event->setDescription($description);
$start_date = new Google_Service_Calendar_EventDateTime();
$start_date->setDateTime($start);
$start_date->setTimeZone($users_calendar->timeZone);
$get_event->setStart($start_date);
$end_date = new Google_Service_Calendar_EventDateTime();
$end_date->setDateTime($end);
$end_date->setTimeZone($users_calendar->timeZone);
$get_event->setEnd($end_date);
$updatedEvent = $this->service->events->update('primary', $get_event->getId(), $get_event);
}

Resources