PHP Guzzle with basic auth and bearer token - php

I'm trying to make a connection with infojobs-api, the documentation explian how to make it in this way:
GET /api/1/application HTTP/1.1
Host: api.infojobs.net
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,Bearer 07d18fac-77ea-461f-9bfe-a5e9d98deb3d
(https://developer.infojobs.net/documentation/user-oauth2/index.xhtml)
And this is my code:
$basicauth = new Client(['base_uri' => 'https://api.infojobs.net']);
$credentials = base64_encode(CLIENT_ID .':' . CLIENT_SECRET ) ;
$newresponse = $basicauth->request(
'GET',
'api/1/curriculum',
['debug' => true],
['auth' =>
['Basic', $credentials] ,
['Bearer', $acceso->access_token]
]
)->getBody()->getContents();
d($newresponse);
The API/Guzlle give me back this error:
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://api.infojobs.net/api/1/curriculum resulted in a 401 No Autorizado response:
{"error":"102","error_description":"Client credentials not valid","timestamp":"2016-06-25T14:08:54.774Z"}
in /app/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
So I'm doing something wrong, but I don't find what it's wrong.
Any idea, thanks.
Oskar

As I'm seeing your request's HTTP headers:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==,Bearer 07d18fac-77ea-461f-9bfe-a5e9d98deb3d
You have an Authorization header which contains a comma separated value. They are not apart from each other. So you can't benefit from Guzzle's auth key like what you have done.
What you should do is setting Authorization header manually:
$newresponse = $basicauth->request(
'GET',
'api/1/curriculum',
['debug' => true],
['headers' =>
[
'Authorization' => "Basic {$credentials},Bearer {$acceso->access_token}"
]
]
)->getBody()->getContents();

For a post call this works for me:
$guzzle = new Client(['base_uri' => self::APIURL]);
$raw_response = $guzzle->post($endpoint, [
'headers' => [ 'Authorization' => 'Bearer ' . $publicKey ],
'body' => json_encode($data),
]);
$response = $raw_response->getBody()->getContents();

Related

param is missing or the value is empty laravel

I am creating a user with the api provided. I am using Laravel and trying to store data to smartrmail and docs to create new subscriber is here https://docs.smartrmail.com/en/articles/636615-list-subscribers
Each time i send request i get following error:
Server error: `POST https://go.smartrmail.com/api/v1/lists/1sptso/list_subscribers` resulted in a `500 Internal Server Error` response: {"error":"param is missing or the value is empty: subscribers"}
{"error":"param is missing or the value is empty: subscribers"}
I am using Laravel and my code is here
Route::get('smartrmail',function(){
$headers = [
'Accept' => 'application/json',
'Authorization' => 'token f91715d5-3aac-4db3-a133-4b3a9493a9a4',
'Content-Type' => 'application/json',
];
$client = new GuzzleHttp\Client([
'headers' => $headers
]);
$data = [
"subscribers"=>[
[
"email"=> "vanhalen#example.com",
"first_name"=> "van",
"last_name"=> "halen",
"subscribed"=> true,
]
]
];
$res = $client->request('POST', 'https://go.smartrmail.com/api/v1/lists/1sptso/list_subscribers', [
'form_params' => [
$data
]
]);
return($res);
// echo $res->getStatusCode();
});
Anybody help me to figure out what is wrong here. I am following this docs
https://docs.smartrmail.com/en/articles/636615-list-subscribers
to create a new subscriber
Instead of
'form_params' => [
$data
]
use
'json' => $data
Explanation
You want to send json data (I assume that because you set header 'Content-Type' => 'application/json', which means that you are sending json), but form_params is used for application/x-www-form-urlencoded.
json sets header to application/json and sends data as json.
As you set proper header, this should work too:
'body' => $data
Proper name of param you can find in Guzzle docs, I used uploading data part.

How to used aweber api to add new subscriber usign php and aweber OAuth 2.0 Examples

i am used aweber api in add subscriber and OAuth 2.0 Examples usign php
require_once('aweber_api/aweber_api.php');
$body = [
'ad_tracking' => 'ebook',
'custom_fields' => [
'apple' => 'fuji',
'pear' => 'bosc'
],
'email' => 'anand#gmail.com',
'ip_address' => '192.168.1.1',
'last_followup_message_number_sent' => 0,
'misc_notes' => 'string',
'name' => 'Anand',
'strict_custom_fields' => 'true',
'tags' => [
'slow',
'fast',
'lightspeed'
]
];
$headers = [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'User-Agent' => 'AWeber-PHP-code-sample/1.0'
];
$listId='myid';
$accountId='myid';
$url = "https://api.aweber.com/1.0/accounts/{$accountId}/lists/{$listId}/subscribers";
$response = $client->post($url, ['json' => $body, 'headers' => $headers]);
echo $response->getHeader('Location')[0];
Error Code :
Notice: Undefined variable: client in D:\xampp\htdocs\Aweber\index.php on line 30
Fatal error: Uncaught Error: Call to a member function post() on null in D:\xampp\htdocs\Aweber\index.php:30 Stack trace: #0 {main} thrown in D:\xampp\htdocs\Aweber\index.php on line 30
The AWeber examples make use of a third party HTTP client for PHP called Guzzle. You need to set up the client first before you'll be able to use it. You can see an example of this in the code examples on AWeber's GitHub here:
https://github.com/aweber/public-api-examples/blob/ea87b1f504cb97d9081a9ea9c8737ae9fd8838e3/php/manage-subscriber
Note the call to create the client:
// Create a Guzzle client
$client = new GuzzleHttp\Client();
Documentation for Guzzle can be found here:
http://docs.guzzlephp.org/en/stable/
It also looks like you're missing the authorization header. When you make the API call it will fail unless you include your access token in the header, so don't forget that part! You can add it to your existing headers like so:
$headers = [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'User-Agent' => 'AWeber-PHP-code-sample/1.0',
'Authorization' => 'Bearer ' . $accessToken
];
Where $accessToken is a variable you initialize with your token somewhere.

How to make a HTTP POSTrequest to an API using headers

I need to integrate an API into my app.
The docs say:
HTTP POST
The following is a sample HTTP POST request and response. The placeholders shown need to be replaced with actual values.
POST /partnerhubwebservice.asmx/Authorise HTTP/1.1
Host: stage.example.co.uk
Content-Type: application/x-www-form-urlencoded
Content-Length: length
username=string&password=string
and response is:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<AuthorisationResult xmlns="http://webservice.example.co.uk/">
<Token>string</Token>
</AuthorisationResult>
Reading the docs I create this function in Laravel Controller:
public function testRld() {
$client = new GuzzleHttp\Client();
try {
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'x-www-form-urlencoded' => [
'Username' => 'MMM_bookings',
'Password' => 'passwordaaaa',
]
]);
return $res;
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$result = json_decode($response->getBody()->getContents());
return response()->json(['data' => $result]);
}
}
but I got a message:
ServerException in RequestException.php line 111: Server error: POST
http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise
resulted in a 500 Internal Server Error response: Missing parameter:
username.
When I try this at POSTMAN app everything is fine and there I get response ike:
<?xml version="1.0" encoding="utf-8"?>
<AuthorisationResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://webservice.example.co.uk/">
<RequestSuccessful>true</RequestSuccessful>
<ErrorMessage />
<Token>27d67d31-999-44e0-9851-d6f427fd2181</Token>
</AuthorisationResult>
Please help me to solve this problem? What is wrong with my code? WHy I got the error , and POSTMAN request works fine ...
Try sending username and password inside of a body as body or json, instead of as application/x-www-form-urlencoded, like so:
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'json' => [
'username' => 'MMM_bookings',
'password' => 'passwordaaaa',
]
]);
or
$res = $client->post('http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'body' => [
'username' => 'MMM_bookings',
'password' => 'passwordaaaa',
]
]);
Use form_params:
$client->request('POST', 'http://stage.example.co.uk/partnerhubwebservice.asmx/Authorise', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'username' => 'MMM_bookings',
'password' => 'password'
]
]);
The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request instead of a Laravel request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations:
Install the necessary dependencies as well:
composer require symfony/psr-http-message-bridge
composer require zendframework/zend-diactoros

