Object of class GuzzleHttp\Psr7\Request could not be converted to string - php

I've got an issue for laravel 5.4 when I trying to using guzzleHttp. here is my code.
use GuzzleHttp\Client;
$url = 'http://example.com';
$client = new Client();
$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);
if ($res->getStatusCode() == 200)
{
$json = (string)$res->getBody();
return $json;
}
and I've got this error on log:
Error Exception: Object of class GuzzleHttp\Psr7\Request could not be converted to string
what is wrong with my code? please kindly help me.
fyi, this error not always happen. sometimes it show this error, sometimes success.
thank you

$json = $res->getBody()->getContents();
try this

Try this.....
try {
$parameter = ['query' => ['name' => 'xxx', 'address' => 'yyy'], 'headers' => [ 'User-Agent' => 'xxxx', 'exceptions' => false, 'timeout' => 10 ]];
$res = $client->request('GET', $url, $parameter);
if ($res->getStatusCode() == 200)
{
return $res->getBody()->getContents();
}
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage();
}

$response = $client->post('http:yanjye.com3', ['phone' => '00','password' => '5555',]);
if ($response->getStatusCode() == 200){
$json = (string)$response->getBody();
return $json;
}
var_dump( $response);
die();
Hello, brother, I think this is the Good way to which is Working On both laravel 5.2[larave 5.2]
i have removed Httm
[laraver 5.2][1]
and use this code :
[1]: https://laravel.com/docs/7.x/http-client`

Related

Using guzzle to post to Facebook Conversions API [duplicate]

