401 Unauthorized using Guzzle but works from curl - php

I'm trying to fetch orders data on my InfusionSoft account. I can do it using the command line but the Guzzle code gives me 401 Unathorized. I suppose I'm doing something wrong and not able to pass the params correctly. Can someone help?
Here's what works from the command line:
curl -G --data "access_token=abcdefgh12345678" https://api.infusionsoft.com/crm/rest/v1/orders?limit=1&offset=100&order_by=id
And here's the (supposedly) equivalent code from PHP:
$token = 'abcdefgh12345678';
$requestBody = array('access_token' => $token);
$url = 'https://api.infusionsoft.com/crm/rest/v1/orders?limit=1&offset=100&order_by=id';
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', $url, array(
'form_params' => $requestBody
));
$response = (string) $response->getBody();

You are sending a GET request, and a GET request cannot contain a body.
curl uses --data according to the request method, so for GET it adds the access token to the URL as a GET-parameter. So should you.

Related

How to change PHP Guzzle from postman to Laravel Guzzle format

I'm struggling to change the code from PHP-Guzzle format that i get from postman to Laravel-Guzzle format.
So i want to use this PHP - Guzzle from Postman.
$client = new Client();
$headers = [
'Authorization' => 'OAuth realm="xxx",oauth_consumer_key="xxx",oauth_token="xxx",oauth_signature_method="HMAC-SHA256",oauth_timestamp="123",oauth_nonce="xxx",oauth_version="1.0",oauth_signature="xxx"',
'Cookie' => 'NS_ROUTING_VERSION=LAGGING'
];
$request = new Request('GET', 'https://domainname.com/record/1234', $headers);
$res = $client->sendAsync($request)->wait();
echo $res->getBody();
from above code. i need to convert to laravel format. and here is what i've done
use GuzzleHttp\Client;
$guzzle = new Client;
$header = [
'Authorization' => 'OAuth realm="xxx",oauth_consumer_key="xxx",oauth_token="xxx",oauth_signature_method="HMAC-SHA256",oauth_timestamp="123",oauth_nonce="xxx", oauth_version="1.0", oauth_signature="xxx"',
'Cookie' => 'NS_ROUTING_VERSION=LAGGING'
];
$response = $guzzle->request('GET', 'https://domainname.com/record/1234', $header);
dd($response->getBody());
but i got error
Client error: `GET https://domainname.com/record/1234` resulted in a `401 Unauthorized` response: {"type":"https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2","title":"Unauthorized","status":401,"o:error (truncated...)
i tried to solve it but cannot. please help how to make it work on laravel.
401 Unauthorized mean you are missing something like: token. That's mean your connection have been made but your credencials is't right. So nothing wrong with your code.

How to get GuzzleHttp 7.x resolved request url from response

How to get the URI/URL of the request sent, from the response?
<?php
// Create a client with a base URI
$client = new GuzzleHttp\Client(['base_uri' => 'https://example.com/api/']);
// Send a request to https://example.com/api/test
$response = $client->request('GET', 'test');
// I want the following line to print 'https://example.com/api/test'
var_export( $response->getUrl() );
Note: I want something like the last line of the above snippet to work.

PHP: How to make an api call with api key authorization using Guzzle?

I'm trying to create a client to connect an IBM-Watson bot service using Guzzle for an application constructed in Laravel, but it fails when attempting to create a new session of the service, I got the error 401: Unauthorized. I'm not using basic authorization, instead I'm trying to connect by api-key authorization.
function start_bot_session() {
//Api Key de Watson.
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//ID bot (Watson).
$assistant_id = '9c1c426d-cd33-49ec-a3bc-f0835c3264b5';
//URL service.
$url = 'https://gateway.watsonplatform.net/assistant/api/v2/assistants/';
//Method for start a new session.
$method = $assistant_id.'/sessions?version=2019-02-28';
$client = new \GuzzleHttp\Client(["base_uri" => $url]);
$response = $client->request('POST', $method, [
'headers' => [
'Authorization:' => $api_key
]
]);
return response;
}
Is there any way I can fix this?
Can you tell me some alternatives to make api call instead of using Guzzle?

Send Body as raw using Guzzle

I am trying to use Guzzle to send POST request to my web service. this service accepts body as raw. It works fine when I use postman but I doesn't using Guzzle. when using Guzzle, I get only the webservice description as I put the web service URL in the browser.
here is my code:
$body = "CA::Read:PackageItems (CustomerId='xxxxxx',AllPackages=TRUE);";
$headers = [
....
....
];
$client = new Client();
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',$headers,$body);
echo $body = $response->getBody();
seems headers or body doesn't pass through.
Try like this
$response = $client->request('POST', 'http://172.19.34.67:9882/TisService',['headers' => $headers, 'body' => $body]);
I have recently had to implement Guzzle for the first time and it is a fairly simple library to use.
First I created a new Client
// Passed in our options with just our base_uri in
$client = new Client(["base_uri" => "http://example.com"]);
I then created a POST request, not how I am using new Request instead of $client->request(... though. This doesn't really matter to much that I've used new Request though.
// Create a simple request object of type 'POST' with our remaining URI
// our headers and the body of our request.
$request = new Request('POST', '/api/v1/user/', $this->_headers, $this->body);
so in essence it would look like:
$request = new Request('POST', '/api/v1/user/', ['Content-Type' => "application/json, 'Accept' => "application/json"], '{"username": "myuser"}');
$this->headers is a simple key-value pair array of our request headers making sure to set the Content-Type header and $this->body is a simple string object, in my case it forms a JSON body.
I can simply then just call the $client->send(... method to send the request like:
// send would return us our ResponseInterface object as long as an exception wasn't thrown.
$rawResponse = $client->send($request, $this->_options);
$this->_options is a simple key-value pair array again simple to the headers array but this includes things like timeout for the request.
For me I have created a simple Factory object called HttpClient that constructs the whole Guzzle request for me this is why I just create a new Request object instead of calling $client->request(... which will also send the request.
What you essentially need to do to send data as raw is to json_encode an array of your $data and send it in the request body.
$request = new Request(
'POST',
$url,
['Content-Type' => 'application/json', 'Accept' => 'application/json'],
\GuzzleHttp\json_encode($data)
);
$response = $client->send($request);
$content = $response->getBody()->getContents();
Using guzzle Request GuzzleHttp\Psr7\Request; and Client GuzzleHttp\Client

Google REST-ful call + Guzzle: Setting Authorization Token

I'm new with Guzzle and I'm trying to make a call to Google API with it. I tried in this way with no luck: PHP + Guzzle, Sending Authorization Key in Header
Here is my code:
$client = new Client();
try {
$request = $client->get ( 'https://www.googleapis.com/analytics/v3/data/ga' );
/*setting Authorization token*/
$request->addHeader('authorization', $accessToken);
$query = $request->getQuery();
$query->set('ids', $profileId);
$query->set('start-date', $startDate);
$query->set('end-date', $endDate);
$query->set('metrics', $metrics);
$response = $request->send();
$response = $response->json();
var_dump($response);
} catch (ClientErrorResponseException $e) {
var_dump($e->getMessage ());
}
I'm always getting this response:
"Client error response
[status code] 401
[reason phrase] Unauthorized
[url] https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3AXXXXXX&start-date=2014-07-01&end-date=2014-07-01&metrics=ga%3Asessions"
I've tried the same call using PHP curl and I'm getting the correct response, but I'd like to use Guzzle in this project.
What is the correct way to do this
array ( CURLOPT_HTTPHEADER => array( 'Authorization: Bearer ' . $accessToken )) with Guzzle?
The problem you are having is that a Request to the Google Analytics API is sent as a Get. Adding a header is used for a POST.
$request->addHeader('authorization', $accessToken);
The following will add the accessToken as part of the Get in your request.
$query->set('oauth_token', $accessToken);

Categories