POST Request works with Postman, but not with Guzzle

In my Laravel application, I periodically need to POST data to an API using Guzzle.
The API users a bearer token to authenticate, and requests and accepts raw json. To test, I accessed the API using Postman, and everything worked wonderfully.
Postman Headers:
Accept:application/json
Authorization:Bearer [token]
Content-Type:application/json
And Postman Body:
{
"request1" : "123456789",
"request2" : "2468",
"request3" : "987654321",
"name" : "John Doe"
}
Postman returns a 200, and a JSON object as a response.
Now, when I try the same with Guzzle, I get a 200 status code, but no JSON object gets returned. Here's my Guzzle implementation:
public function getClient($token)
{
return new Client([
'base_uri' => env('API_HOST'),
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
]);
}
$post = $client->request('POST', '/path/to/api', [
'json' => [
'request1' => 123456789,
'request2' => 2468,
'request3' => 987654321,
'name' => 'John Doe',
]
]);
Is there some trick to POSTing JSON with Guzzle? If not, is there a way to debug what's going on under the hood?
I cannot, for the life of me, understand what the difference is between the Postman POST and the Guzzle POST.
You have to use headers config sections for headers, not the root level.
return new Client([
'base_uri' => env('API_HOST'),
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json',
],
]);

CloudMQTT API Guzzle

I have a problem with translating curl to guzzle request.
In docs to create a user i just need to post:
$ curl -XPOST -d '{"username":"test", "password":"super_secret_password"}' -H "Content-Type:application/json" -u "$CLOUDMQTT_USER:$CLOUDMQTT_PASSWORD" https://api.cloudmqtt.com/user
In my project I cannot use curl, so i use guzzle:
$client = new Client();
$res = $client->post('https://api.cloudmqtt.com/user', ['auth' => ['xxx', 'xxx'], 'body' => ["username"=>"user", "password"=>"super_secret_password"]]);
And user is created, I can see new user on the users list on panel, but server is responsing with 500 when creating the user. What am I doing wrong? Maybe my guzzle request is wrong format? I have no idea
https://www.cloudmqtt.com/docs-api.html link to API
This will match up your Guzzle request to the curl request, although I can't say for sure that will solve your 500 error:
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'body' => json_encode(
[
"username"=>"user",
"password"=>"super_secret_password"
]
)
]
);
The differences here include setting the Content-Type header and also encoding the body to json instead of an array (which may not have an effect here?).
EDIT:
It looks like the json parameter will automatically set the header and json_encode the body for you:
$client = new Client();
$response = $client->post('https://api.cloudmqtt.com/user',
[
'auth' => ['xxx', 'xxx'],
'json' =>
[
"username"=>"user",
"password"=>"super_secret_password"
]
]
);
Docs

Categories