Does anybody know the correct way to post JSON using Guzzle?
$request = $this->client->post(self::URL_REGISTER,array(
'content-type' => 'application/json'
),array(json_encode($_POST)));
I get an internal server error response from the server. It works using Chrome Postman.
For Guzzle 5, 6 and 7 you do it like this:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);
Docs
The simple and basic way (guzzle6):
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('http://api.com/CheckItOutNow',
['body' => json_encode(
[
'hello' => 'World'
]
)]
);
To get the response status code and the content of the body I did this:
echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';
For Guzzle <= 4:
It's a raw post request so putting the JSON in the body solved the problem
$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
],
);
$request->setBody($data); #set body!
$response = $request->send();
This worked for me (using Guzzle 6)
$client = new Client();
$result = $client->post('http://api.example.com', [
'json' => [
'value_1' => 'number1',
'Value_group' =>
array("value_2" => "number2",
"value_3" => "number3")
]
]);
echo($result->getBody()->getContents());
$client = new \GuzzleHttp\Client();
$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
You can either using hardcoded json attribute as key, or you can conveniently using GuzzleHttp\RequestOptions::JSON constant.
Here is the example of using hardcoded json string.
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
'json' => ['foo' => 'bar']
]);
See Docs.
$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);
$response = $client->post('/save', [
'json' => [
'name' => 'John Doe'
]
]);
return $response->getBody();
This works for me with Guzzle 6.2 :
$gClient = new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
array(
'headers'=>array('Content-Type'=>'application/json'),
'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
)
);
According to the documentation guzzle do the json_encode
Solution for $client->request('POST',...
For those who are using $client->request this is how you create a JSON request:
$client = new Client();
$res = $client->request('POST', "https://some-url.com/api", [
'json' => [
'paramaterName' => "parameterValue",
'paramaterName2' => "parameterValue2",
]
'headers' => [
'Content-Type' => 'application/json',
]
]);
Guzzle JSON Request Reference
Php Version: 5.6
Symfony version: 2.3
Guzzle: 5.0
I had an experience recently about sending json with Guzzle. I use Symfony 2.3 so my guzzle version can be a little older.
I will also show how to use debug mode and you can see the request before sending it,
When i made the request as shown below got the successfull response;
use GuzzleHttp\Client;
$headers = [
'Authorization' => 'Bearer ' . $token,
'Accept' => 'application/json',
"Content-Type" => "application/json"
];
$body = json_encode($requestBody);
$client = new Client();
$client->setDefaultOption('headers', $headers);
$client->setDefaultOption('verify', false);
$client->setDefaultOption('debug', true);
$response = $client->post($endPoint, array('body'=> $body));
dump($response->getBody()->getContents());
#user3379466 is correct, but here I rewrite in full:
-package that you need:
"require": {
"php" : ">=5.3.9",
"guzzlehttp/guzzle": "^3.8"
},
-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):
$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('username#gmail.com', 'password', 'Digest'),)));
$url = "https://api.yourbaseapiserver.com/incidents.xml";
$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>dsss#mail.ca</email></requester>
<description>description2a</description>
</incident>';
$request = $client->post($url, array('content-type' => 'application/xml',));
$request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.
$response = $request->send(); #you must do send() method!
echo $response->getBody(); #you should see the response body from the server on success
die;
--- Solution for * Guzzle 6 * ---
-package that you need:
"require": {
"php" : ">=5.5.0",
"guzzlehttp/guzzle": "~6.0"
},
$client = new Client([
// Base URI is used with relative requests
'base_uri' => 'https://api.compay.com/',
// You can set any number of default request options.
'timeout' => 3.0,
'auth' => array('you#gmail.ca', 'dsfddfdfpassword', 'Digest'),
'headers' => array('Accept' => 'application/vnd.comay.v1.1+xml',
'Content-Type' => 'text/xml'),
]);
$url = "https://api.compay.com/cases.xml";
$data string variable is defined same as above.
// Provide the body as a string.
$r = $client->request('POST', $url, [
'body' => $data
]);
echo $r->getBody();
die;
Simply use this it will work
$auth = base64_encode('user:'.config('mailchimp.api_key'));
//API URL
$urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
//API authentication Header
$headers = array(
'Accept' => 'application/json',
'Authorization' => 'Basic '.$auth
);
$client = new Client();
$req_Memeber = new Request('POST', $urll, $headers, $userlist);
// promise
$promise = $client->sendAsync($req_Memeber)->then(function ($res){
echo "Synched";
});
$promise->wait();
I use the following code that works very reliably.
The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.
The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.
If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.
public function callAPI($request, $searchType) {
$guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);
try {
$result = $guzzleClient->post( $searchType, ["json" => $request]);
} catch (Exception $e) {
$error = $e->getMessage();
$error .= '<pre>'.print_r($request, $return=true).'</pre>';
$error .= 'No returnable data';
Event::logError(__LINE__, __FILE__, $error);
return false;
}
return json_decode($result->getBody(), $return=true);
}
The answer from #user3379466 can be made to work by setting $data as follows:
$data = "{'some_key' : 'some_value'}";
What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):
$data = "{\"collection\" : [$existing_variable]}";
So with $existing_variable being, say, 90210, you get:
echo $data;
//{"collection" : [90210]}
Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.
Above answers did not worked for me somehow. But this works fine for me.
$client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);
$request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));

HTTP Guzzle not returning all data

I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.
I call the function here:
$arr = array(
'skip' => 0,
'take' => 1000,
);
$sims = api_request('sims', $arr);
And here is the function, where I have tried the following in my $response variable
json_decode($x->getBody(), true)
json_decode($x->getBody()->getContents(), true)
But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.
use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
$username = '***';
$password = '***';
//use GuzzleHttp\Client;
$client = new Client([
'auth' => [$username, $password],
]);
$auth_header = 'Basic '.$username.':'.$password;
$headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
$json_data = json_encode($vars);
$end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
try {
$x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
$response = array(
'success' => true,
'response' => // SEE ABOVE //
);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = array(
'success' => false,
'errors' => json_decode($e->getResponse()->getBody(true)),
);
}
return $response;
}
By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.
In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

Freshdesk API Create note with attachment throwing validation error

