Post request with Guzzle to sending email with queue not working - php

I developed send email service(with queue) with Laravel lumen. That's working fine with Postman.
When I request that service from another Laravel application with Guzzle post request, reach to API controller and return response but queue is not working also email not send.
Request from Laravel application:
code :
public function request($method,$requestUrl,$formParams = [],$headers = []) : string {
$client = new Client([
'base_url' => 'https://localhost/email-service/api/'
]);
// if(isset($this->secret)){
// $headers['Authorization'] = $this->secret;
// }
$headers['Authorization'] = 'secret';
$response = $client->request(
$method,
$requestUrl,
[
'form_params' => $formParams,
'headers' => $headers
]
);
return $response->getBody()->getContents();
}
Email service(lumen):
code :
public function SendGeneralEmail(Request $request){
$this->validate($request,[
'form_name' => 'required',
'subject' => 'required',
'body' => 'required',
'to' => 'required',
'app_name' => 'required',
]);
$data = $request->all();
dispatch(new SendEmailJob($data));
return $this->successResponse('SuccessFully sent mail',$data);
}

Related

Replacing Google OAuth API in Laravel

I have an app that I was tasked with to renew. However, the app runs a Google OAuth API to authenticate the users. However, this instance of the API no longer works as the company has changed name and thus the old mail domain no longer exists.
E.g: name#companyname.com
Is there a way for me to change the instance of the api so it will allow any gmail to get in.
here's my current controller for the oauth
public function checkUserByToken($social_token)
{
$client = new \Google_Client(['client_id' => env('GOOGLE_CLIENT_ID', '')]);
$payload = $client->verifyIdToken($social_token);
if ($payload) {
$validator = Validator::make($payload, [
'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
]);
if ($validator->fails()) {
return false;
}
$user = User::where('email', $payload['email'])->first();
if (!$user) {
$data = [
'name' => $payload['family_name'],
'full_name' => $payload['name'],
'email' => $payload['email'],
'password' => bcrypt(str_random(8)),
];
$user = $this->createUser($data);
}
$user->forceFill([
'email' => $payload['email'],
'email_verified_at' => Carbon::now(),
])->save();
$tokenResult = $user->createToken('Personal Access Client');
$token = $tokenResult->token;
$token->expires_at = Carbon::now()->addMonth();
$token->save();
$data = [
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
'full_name' => $payload['name'],
'avatar' => $payload['picture'],
'role' => $user->role,
'section' => isset($user->section)?$user->section->name:"",
'id' => $user->id
];
return $data;
} else {
return false;
}
}
I have tried replacing the google OAuth API in .env and change
$validator = Validator::make($payload, [
'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
]);
to
$validator = Validator::make($payload, [
'email' => 'required|email|regex:/(.*)newcompany.com$/i',
]);
no avail as I think the google API outside of sending back auth token also send back something else but I'm not sure what it is.

HTTP request to the http address of an API with Laravel

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Auth,Str,Storage,Image,DB;
use GuzzleHttp\Client;
class SmsController extends Controller
{
//
public function index()
{
//
$data =[
'title'=>$description='Envoie SMS',
'description'=>$description,
//'membre'=>$membre,
//'membres'=>$membres,
//'departement'=>$departement,
];
return view('sms.index',$data);
}
public function envoyer(Request $request)
{
//
$senderid=$request->senderid;
$numero=$request->numero;
$message=$request->message;
$dateheure=date('Y-m-d h:i:s', time());
//dd($dateheure);
$client = new Client();
$res = $client->request('POST', 'http://africasmshub.mondialsms.net/api/api_http.php', [
'form_params' => [
'username' => 'test',
'password' => '0758224162',
'sender' => 'test',
'text' => 'Hello World!',
'type' => 'text',
'numero' => $numero,
'message' => $message,
'datetime' => $dateheure,
]
]);
//dd($res);
$success = 'message envoyé avec succès';
return redirect()->route('sms')->withSuccess($success);
}
}
Hello everyone ! I have a problem with Laravel, I cannot make an Http request to the Http address of an API which should allow me to send SMS. I am sending you as attachments the source code of my Controller "Smscontroller.php". I need your help. Thank you !

Return JSON details of failed validation with Laravel 8

