how fix Authorization Bearer Problem in guzzle - php

I'm trying to send this request to the server, but with a 401 error
Which part of the code can the problem be?
"guzzle version 6.3"
try {
$urlDoPayment = 'https://api.example.com/v1/pay';
$client = new Client();
try {
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]
]);
$statusCode = $response->getStatusCode();
$content = $response->getBody();
dd($content);
} catch (GuzzleException $e) {
dd($e->getMessage());
}
} catch (\Exception $exception) {
dd($exception->getCode());
}

The headers in the request are nested in the wrong part of the request options. That should at least fix the 401 error if the token is valid.
Try:
$response = $client->request('POST', $urlDoPayment, [
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'amount' => 100,
'returnUrl' => "https://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
// headers should not be here
], // json post body params end
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);

This problem solved using this code
$response = $client->request('POST', $urlDoPayment, [
'json' => [
'amount' => 100,
'returnUrl' => "http://example.com/payment/verify",
'payerIdentity' => "",
'payerName' => "",
'description' => "",
'clientRefId' => ""
],
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => 'Bearer MY_TOKEN',
'Accept' => 'application/json'
]
]);

I suspect that the problem lays in undefined port or protocol. Headers content wasn't an issue for me. I resolved same problem by changing:
115.12.3.44 to 115.12.3.44:80
also tested
115.12.3.44 to http://115.12.3.44
or
google.com to http://google.com

Related

GuzzleHttp firebase messaging INVALID_ARGUMENT The message is not set

I'm trying to implement a function to send a a notification using FirebaseCloudMessaging, I got the Auth part, But seems there is an issue with the GuzzleHttp\Client and how it passes the data part
This is my code
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=<path-to-json-file>.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
// create the HTTP client
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
$data = json_encode(
[
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
],
);
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
'json' => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);
dd($response);
}
I keep getting that response 400, INVALID_ARGUMENT "The message is not set."
Client error: POST https://fcm.googleapis.com/v1/projects//messages:sendresulted in a400 Bad Request response: { "error": { "code": 400, "message": "The message is not set.", "status": "INVALID_ARGUMENT", "details (truncated...)
Although my data structure is being passed as documented, what I'm missing here?
Note: I use Laravel, I hided the , etc.
Try to use the Laravel wrapper
use Google\Auth\ApplicationDefaultCredentials;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Facades\Http;
public function send(){
putenv('GOOGLE_APPLICATION_CREDENTIALS=D:\Projects\waterko_final\waterco-356810-firebase-adminsdk-brisz-11133a2abb.json');
$scopes = ['https://www.googleapis.com/auth/firebase.messaging'];
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
];
$middleware = ApplicationDefaultCredentials::getMiddleware($scopes);
$stack = HandlerStack::create();
$stack->push($middleware);
$client = new Client([
'handler' => $stack,
'base_uri' => 'https://fcm.googleapis.com',
'auth' => 'google_auth'
]);
return Http::withHeaders($headers)->bodyFormat("json")->setClient($client)
->post('https://fcm.googleapis.com/v1/projects/waterco-356810/messages:send', $data);
}
I ran into the exact same issue, here's what worked for me:
$data should not be json encoded, but passed as an array.
And instead of the json key, it's safer to use the constant : GuzzleHttp\RequestOptions::JSON
$data = [
"message" => [
"topic" => "availableProviders",
"notification" => [
"title" => "New Order",
"body" => "New Order to accept",
],
"data" => [
"service_id" => '1'
],
],
"validateOnly" => false,
];
$response = $client->post('/v1/projects/<Project-id>/messages:send', [
[
GuzzleHttp\RequestOptions::JSON => $data,
'headers' => [
'accept' => 'application/json',
'Content-Type' => 'application/json',
],
]
]);

How do I pass apikey and other keys to header in guzzle 6.3?

