CloudMQTT API Guzzle - php

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

Related

Can’t get a refreshed access_token using spotify api and laravel

First time using HTTP Client and Spotify API in Laravel.
The first step is to get a code by visiting
https://accounts.spotify.com/authorize?client_id=c1990...deed3&response_type=code&redirect_uri=http%3A%2F%2Fexample.test%2F&scope=user-read-currently-playing%20user-top-read
I then copy the code from the url after being redirected.
Then using curl -
curl -H "Authorization: Basic YzE5OT...Q2ZjA=" -d grant_type=authorization_code -d code=AQBX...X5zg -d redirect_uri=http%3A%2F%2Fexample.test%2F https://accounts.spotify.com/api/token
This returns the refresh token in JSON format -
{
"access_token":"BQBQL...vNDQ",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"AQCy...areM",
"scope":"user-read-currently-playing user-top-read"
}
But then I can't seem to get an access token using the refresh_token.
I'm getting "Bad Request" statusCode: 400 in my app
$response = Http::withHeaders([
'Authorization' => `Basic YzE5O...Q2ZjA`,
'Content-Type' => 'application/x-www-form-urlencoded'
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
Here is the documentation https://developer.spotify.com/documentation/general/guides/authorization/code-flow/.
Has anyone implemented this before in Laravel and if so how?
I have no idea about the Spotify API, but I am 99% sure your error is ->asForm(), you are sending that as a form instead of a normal request... so your code may need to be like this:
$response = Http::withToken('YzE5O...Q2ZjA')
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
See that I have removed ->asForm() and Content-Type (not sure why you are using that, it is a normal API... and ->asForm() already sets the same content you have manually set...
This is the Spotify API and I do not see any need to set the Conetnt-Type.
My bad, you need to set the ->asForm(), so the code should be:
$response = Http::withToken('YzE5O...Q2ZjA')
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);
But I still think you are missing something. Check that your refresh_token is correct. Also lookf for more debugging output
This worked for me.
'Content-Type' => 'application/x-www-form-urlencoded' was removed from withHeaders
$response = Http::withHeaders([
'Authorization' => 'Basic ' . 123...123,
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 123...456
]
);

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.

Convert cURL request to Guzzle Request using Laravel

I haven't tried using cUrl Request with API and converting it to Guzzle HTTP.
I need to convert this cUrl to a working guzzle http post request to try the API
curl -X POST
"https://urltosendblahblah" -H "Content-Type: application/json" -d
{
"outboundRewardRequest" : {
"app_id" : "B54z9Ug55zLh5rTGRT5g6hq64pGUq6ap",
"app_secret" : "f6554137d08f5607a696cd40741993758c411af3bb5f6c230270ec26e8d54126",
"rewards_token" : "I7SkxKYid_F_p-JSgTejow",
"address" : "9271051129",
"promo" : "LOAD 50"
}
}
Currently I had done this with my Guzzle Http but receiving 500 response
public function loadSample(){
$url = "";
$request = $this->client->post($url, [
'verify'=>false,
'outboundRewardRequest' => [
'app_id'=>'',
'app_secret'=> '',
'rewards_token'=>'==',
'address'=>'',
'promo'=>''
]
]);
$response = $request->getBody();
dd($response);
}
thank you!
$request = $this->client->post($url, [
'headers' => [
'verify' => false
],
'form_params' => ['outboundRewardRequest' => [
'app_id'=>'',
'app_secret'=> '',
'rewards_token'=>'==',
'address'=>'',
'promo'=>''
]],
'debug' => false,
]);
Try this approach when using guzzle. Your body parameters must be a part of the form_params array.
Also you can set your guzzle debugging to false so you don't have any issues there.
The expected key for the request body is body source. So try changing outboundRewardRequest to body.
Put your data in the json attribute or form_params depending on how it is received.
public function loadSample(){
$url = "";
$request = $this->client->post($url, [
'verify'=>false,
'json' => [
'outboundRewardRequest' => [
'app_id'=>'',
'app_secret'=> '',
'rewards_token'=>'==',
'address'=>'',
'promo'=>''
]
]
]);
$response = $request->getBody();
dd($response);
}

How to send data to CloudFlare API?

I'm trying to delete files from my CloudFlare cache using PHP. Using Guzzle I've done this:
$client = new \GuzzleHttp\Client;
$response = $client->delete('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'query' => [
'files' => 'https://example.com/styles.css,
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);
But when I run this I get an error:
Client error: DELETE https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache?files=https%3A%2F%2Fexample.com/etc resulted in a 400 Bad Request response: {"success":false,"errors":[{"code":1012,"message":"Request must contain one of \"purge_everything\", \"files\", \"tags\" (truncated...)
I can't get it to work using Postman either. I put in the required headers and try to set a key of files or files[] with the URL but it doesn't work. I've also tried data with raw JSON as the value like {"files":["url"]} (along with a JSON content-type header) but get the same error. It thinks I'm not sending the files key.
The method for purge_cache is POST instead of DELETE (Source: https://api.cloudflare.com/#zone-purge-files-by-url).
The payload is not sent as 'query', but as 'json'.
Files should be an array, not a string.
So the correct syntax should be....
$client = new \GuzzleHttp\Client;
$response = $client->post('https://api.cloudflare.com/client/v4/zones/myzoneid/purge_cache', [
'json' => [
'files' => ['https://example.com/styles.css'],
],
'headers' => [
'X-Auth-Email' => 'myemail',
'X-Auth-Key' => 'myapikey',
],
]);

Can you include raw JSON in Guzzle POST Body?

This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment. All the CURL functions utilise raw JSON variables in the body.
I am trying to create a working Guzzle client but the server is respsonding with 'invalid request' and I am just wondering if something fishy is going on with the JSON I am posting. I am starting to wonder if you can not use raw JSON in the Guzzle POST request body? I know the headers are working as I am receiving a valid response from the server and I know the JSON is valid as it is currently working in a CURL request. So I am stuck :-(
Any help would be sooo greatly appreciated.
$headers = array(
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
);
// JSON Data for API post
$GetOrder = '{
"Filter": {
"OrderID": "N10139",
"OutputSelector": [
"OrderStatus"
]
}
}';
$client = new client();
$res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);
return $res->getBody();
You can send a regular array as JSON via the 'json' request option; this will also automatically set the right headers:
$headers = [
'NETOAPI_KEY' => env('NETO_API_KEY'),
'Accept' => 'application/json',
'NETOAPI_ACTION' => 'GetOrder'
];
$GetOrder = [
'Filter' => [
'OrderID' => 'N10139',
'OutputSelector' => ['OrderStatus'],
],
];
$client = new client();
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers,
'json' => $GetOrder,
]);
Note that Guzzle applies json_encode() without any options behind the scenes; if you need any customisation, you're advised to do some of the work yourself
$res = $client->post(env('NETO_API_URL'), [
'headers' => $headers + ['Content-Type' => 'application/json'],
'body' => json_encode($getOrders, ...),
]);
Guzzle 7 Here
The below worked for me with raw json input
$data = array(
'customer' => '89090',
'username' => 'app',
'password' => 'pwd'
);
$url = "http://someendpoint/API/Login";
$client = new \GuzzleHttp\Client();
$response = $client->post($url, [
'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
'body' => json_encode($data)
]);
print_r(json_decode($response->getBody(), true));
For some reasons until I used the json_decode on the response, the output wasn't formatted.
You probably need to set the body mime type. This can be done easily using the setBody() method.
$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');

Categories