I'm creating an endpoint to store an Office with two fields: name, address.
When validation fails laravel returns status 200 and a welcome page. It should return 4xx and error details with JSON, shouldn't it? I tried to catch an exception (ValidationError) but I don't get the error details.
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'address' => 'required'
]);
// if validation failed, 4xx?
// logic to create a model here
return $office; // everything fine, 201 and object details
}
I'm testing it with unit test and postman:
public function testValidationFailed()
{
$payload = [
"wrongfield" => "Example Name"
];
$response = $this->postJson('/api/offices/', $payload);
and with postman the content-type is application/json
EDITED
Postman was messing up the headers. httpie and curl get the correct response with this code and the accepted answer's.
You can use Validator instead like so
$validator = Validator::make($request->all(), [
'name' => 'required',
'address' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 404);
}
Or you can use validator() helper method
validator($request->all(), [
'name' => 'required',
'address' => 'required'
])->validate();
This will automatically validate and response back with errors and it also, works with web and api endpoints.

Laravel Passport logout test returning 200 when it should be denied

I'm trying to write a test for the logout procedure for Laravel Passport. But every time I run it i am receiving the error expected 401 but got 200 which means that its not actually logging out the user.
The Logout functionality in the AuthController is as follows;
public function logout(Request $request): JsonResponse
{
$accessToken = $request->user()->token();
$refreshToken = DB::table('oauth_refresh_tokens')
->where('access_token_id', $accessToken->id)
->update([
'revoked' => true
]);
$accessToken->revoke();
return response()->json(['message' => 'Successfully logged out']);
}
This works fine, but the testing is the issue.
My test is as follows;
public function testUserIsLoggedOutProperly(): void
{
$user = factory(User::class)->create();
Passport::actingAs($user);
$this->json('GET', 'api/user')->assertStatus(JsonResponse::HTTP_OK);
$this->json('GET', 'api/logout')->assertStatus(JsonResponse::HTTP_OK);
$this->json('GET', 'api/user')
->assertStatus(JsonResponse::HTTP_UNAUTHORIZED);
}
The last assert is actually returning a HTTP_OK (200)
Any help would be greatly appreciated.
It's just a quick reflexion (not tested) but you should do your test with :
get a new token, (I think you can do that without api call)
call "api/logout" with token get in 1)
check with assertDatabaseHas function
$response = $this->json('POST','oauth/token', [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'client-id',
'client_secret' => 'client-secret',
'username' => 'taylor#laravel.com',
'password' => 'my-password',
'scope' => '',
]
]);
$response->assertStatus(JsonResponse::HTTP_OK);
$token = json_decode((string) $response->getBody(), true)['access_token'];
$this->json('POST', 'api/logout')->withHeaders([
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
])->assertStatus(JsonResponse::HTTP_OK);
$this->assertDatabaseHas('oauth_refresh_tokens', [
'access_token_id' => $token,
'revoked' => true
]);

How can I assign 'g-recaptcha-response' to a variable? With 'g-recaptcha-response' being a parameter inside $request->validate([])

So what i want is to put 'g-recaptcha-response' in a variable to be able to use it in my condition to verify recaptcha but I haven't been able to do this. Is there any way to only use recaptcha field from the array inside validate() because my code as it is, redirects me back to homepage. It goes straight to else statement.
public function contactanospost(Request $request){
$request->validate([
'nombre' => 'required|distinct',
'telefono'=> 'required|telefono',
'correo' => 'required|email',
'mensaje' => 'required',
'g-recaptcha-response' => 'required|captcha',
]);
if(POST['g-recaptcha-response']){ /*here I am trying to
check with a condition if recaptch was really validated once the form is submitted */
$token= POST['g-recaptcha-response'];
$client = new Client();
$response = $client->post('https://www.google.com/recaptcha/api/siteverify', [
'form_params' => array('secret' => 'mycaptchakey',
'response'=> $token /*Checking with google parameters for recaptcha if the user was indeed verified */
)
]);
$resultados = json_decode($response->getBody()->getContents()); //decode with json
if($resultados->success){ /*if this was a success then return a page with parameters from google recaptcha such as: secret, response, remote ip.*/
dd($resultados); /*show the results from verified user and that recaptcha is working*/
$contactanos = Contactanos::create($request->all());/* and create all fields for model Contactanos*/
Mail::to('some#mail')->send(new enviacorreo($contactanos)); /* since it is a contact form then send all the information to some mail*/
\Session::flash('flash_message','Tu mensaje ha sido enviado!'); /* send a message with "email delivered" verification*/
return redirect()->back();
}
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
}
else{
return redirect('/');
}
}
I'm now able to access request properties using input() what got me confused were my if statements. The real problem is that after:
$resultados = json_decode($response->getBody()->getContents());
next if statement is not getting the expected success but instead it goes straight to else with robot message:
else{
\Session::flash('flash_message','Robot');
return redirect('/');
}
You can access all the properties of the request from the $request object by calling e.g, $request->input('g-recaptcha-response') This is the basic of Accessing the request if you have read through the documentation.
I can lend you a snippet to do this perhaps it will help you rethink how you're validating the captcha:
use GuzzleHttp\Client;
....
$v = Validator::make($request->all(), [
'name' => 'required|min:2',
'email' => 'required|email|max:255',
'subject' => 'sometimes|required|min:3',
'message' => 'required|min:3',
'g-recaptcha-response' => 'sometimes|required'
], [
'g-recaptcha-response.*' => 'Please verify that you are not a robot'
]);
if ($v->fails()) {
return [
'success' => 'no',
'data' => $v->errors()->first()
];
}
if ($request->get('g-recaptcha-response')) {
$verify_form = [
'secret' => env('GOOGLE_RECAPTCHA_SECRET', 'default'), //better to save in config though
'response' => $request->get('g-recaptcha-response')
];
$client = new Client();
$verify_serial = '?'.http_build_query($verify_form);
$response = $client->post('https://www.google.com/recaptcha/api/siteverify'.$verify_serial);
$arrayed_response = json_decode($response->getBody()->getContents(), true);
if(!$arrayed_response['success']){
Log::notice('There is something wrong with the verification of recaptcha: ',$arrayed_response );
return [
'success' => 'no',
'data' => 'Something went wrong in verification process',
];
}
}
The idea is that, you build the secret and response body and use that to request validation check from Google just as you have done but building the query as query parameters directly to the url.
PS: you don't have to return the snippet :)

Categories