I have a simple registration form that the user can register in my app, now I want to send submitted data to another service.
First I test my request using postman as follows using a raw option in a postman panel.
Api url : app3.salesmanago.pl/api/contact/upsert
JSON DATA:
{
"clientId":"w2ncrw06k7ny45umsssc",
"apiKey":"ssssj2q8qp4fbp9qf2b8p49fz",
"requestTime":1327056031488,
"sha":"ba0ddddddb543dcaf5ca82b09e33264fedb509cfb4806c",
"async" : true,
"owner" : "adam#rce.com",
"contact" : {
"email" : "test-1#konri.com",
"name" : "Test",
"address":{
"streetAddress":"Brzyczynska 123",
}
}
}
UPDATE I get the following success result
{
"success": true,
"message": [],
"contactId": "b52910be-9d22-4830-82d5-c9dc788888ba",
"externalId": null
}
Now using guuzle htpp request in laravel
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$client = new client();
$current_timestamp = Carbon::now()->timestamp;
try {
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
],
],
]);
}
catch (GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = $response->getBody()->getContents();
}
$status = $request->getStatusCode();
$response = $request->getBody();
$r = json_decode($response);
dd($r);
dd($status, $r );
return $user;
}
When I run my app and send the form data I get this using the same data as in postman I get this
{#306 ▼
+"success": false
+"message": array:1 [▼
0 => "Not authenticated"
]
+"contactId": null
+"externalId": null
}
It seems like my API key and other header data are not passed to the header as required,
Can someone tell me what am I doing wrong here?
Maybe something like this. Notice that according to the API some values should be passed as headers (Accept, and Content-Type -commonly used as headers, btw-), and other values as part of the body. This is the case of the authentication values like clientId and apiKey.
I don't have guzzle 6 installed at hand but you can try and modify the code to include that data not in the headers section of the request but in the body:
$request = $client->post('app3.salesmanago.pl/api/contact/upsert', [
\GuzzleHttp\RequestOptions::HEADERS => array(
'debug' => true,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
),
\GuzzleHttp\RequestOptions::JSON => [
'form_params' => [
'name' => $data['name'],
'email' => $data['email'],
'clientId' => 's255hncrw06k7ny45umc',
'apiKey' => 'sj2q8rt5qp4fbp9qf2b8p49fz',
'sha' => 'ba0br45543dcaf5ca82b09e33264fedb509cfb4806c',
'requestTime' => $current_timestamp,
'owner' => 'adwamtrw#fere.com',
'http_error' => true
],
],
]);
I'm not sure about the 'form_params' in under the RequestOptions::JSON, but mabye you can put the values directly under RequestOptions::JSON.
Just FYI, not sure what Laravel you're using but there's now The Laravel HTTP client which make this sooo much easier.
$response = Http::withHeaders([
'Accept' => 'application/json, application/json',
'Content-Type' => 'application/json',
'clientId' => 'dd2ncrw06k7ny45umce',
'apiKey' => 'ddjdd2q8qp4fbp9qf2b8p49fdzd',
'sha' => ' wba0b543dcaf5ca82b09e33264fedb4509cfb4806ec',
"requestTime" => $current_timestamp,
"owner" => "testemail#wp.com",
])->post('app3.salesmanago.pl/api/contact/upsert', [
'name' => $data['name'],
'email' => $data['email'],
]);
if($response->successful()){
dd($response->json())
}else{
// handle yo errors
}

How can I get response from guzzle in Laravel 5.3

