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) {
}
Related
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',
],
]
]);
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
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
I have a problem with my Bearer-Authorization in Guzzle-HTTP.
I use it to test my PHP-REST-API with PHPUnit.
here is my test method:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = $responseJson->data->token;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
But if I set the token hard coded like this:
public function testGetMe()
{
$client = new Client([
'base_uri' => $this->apiBaseURL
]);
$data = ['email' => $email, 'password' => '12345'];
$client->post('register', [
'form_params' => $data]
);
$responseJson = json_decode($response->getBody());
$myToken = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE0NjQ5NzExMzQsImp0aSI6IjByR3FpOW15Rm1rRGo2TU9sMVhkK3dRU3p1V0pWejM1UEhiU2dTMmg5SEU9IiwiaXNzIjoiQXBwTmFtZSIsIm5iZiI6MTQ2NDk3MTE0NCwiZXhwIjoxNDY0OTczMTQ0LCJzdWIiOiJ0ZXN0QG1haWwuZGUifQ.yA4a_S6ILCeqENm00H712g9uF5g9eSz_BmnaMDdZ2r4p5e1q88g0T09IG2WKCi1oExoBfQ8VTmKeX6ZQv0RydQ;
$response = $client->request('GET', 'users', [
'headers' => [
'Authorization' => 'Bearer '.$myToken
],
'debug' => true
]);
}
and also with Postman, it is working.
It's the same token which I receive from my REST-API.
Do you have any ideas what's wrong?
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.