Laravel guzzleHttp error 302 and return null value - laravel

I'm creating a Laravel project that getting data from API using guzzleHttp request. But getting error 302. I've tried using options 'allow_redirects'=>false but still not working. here piece of my code, hope you guys understand what my problem is and sorry for my bad english.
$list_receiveItem = Http::withHeaders([
'Authorization' => 'Bearer '.$data['access_token'],
'X-Session-ID' => $xsessionID,
'Accept' => 'application/json'
])->withOptions([
'allow_redirects' => false
])->get($host.'/api/item/list.do',[
'query_param' => [
'fields' => 'id,name,no',
'filter.itemType' => 'INVENTORY'
]
]);
here's the result when I dd the $list_receiveItem :
error
edited :
here's the error I got from postman :
Error From Postman

unfortunely, I send a wrong URL in http get, so that's why I'm getting this error.
I've solved this issue.
Thank you so much.

Related

Sales force refresh token could not generating in Laravel php

hope you all are doing well. I am stuck with an issue since couple of hours and could not be able to resolve it. Please have a look on error
enter image description here
I am trying to generate refresh token. Access_token generated successfully that is expired after 20 minutes. refresh token could not be generated
$client = new Client();
$res = $client
->request("POST",
"https://test.salesforce.com/services/oauth2/token",[
'body'=> json_encode([
'grant_type'=>'refresh_token',
'client_id'=>Config::get('forrest.info.client_id'),
'client_secret'=>Config::get('forrest.info.client_secret'),
'Authorization'=>'Bearer 00D3H0000008olE!ARYAQOzGGJDDIaygn7GokNk4T319XlDwwBXIDYPkJfej74dfhFT3CMDvBD2pZBQK_x.v2amiRe5Y29ZNXMp9EOA6ZTYyqrTW',
'access_token'=>'00D3H0000008olE!ARYAQOzGGJDDIaygn7GokNk4T319XlDwwBXIDYPkJfej74dfhFT3CMDvBD2pZBQK_x.v2amiRe5Y29ZNXMp9EOA6ZTYyqrTW',
])
]
);
dd ($res->getStatusCode());
any help or comment would be highly appreciated! thank for your time.
It seems like this error is returned from SalesForce API.
Looking at their documentation, it seems that they expect to see application/x-www-form-urlencoded not json.
Try out this code:
$client = new Client();
$response = $client->request('POST', '/post', [
'form_params' => [
'grant_type' => 'refresh_token',
'client_id' => Config::get('forrest.info.client_id'),
'client_secret' => Config::get('forrest.info.client_secret'),
'Authorization' => 'Bearer 00D3H0000008olE!ARYAQOzGGJDDIaygn7GokNk4T319XlDwwBXIDYPkJfej74dfhFT3CMDvBD2pZBQK_x.v2amiRe5Y29ZNXMp9EOA6ZTYyqrTW',
'access_token' => '00D3H0000008olE!ARYAQOzGGJDDIaygn7GokNk4T319XlDwwBXIDYPkJfej74dfhFT3CMDvBD2pZBQK_x.v2amiRe5Y29ZNXMp9EOA6ZTYyqrTW',
],
]);
dd($response);
let me know if it helped.
(Not an answer but too long for a comment)
This looks weird. "Authorization Bearer" should be a http header, not part of the message's body. Are you able to do what you need in plain old Postman, SoapUI etc?
Which OAuth2 flow did you use to generate this access token? Not all flows generate refresh token, for example https://help.salesforce.com/s/articleView?id=sf.remoteaccess_oauth_username_password_flow.htm&type=5 says "this flow doesn't support scopes" so you get full access - but also "this response doesn’t send a refresh token."
Have you checked the connected app (place in SF where you took client id and secret from), do the OAuth2 scopes include refresh? Did you ask for refresh token (included it in the original request's grants)?

Laravel HTTP Client Bad Request on Discord API Access Token Exchange

I have a laravel application setup and I'm configuring a Discord auth system.
I have sent & requested authorization & recieved a confirmation code back.
When I try to exchange the code for an access token I'm receiving a 400 bad request and I'm not sure why.
I'm new to laravel and can't seem to find any sort of error that may help to pin point the problem.
Controller function that discord redirects after authorization
public function exchange(Request $request) {
//exchange discord code for access_token
$code = Request::get('code',false);
$params = array(
'grant_type' => 'authorization_code',
'client_id' => env('CLIENT_ID'),
'client_secret' => env('OAUTH2_CLIENT_SECRET'),
'redirect_uri' => Request::root().'/discord/return',
'scope' => 'identify guilds guilds.join',
'code' => $code
);
$access_token = Http::withOptions([
'debug' => true,
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/x-www-form-urlencoded'
],
'json' => $params
])->post('https://discordapp.com/api/oauth2/token');
dd($access_token);
return redirect()->route('return.discord',['token' => $access_token->access_token]);
}
I've dumped out $params and all the data is pulling in as it should.
Guzzle dumps this:
[CONNECT] [FAILURE] severity: "2" message: "HTTP/1.1 400 Bad Request " message_code: "400" [MIME_TYPE_IS] message: "application/json" [FILE_SIZE_IS] message: "Content-Length: 26" bytes_max: "26" [PROGRESS] bytes_max: "26"
I know that 400 bad request means an issue with the data being sent along, but I can't figure out what I'm doing that's not producing the correct result. The documentation states the required content type which I have set, so I'm really scratching my head here.
Any help would be much appreciated.
Here's the Discord API documentation:
https://discord.com/developers/docs/topics/oauth2#authorization-code-grant
To anyone looking for an answer...
The "invalid grant" error is due to an issue with the Discord API and non-standard requests. I could not get the Laravel HTTP class request to work for exchanging the access token. Instead, I used native php cURL within Laravel.
As for the issue with receiving '400 bad request', that was due to using incorrect function withOptions() as oppossed to asJson()->withHeaders(). Thanks #Zachary Craig!
However, I could not use this in the end due to the problem described above.
If any others find a better solution, let me know :)!
For all who have the same problem.
The solution is to use ->asForm() before the post. This changes the handling of the data from json to form_params. This way the Discord API accepts the parameters.
return Http::asForm()->post($this->endpoint.'/oauth2/token', $data);

