Hi i want to consume a service and i use laravel 5.x with guzzle with this code i can send request and i use the correct api-key but i always obtain 403 forbidden....
public function searchP(Request $request) {
$targa = request('targa');
$client = new \GuzzleHttp\Client();
$url = 'https://xxx.it/api/xxx/xxx-number/'.$targa.'/xxx-xxxx';
$api_key ='xxxxxcheepohxxxx';
try {
$response = $client->request(
'GET',
$url,
['auth' => [null, $api_key]]);
} catch (RequestException $e) {
var_dump($e->getResponse()->getBody()->getContent());
}
// Get JSON
$result = $response->json();
}
Why? I cannot understand
In postman i write in the AUTHORIZATION label this
key : x-apikey
value: xxxxxcheepohxxxx
Add to header
and it works.
i also tried this
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey', $api_key
]
]);
} catch .....
but doesn't work
Thx
it should be this, you have a typo
.... try {
$response = $client->request('GET',$url,[
'headers' => [
'x-apikey'=> $api_key
]
]);
} catch .....
Related
I'm trying to make a request with my other endpoint, using GuzzleHttp in laravel, but the token isn't authorizing it. I believe it's in the way I'm going. Anyone know how to fix this? This is my code.
public function productRecommendation($rowPerPage,$keywords, $page){
try{
$request = request();
$token = $request->bearerToken();
$client = new \GuzzleHttp\Client();
$promise = $client->request('GET', $this->sellerUrl.'recommended', [
'headers' => ['Authorization' => "Bearer {$token}"],
'query' =>
[
'rowPerPage' => $rowPerPage,
'page' => $page,
'keywords' => $keywords,
],
]);
$response = (string) $promise->getBody();
return json_decode($response, true);
}
catch (Exception $e){
return $e;
}
}
You are getting the bearer token of your first application using $request->bearerToken() and send it to your second application for authorization which must not work;
You need to get a working token from your second application. You can either generate a token in your second application and copy it inside your current $token variable, or first call the login endpoint of second application with your credentials and use that token.
By the way, Laravel now supports a guzzle wrapper called Illuminate\Support\Facades\Http which makes things lot easier, you can rewrite your code like this:
public function productRecommendation($rowPerPage, $keywords, $page)
{
try{
$token = "some valid token from second endpoint";
$response = Http::withToken(
$token
)->get(
$this->sellerUrl . 'recommended',
[
'rowPerPage' => $rowPerPage,
'page' => $page,
'keywords' => $keywords,
]
);
return response()->json(
json_decode($response->body(), true)
);
}
catch (Exception $e){
return $e;
}
}
I am trying to recreate the following Tesco API code using Symfony\Component\HttpFoundation:
<?php
// This sample uses the Apache HTTP client from HTTP Components (http://hc.apache.org/httpcomponents-client-ga/)
require_once 'HTTP/Request2.php';
$request = new Http_Request2('https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}');
$url = $request->getUrl();
$headers = array(
// Request headers
'Ocp-Apim-Subscription-Key' => '{subscription key}',
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
);
$url->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_GET);
// Request body
$request->setBody("{body}");
try
{
$response = $request->send();
echo $response->getBody();
}
catch (HttpException $ex)
{
echo $ex;
}
?>
I am new to php in general and I am undertaking my first Symfony project. Could somebody please help me will recreating the above code using Symfony HttpFoundation instead?
I have tried the following code, and I return nothing:
$req2 = Request::create('https://dev.tescolabs.com/grocery/products/?query={query}&offset={offset}&limit={limit}', 'GET');
$req2->headers->set('Ocp-Apim-Subscription-Key', 'my_api_key');
$params = array(
'query' => 'walkers',
'offset' => '0',
'limit' => '10',
);
$req2->query->add($params);
try
{
$response = new Response();
var_dump($response);die;
}
catch (HttpException $ex)
{
die ('EX: '.$ex);
}
Symfony's Request class is used for an incoming request to Symfony. Maybe you should have a look at Guzzle to use an object-oriented approach to create a request or cURL like proposed in Symfony2 - How to perform an external Request
This question already has answers here:
(Updated) Laravel PUT Method Not Working
(2 answers)
Closed 5 years ago.
updated - I am trying to use the API documentation to change the billing date using the PUT method in Http and Guzzle in Laravel, however, the JSON file would return but it will not change the billing date at all.
Reference 1: The official documentation about changing the billing date.
Reference2: their sample code in detail (sorry about the bad formatting):
<?php
$request = new HttpRequest();
$request->setUrl('https://subdomain.chargify.com/subscriptions/subscriptionId.json');
$request->setMethod(HTTP_METH_PUT);
$request->setHeaders(array('content-type' => 'application/json'));
$request->setBody('{"subscription":{"next_billing_at":"2018-12-15"}}');
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
My code in detail:
public function changeYearlySubscriptionBillingDate(Request $request)
{
$user = $request->user();
$subscriptionId = $user->subscription->subscription_id;
$nextBilling = Carbon::now()->addYear();
$hostname = env('CHARGIFY_HOSTNAME');
$headers = [
'authorization' => 'Basic ANIDIANDIAJIJCQ',
'content-type' => 'application/json'
];
$body = ["subscription" => ["next_billing_at" =>[ $nextBilling ]]];
$config = [
'headers' => $headers,
'form_param' => $body
];
$client = new Client($config);
$res = $client->put("https://$hostname/subscriptions/$subscriptionId.json");
echo $res->getBody();
}
Changes this:
echo $response->getBody();
to
dd($response->getBody());
and repost the response data is returned.
I connecting to API by Guzzle:
$client = new Client();
try {
$res = $client->post( 'xxx' . $this->url , [
'headers' => $headers,
'json' => $data,
]);
} catch( Exception $e ) {
echo json_decode( $e->getResponse()->getBody(), true );
}
And it's working but when it's 'catch', I need to get code from response but I getting:
Server error: `POST XXXXX` resulted in a `555 Error` response: {"status":"ERROR","errors":[{"message":"Subscribers already exists in this subscribers list","code":1304}]}
And I can't get the code. How to do this?
UPDATE
Here is screen with full response.
Just extract the response from the exception. Guzzle throws a special BadResponseException in case of failure, so take a look at this class.
try {
// ...
} catch (BadResponseException $exception) {
// 555
$exception->getCode();
$appError = json_decode(
$exception->getResponse()->getBody()->getContents(),
true
);
// 1304
$appErrorCode = $appError['errors'][0]['code'];
}
I am new to guzzle and I'm testing its api, when I want to run the sample code in guzzle site, a blank page was shown in the browser. What is the problem?
Thanks.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
require_once "vendor/autoload.php";
try {
$client = new Client();
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$response = $client->send($request, [
'timeout' => 30,
]);
echo $response->getBody();
} catch (RequestException $e) {
echo $e->getRequest();
if ($e->hasResponse()) {
echo $e->getResponse();
}}