I try like this :
$client = new Client();
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone/requests/', [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '.$token,
/*'Content-Type' => 'application/x-www-form-urlencoded',*/
],
/*'form_params' => $body ,*/
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> 'tel:+$phone',
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test!'
]
]],
'debug' => true,
'verify' => false,
]
);
$res->getStatusCode();
// 200
$res->getHeader('content-type');
// 'application/json; charset=utf8'
$res->getBody();
When executed, the result is an errror curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*
How can I get the response?
I try in postman, it success get response
But I try use guzzle, it failed
You can try code below:
try {
$client = new Client();
$token = 'token';
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone/requests/', [
'headers' => [
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '. $token,
],
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> "tel:youre-phone",
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test!'
]
]],
'debug' => true,
'verify' => false,
]
);
echo $res->getBody();
} catch ( \GuzzleHttp\Exception\ClientException $exception ) {
echo $exception->getResponse()->getBody();
}
I resolved it like this
$requestContent = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization'=>'Bearer '.$token,
],
'json' => [
'outboundSMSMessageRequest'=>[
'address'=> "tel:youre-phone",
'senderAddress'=>'tel:+phone_rec',
'outboundSMSTextMessage'=>[
'message'=> 'Hello test !'
]
]
]
];
try {
$client = new Client();
$res = $client->request('POST', 'https://api.orange.com/smsmessaging/v1/outbound/tel:+phone_rec/requests/', $requestContent);
$response = json_decode($res->getBody());
dd($response);
} catch (RequestException $re) {
}

API error no parameters when there are parameters given

This is the error I'm getting, as you can see there is a parameter in the URL, but the error says there weren't any parameters given. Can anbody help me out?
Client error: PUT https://webapi.teamviewer.com/api/v1/devices/d38237721?alias=laptop-test resulted in a 400 Bad Request response:
{"error":"invalid_request","error_description":"no parameters were given.","error_code":1}
This is my code
public function update($device_id, $options)
{
$token = 'thereisatokenhere';
$client = new Client(['base_uri' => 'https://webapi.teamviewer.com/api/v1/']);
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept-Language' => 'en-US',
'Content-Type' => 'application/json'
];
$response = $client->request('PUT', 'devices/' . $options['device_id'], [
'headers' => $headers,
'form_params' => [
'alias' => $options['alias'],
],
]);
$response = json_decode($response->getBody()->getContents(), true);
$deviceIdsAPI = $response['devices'];
return $deviceIdsAPI;
}
2nd
$request = new Request('PUT', 'https://webapi.teamviewer.com/api/v1/devices/' . $options['device_id'], ['alias' => $options['alias']]);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
Here is an example of a PUT request in Guzzle:
$client->put('devices/' . $options['device_id'], [
'body' => [
'alias' => $options['alias'],
'other_field' => '123'
],
'headers' => $headers,
'allow_redirects' => false,
'timeout' => 5
]);
Update:
In the latest version (Guzzle 6) it should be like this:
use GuzzleHttp\Psr7\Request;
$request = new Request('PUT', 'http://httpbin.org/put', ['test' => '123']);
$response = $client->send($request, ['timeout' => 2, 'headers' => $headers]);
See this answer and here is the official Guzzle documentation

Can't set Guzzle Content Type

I'm trying to request this way:
$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'defaults' => [
'auth' => [$publishable_key, ''],
],
'body' => json_encode($body),
]);
The problem is that this request is being set without Content-Type.
What am I doing wrong?
Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:
$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
'auth' => [$publishable_key, ''],
'headers' => ['content-type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($body),
],
]);
Guzzle 6
Guzzle will set the Content-Type header to
application/x-www-form-urlencoded when no Content-Type header is
already present.
You have 2 options.
Option 1: On the Client directly
$client = new GuzzleHttp\Client(
['headers' => [
'Content-Type' => 'application/json'
]
]
);
Option 2: On a Per Request basis
// Set various headers on a request
$client = new GuzzleHttp\Client();
$client->request('GET', '/whatever', [
'headers' => [
'Content-Type' => 'application/json'
]
]);
You can refer to Guzzle 6: Request Options
I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.
I fixed it this way
$client = new Client([
'base_uri' => 'https://api.hubapi.com/',
'timeout' => 5,
'headers' => ['Content-Type' => 'application/json']
]);
And then performing my requests the regular way
try
{
$response = $client->request('POST', '/contacts/v1/contact/email/test#test.com/profile',
['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }
I hope this helps.

Categories