use GuzzleHttp\Client;
function insert_freshdesk_note($ticketId, $content, $attachments=null)
{
if(is_null($content)) {
return false;
}
$url = 'https://mydomain.freshdesk.com/api/v2/tickets/'.$ticketId.'/notes';
$method = 'POST';
$userName = config('freshdesk_api_key');
$password = 'password';
$data = (!empty($attachments)) ? [
"attachments[]" => $attachments,
"body" => $content,
"private" => false,
] : [
"body" => $content,
"private" => false,
];
$options = (!empty($attachments)) ? [
'json' => $data,
'auth' => [$userName, $password],
'headers' => ['content-type' => 'multipart/form-data']
] : [
'json' => $data,
'auth' => [$userName, $password]
];
$client = new Client();
try {
$response = $client->request($method, $url, $options);
return json_decode($response->getBody(), true);
} catch (Exception $e) {
Log::error($e);
}
}
Above code is working fine without attachments but when an attachment comes into the picture it's throwing the following error:-
GuzzleHttp\Exception\ClientException: Client error: `POST https://mydomain.freshdesk.com/api/v2/tickets/13033/notes` resulted in a `400 Bad Request` response:
{"description":"Validation failed","errors":[{"field":"{\"attachments","message":"Unexpected/invalid field in request","
I am working according to the documentation and I have hit a dead end as of this point. I tried other permutations and combinations but via those, I wasn't able to resolve this problem.
Can anyone please help me.
Here is the link of the documentation of freshdesk
And in $attachments[] = '#/path/to/xyz.ext' this particular is going.
The function call will go like this:-
insert_freshdesk_note($this->freshdesk_ticket_id, $noteText, $image->image_full_path);
In the above question, I was trying to achieve the addition of note using GuzzleHTTP Client, Laravel Framework, and PHP language. Here's the following source code by which it starts working.
use GuzzleHttp\Client;
function insert_freshdesk_note($ticketId, $content, $attachments=null)
{
if(is_null($content)) {
return false;
}
$url = 'https://mydomain.freshdesk.com/api/v2/tickets/'.$ticketId.'/notes';
$method = 'POST';
$userName = config('freshdesk_api_key');
$password = 'password';
$attachmentsFilePath = explode('/',$attachments);
$fileName = end($attachmentsFilePath);
$options = (!empty($attachments)) ? [
'multipart' => [
[
'name' => 'body',
'contents' => $content,
],
[
'name' => 'private',
'contents' => "false",
],
[
'name' => 'attachments[]',
'contents' => fopen($attachments, 'r'),
'filename' => $fileName,
],
],
'auth' => [$userName, $password],
] : [
'json' => [
"body" => $content,
"private" => false,
],
'auth' => [$userName, $password]
];
$client = new Client();
try {
$response = $client->request($method, $url, $options);
return json_decode($response->getBody(), true);
} catch (Exception $e) {
Log::error($e);
}
}
We have to send the data in multipart fashion in order to Freshdesk backend to understand that data is there, by writing multipart/form-type in the header won't help. If you look at documentation also with and without attachments below:-
Without Attachment:-
curl -v -u user#yourcompany.com:test -H "Content-Type: application/json" -X POST -d '{ "body":"Hi tom, Still Angry", "private":false, "notify_emails":["tom#yourcompany.com"] }' 'https://domain.freshdesk.com/api/v2/tickets/3/notes'
With Attachment:-
curl -v -u user#yourcompany.com:test -F "attachments[]=#/path/to/attachment1.ext" -F "body=Hi tom, Still Angry" -F "notify_emails[]=tom#yourcompany.com" -X POST 'https://domain.freshdesk.com/api/v2/tickets/20/notes'
The difference in the curl can be seen.
This was the missing piece that I overlooked.

Using Guzzle 6 in Laravel to communicate with an external API

When I do this on the commandline:
curl -X POST -d '{"userDetails":{"username":"myself","password":"Myself123"}}' https://sub.domain.com/energy/api/login
it returns a sessionid like expected.
When I use Guzzle 6 on Laravel 5.5 and do this:
$client = new GuzzleHttp\Client();
$login = $client->post('https://sub.domain.com/energy/api/login', [
'userDetails' => [
'username' => 'myself',
'password' => 'Myself123'
]
]);
I get this error:
Server error: `POST https://sub.domain.com/energy/api/login` resulted in a `503 Service Unavailable` response: org.json.JSONException: JSONObject["userDetails"] not found.
What am I doing wrong?
Use this to debug and send request, sample here.
include these in class
//FOR GUZZLE
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Exception\BadResponseException;
use GuzzleHttp\Exception\ClientException;
try{
$endPoint = "http://server_ip/security/subject";
$options = [ "auth" => [$username, $password], "headers" => ["header1" => value, "header2" => value] ];
$client = new Client();
$response = $client->get($endPoint, $options);
$responseArray = json_decode($response->getBody()->getContents(), true);
$status = $response->getStatusCode();
}catch(BadResponseException $e){
$response = $e->getResponse();
$reason = $response->getReasonPhrase();
$exceptionMessage = (!empty($reason)) ? $reason. ' email or password.' : 'Unauthorized email or password.';
}
You are not passing as a json. Try this:
$req = [
'userDetails' => [
'username' => 'myself',
'password' => 'Myself123'
]
];
$client = new GuzzleHttp\Client();
$login = $client->post('https://sub.domain.com/energy/api/login',
[
'json' => $req
]
);
return $login;

PHP SoapClient Cannot process the message because the content type 'text/xml;

I cannot connect to webservice and send/receive data
Error
HTTP,Cannot process the message because the content type 'text/xml;
charset=utf-8' was not the expected type 'application/soap+xml;
charset=utf-8'.
Code
$parameters = [
'UserName' => 12324,
'Password' => 432123,
'Bill_Id' => 153585611140,
'Payment_Id' => 8560103,
];
$url="https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl";
$method = "VerifyBillPaymentWithAddData";
$client = new SoapClient($url);
try{
$info = $client->__call($method, array($parameters));
}catch (SoapFault $fault){
die($fault->faultcode.','.$fault->faultstring);
}
Notice : not work Soap version 1,1 and other resolve sample for this error in stackoverflow.
You could try
$url = "https://bill.samanepay.com/CheckBill/BillStateService.svc?wsdl";
try {
$client = new SoapClient($url, [
"soap_version" => SOAP_1_2, // SOAP_1_1
'cache_wsdl' => WSDL_CACHE_NONE, // WSDL_CACHE_MEMORY
'trace' => 1,
'exception' => 1,
'keep_alive' => false,
'connection_timeout' => 500000
]);
print_r($client->__getFunctions());
} catch (SOAPFault $f) {
error_log('ERROR => '.$f);
}
to verify that your method name is correct.
There you can see the method
VerifyBillPaymentWithAddDataResponse VerifyBillPaymentWithAddData(VerifyBillPaymentWithAddData $parameters)
Next is to check the Type VerifyBillPaymentWithAddData and if the parameter can be an array.
Also you could test to call the method via
$client->VerifyBillPaymentWithAddData([
'UserName' => 12324,
'Password' => 432123,
'Bill_Id' => 153585611140,
'Payment_Id' => 8560103,
]);
or yours except the additional array
$info = $client->__call($method, $parameters);
EDIT:
Assuming to https://stackoverflow.com/a/5409465/1152471 the error could be on the server side, because the server sends an header back that is not compatible with SOAP 1.2 standard.
Maybe you have to use an third party library or even simple sockets to get it working.
Just use the following function. Have fun!
function WebServices($function, $parameters){
$username = '***';
$password = '***';
$url = "http://*.*.*.*/*/*/*WebService.svc?wsdl";
$service_url = 'http://*.*.*.*/*/*/*WebService.svc';
$client = new SoapClient($url, [
"soap_version" => SOAP_1_2,
"UserName"=>$username,
"Password"=>$password,
"SOAPAction"=>"http://tempuri.org/I*WebService/$function",
'cache_wsdl' => WSDL_CACHE_NONE, // WSDL_CACHE_MEMORY
'trace' => 1,
'exception' => 1,
'keep_alive' => false,
'connection_timeout' => 500000
]);
$action = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', "http://tempuri.org/I*WebService/$function");
$to = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', $service_url);
$client->__setSoapHeaders([$action, $to]);
try{
return $client->__call($function, $parameters);
} catch(SoapFault $e){
return $e->getMessage();
}
}

Categories