CORS Access to XMLHttpRequest at X from origin has been blocked by CORS policy

CORS Access to XMLHttpRequest at X from origin has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Hi, I am struggling to resolve my problems with CORS denying interaction of my Vue component with an external API with axios since it returns this error. I've tried both using Barryvdh's Cors header support and making a middleware and custom route. It simply won't work. Everything that has been mentioned in README.md in Barryvdh's repo has been done and unfortunately, this problem won't get resolved by any means necessary.
Here is the code, even though I don't think there's need to show since it's exactly the same as mentioned in the repo;
inside Kernel.php:
protected $middleware = [
\Barryvdh\Cors\HandleCors::class,
inside app.php (providers array):
Barryvdh\Cors\ServiceProvider::class,
config/cors.php:
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
Here's the axios get call (I've replaced my token with 'TOKEN')
methods: {
loadWeatherData: function() {
axios.get( 'http://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN' )
.then( function( response ) {
console.log( 'radi' );
}).catch( errors => {
console.log( errors+' ne radi');
});
}
},
I've composer dump-ed, nothing affected resolving the problem.
Is there something I am doing wrong and are there any solutions for this problem? Thanks in advance!
The problem here seems to be that axios likes to send its own default headers, and these don't pass the preflight check for your external request. To fix this, you will need to remove the offending headers.
I was able to recreate your error, and also to bypass the CORS issue using the code below.
let url = 'https://api.openweathermap.org/data/2.5/weather?q=London&mode=json&units=metric&appid=TOKEN';
// create a new instance so we don't delete the headers for other requests
let instance = axios.create();
// delete headers if existing
delete instance.defaults.headers.common['Accept'];
delete instance.defaults.headers.common['X-Requested-With'];
delete instance.defaults.headers.common['X-CSRF-TOKEN'];
// use the new axios instance to make your get request
instance.get(url)
.then(function(response) {
console.log(response);
}).catch( errors => {
console.log(errors + ' ne radi');
});
Hope this helps and good luck!
You can add into TrustHosts.php Middleware without doing anything extra. Read more from here https://stackoverflow.com/a/70361284/2612926

API call is working fine when called through Postman, but when called by the web page it bogs and returns failed

I have a laravel application that I'm creating. The web routes calls the API for information. When I test my API it returns data, but when the front end dev calls the API it slows the system and returns a failure. This is a simple GET that was working before but is not working now.
This is the the API call from the web:
$url = 'http://localHost:8000/api/v1.0/theater_movies';
$opts = array('http'=>array('http' => array(
'protocol_version' => 1.1,
'user_agent' => 'PHPExample',
'method' => 'GET',
'header' => "Content-type: application/json\r\n")
));
//Basically adding headers to the request
$context = stream_context_create($opts);
$getMovies = json_decode(file_get_contents($url,false,$context), true);
I'm getting the file_get_contents error:
file_get_contents(http://localhost:8000/api/v1.0/theater_movies): failed to open stream: HTTP request failed!
And this is the correct output from Postman

Laravel api header request

Route::resource('get-users','api\UserController#get_users');
Route::resource('register','api\UserController#register');
My Api is giving me the response I checked it using POSTMAN but android developer is asking me that what should he sent in header for my API .
I am not getting that how to create a header I am using laravel and I have written functions in controller .
You should go through this part of the documentation: https://laravel.com/docs/5.6/responses#attaching-headers-to-responses
He maybe wants additional header in the response.
Your return value in api\UserController can be extended like this:
return response($content)
->withHeaders([
'Content-Type' => $type,
'X-Header-One' => 'Header Value',
'X-Header-Two' => 'Header Value',
]);

Resources