I use Guzzle to send messages to the Slack API. It's all working fine except for the warning missing-charset. Here is my Guzzle function:
private function guzzleClient(string $method, string $url, array $parameters = [])
{
$client = new Client(['headers' => [
'Authorization' => "Bearer " . $this->slackOauthToken,
'Content-Type' => 'application/json; charset=utf-8',
]]);
switch (strtoupper($method)) {
case "POST":
$response = $client->post($url, [RequestOptions::JSON => $parameters]);
break;
case "GET":
$response = $client->get($url, ["query" => $parameters]);
break;
}
$json = json_decode($response->getBody()->getContents());
if((is_object($json)) && ($json->ok == false)) {
return "Error: " . $json->error . "\n";
} else {
return $json;
}
}
As far as I can determine, the charset is there and in the headers. But I keep still getting the missing-chaset error - where am I going wrong?
Related
I've generated my client code from proto files. Now I'm trying to connect but get the 'jwt' is not located at the context error from server. Here's what I do:
$myServiceClient = new MyServiceClient(
"$host:$port",
[
'credentials' => ChannelCredentials::createInsecure(),
'update_metadata' => function ($metaData) use ($token) {
// $metaData['authorization'] = ['jwt' . $token]; // doesn't work
// $metaData['authorization']['jwt'] = $token; // doesn't work
// $metaData['jwt'] = $token; // doesn't work
$metaData['authorization'] = ['Bearer ' . $token]; // doesn't work
return $metaData;
},
]
);
$unaryCall = $myServiceClient->MyMethod(new MyMethodRequest());
$wait = $unaryCall->wait();
Try this
$myServiceClient = new MyServiceClient(
"$host:$port",
[
'credentials' => ChannelCredentials::createInsecure(),
'update_metadata' => function ($metaData) use ($token) {
$metaData['Authorization'] = 'Bearer ' . $token;
return $metaData;
},
]
);
Best HTTP Authorization header type for JWT
Or like this:
https://jwt.io/introduction
Authorization: Bearer <token>
The following works for me:
$myServiceClient = new MyServiceClient(
"$host:$port",
[
'credentials' => ChannelCredentials::createInsecure(),
'update_metadata' => function ($metaData) use ($token) {
$metaData['jwt'] = [$token];
return $metaData;
},
]
);
I'm learning to use an API. They provide an example of the following authentication code:
curl -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d " {\"Username\": \"the_username\",
\"Password\": \"the_password\"}
" "https://someurl.someapi.com:443/api/Login/Authenticate"
However I need to reproduce this with a Guzzle request. Here is what I've been trying
$headers = [
"Content-Type" => "application/json",
"Accept" => 'application/json -d " {\"Username\": \"the_username\", \"Password\": \"the_password\" }" ',
];
// $headers = [
// "Content-Type" => "application/json"
// ];
$extra_data = ["proxy" => $proxy,
"headers" => $headers ];
// Defining the Guzzle Client to communicate with Legacy.com
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/Login/Authenticate',
// You can set any number of default request options.
'timeout' => 10.0,
]);
try {
$response = $client->request('POST', '', $extra_data);
}
However no matter what I try (this was the latest of my failed attempts), I can't get anything other than a code 400 error.
So I finally figured how to do this:
This code worked!
$str = json_decode('{ "Username": "' . $username . '", "Password": "' . $password . '"}',true);
var_dump($str);
if ($str == NULL) return;
$url_authenticate = "Login/Authenticate";
$extra_data = ["proxy" => $proxy,
"json" => $str ];
// Defining the Guzzle Client to communicate with Legacy.com
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://someurl.someapi.com:443/api/',
// You can set any number of default request options.
'timeout' => 10.0,
]);
try {
$response = $client->request('POST', $url_authenticate, $extra_data);
}
catch (Exception $e) {
echo 'Exception: ' . $e->getResponse()->getStatusCode() . "\n";
exit;
}
$body = $response->getBody();
echo $body;
The key was use the json field int the extra data and transform the json to php array using json_decode. I hope this helps someone else
This function is meant to download .zip files
function download($url, $debug = false)
{
$client = new Client([
'connect_timeout' => 10,
'timeout' => 60.0,
'debug' => $debug
]);
$response = $client->request('GET', $url);
try {
if ($response->getStatusCode() == 200) {
return $response->getBody()->getContents();
}
} catch (RequestException $e) {
//var_dump($response->getBody()->getContents());
$txt = json_encode(['log_error' => $e->getResponse(), 'response' => $response->getBody()->getContents(), 'url' => $url]);
file_put_contents(storage_path() . '/logs-etiquetas/log-' . microtime(true) . '-' . auth()->user()->company_id . '.txt', $txt);
}
return false;
}
I'm getting error below
production_ERROR: Client error: GET https: //api.mercadolibre.com/shipment_labels? shipment_ids = 27868452659,27864682043,27168438675,27868264704,27868866716,27868738288,27867965828 & response_type = zpl2 & caller.id = 23264143 & access_token = 400 Bad Request response:
bad_request
I am sending a POST request to an API, Curl returns 200 and the correct response.
When Implementing with GuzzleHttp\Client, I get a 400 Bad request, what is wrong with my formatting.
here is my code using Laravel Returns 400 Bad Request:
$client = new Client();
$URI = 'http://api.example.com';
$params['headers'] = ['Content-Type' => 'application/json',
'apikey' => config('app._api_key'),
'debug' => true
];
$params['form_params'] = [
'sender' => 'Test_sender',
'recipient' => config('app.test_recipient'),
'message_body' => 'Test body'
];
return $response = $client->post($URI, $params);
Curl (Returns 200):
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'apikey: 212121212’ -d '{ "message_body": "test","sender": "2018","recipient": “4453424141” }' 'http://api.example.com'
Try the below code:
$client = new \GuzzleHttp\Client(['headers' => ['Content-Type' => 'application/json',
'apikey'=> config('app._api_key'),
'debug' => true
]
]);
$URI = 'http://api.example.com';
$body['sender']='Test_sender';
$body['recipient']=config('app.test_recipient');
$body['message_body']='Test body';
$body=json_encode($body);
$URI_Response = $client->request('POST',$URI,['body'=>$body]);
$URI_Response =json_decode($URI_Response->getBody(), true);
return $URI_Response;
Note: I would suggest you to handle error please refer GuzzleDocumentation
That is proper error handling:
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
try {
$response = $client->get(YOUR_URL, [
'connect_timeout' => 10
]);
// Here the code for successful request
} catch (RequestException $e) {
// Catch all 4XX errors
// To catch exactly error 400 use
if ($e->getResponse()->getStatusCode() == '400') {
echo "Got response 400";
}
// You can check for whatever error status code you need
} catch (\Exception $e) {
// There was another exception.
}
Implementation: http://guzzle.readthedocs.org/en/latest/quickstart.html
You can handle errors like this
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Exception;
try{
$client = new Client();
$response = $client->request('POST', $url,[
'headers' => $header,
'form_params' => $form-params
]);
$body = $response->getBody();
$status = 'true';
$message = 'Data found!';
$data = json_decode($body);
}catch(ClientException $ce){
$status = 'false';
$message = $ce->getMessage();
$data = [];
}catch(RequestException $re){
$status = 'false';
$message = $re->getMessage();
$data = [];
}catch(Exception $e){
$this->status = 'false';
$this->message = $e->getMessage();
$data = [];
}
return ['status'=>$status,'message'=>$message,'data'=>$data];
I need your help with this:
I try to create a shot in Dribbly but get the error message.
I did it like described in the documentation(http://developer.dribbble.com/v1/shots/#create-a-shot). This is my code:
$url = "http://www.rodos-palace.gr/uploads/images/509.jpg";
print_r($drib->create_shot('shottitle', $url));
public function create_shot($title, $image, $description = false)
{
$query = array(
'title' => $title,
'image' => $image
);
if ($description) {
$query['description'] = $description;
}
// print_r("<br>crearing_shot-> ".__LINE__);
$query['access_token'] = $this->access_token;
return $this->curl_post_shot($this->short_api, $query);
// return $this->curl_post_shot($this->short_api . "?" . 'access_token=' . $this->access_token, http_build_query($query));
}
public function curl_post_shot($url, $post)
{
$headers = array("Content-Type: multipart/form-data");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $post,
CURLOPT_HTTPHEADER => $headers,
/*, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false*/
));
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$information = curl_getinfo($curl);
if( ($resp = curl_exec($curl)) === false )
{
echo 'Curl error: ' . curl_error($curl);
}
else
{
// echo 'Operation completed without any errors';
}
//echo "Check HTTP status code >>>>";
// Check HTTP status code
if (!curl_errno($curl)) {
switch ($information = curl_getinfo($curl, CURLINFO_HTTP_CODE)) {
case 200: # OK
break;
default:
{ /*echo 'Unexpected HTTP code: ', $http_code, "\n";*/}
}
}
curl_close($curl);
print_r("<br>crearing_shot-> ".__LINE__);
echo "<pre>";
var_dump($information);
print_r("<br>----------------------------<br>");
print_r($headers);
return $resp;
}
and this is the error:
{ "message": "Validation failed.", "errors": [
{
"attribute": "image",
"message": "file is required"
} ] }
beside this, I try to do it with the image real path and with the PHP $_FILES and the result is the same.
please help me to solve this problem.
Thanks a lot.
Since I cannot verify, because I do not have an uploader account, I recommend using the cURL file class to upload a file. There are multiple ways to to this, but since you use OOP you should try this:
public function create_shot($title, $image, $description = false)
{
$query = array(
'title' => $title,
'image' => new CURLFile($image), // $image is the absolute path to the image file
);
if ($description) {
$query['description'] = $description;
}
$query['access_token'] = $this->access_token;
return $this->curl_post_shot($this->short_api, $query);
}
You will find details in the manual about the file upload.