Am using the following post request on guzzle to microsoft graph which works.
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $token ]
]);
$url = "myurl";
$response = $client->post(
$url,
[
'body' => json_encode(
[
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
"meeting"=>$arr['subject']
]
)]
);
$payload = json_decode($response->getBody()->getContents());
var_dump($payload) //here has data
The am doing the same request via curl using
$post = [
"meeting"=>$arr['subject'],
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
$authorization = "Authorization: Bearer ".$token;
$headers = [
'Content-Type' => 'application/json',
$authorization
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$error = curl_errno($ch) ? curl_error($ch) : '';
curl_close($ch);
if ($error){
var_dump($error);
throw new Exception($error,500);
}
return $response;
But in curl the above in micorsoft graph throws an error Expected not null\r\nParameter name: meeting but the meeting parameter is not empty. I have also tried setting the value of meeting directly via
$post = [
"meeting"=>"Test meeting",
"startDateTime"=>$arr['start_date'],
"endDateTime"=>$arr['end_date'],
];
But still doesnt solve. I guess it has something to do with body parameter i have set on guzzle which works. How can i resolve this to have it work even on curl
Related
I have the following PHP curl code to generate a security token within an Application.
When I run this code it works perfect.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://host.com/api/v1/auth/keys');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{}");
curl_setopt($ch, CURLOPT_USERPWD, 'admin' . ':' . 'password');
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
But at the moment I need a Guzzle version of this Curl script and that's where this issue begins.
I found different ways to handle the Authentication within Guzzle but so far nothing works.
This is what I came up with.
use GuzzleHttp\Client;
include "../vendor/autoload.php";
try{
$client = new Client(['base_uri' => 'https://host.com/api/v1/']);
$client->request('POST', 'auth/keys',[
'config' => [
'curl' => [
// CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => 'admin:password'
]
],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
print_r($client->getBody()->getContents());
}catch (Exception $e) {
print_r([
"status" => false,
"message" => $e->getMessage()
]);
}
Instead of returning a security token, I get an error message "401 Unauthorized` response" - which means no correct authentication received.
What exactly am I doing wrong?
Thank you in advance.
I believe you are not well aware of how to use curl options within guzzle
Only use curl as request option no need to use config.(See docs)
<?php
require "../vendor/autoload.php";
use GuzzleHttp\Client;
try{
$client = new Client(['base_uri' => 'https://host.com/api/v1/']);
$guzzleResponse = $client->request('POST', 'auth/keys', [
'curl' => [
CURLOPT_USERPWD => 'admin:password'
],
'headers' => [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
print_r($guzzleResponse->getBody()->getContents());
} catch (GuzzleHttp\Exception\RequestException $e) {
print_r([
"status" => false,
"message" => $e->getMessage(),
]);// you can use logs here like monolog library
} catch(Exception $e){
print_r([
"status" => false,
"message" => $e->getMessage(),
]);
}
method 2
Refering to this answer, I believe you can also use Basic Auth http header.
$encodedAuth = base64_encode( $usename.":".$passwd);
// ... other same as above
$guzzleResponse = $client->request('POST', 'auth/keys', [
'headers' => [
'Authorization' => 'Bearer '. $encodedAuth,
'Content-Type' => 'application/json',
'Accept' => 'application/json',
]
]);
// ... other same as above
Example Code (provided by Channel Advisor):
https://developer.channeladvisor.com/authorization/updating-access-token/php-updating-access-token
<?php
$endpoint = "https://api.channeladvisor.com/oauth2/token";
$refresh_token="{{REFRESH_TOKEN}}";
$application_id= "{{APPLICATION_ID}}";
$shared_secret="{{SHARED_SECRET}}";
$url = $endpoint;
$client_id = base64_encode("$application_id:$shared_secret");
$body = "grant_type=refresh_token&refresh_token=$refresh_token";
$length = strlen($body);
$headers = array(
"Authorization: Basic $client_id",
"Content-Type: text/plain",
"Cache-Control: no-cache",
"Content-Length: $length"
);
echo "URL:".$url."\n";
echo "Body:$body\n";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
print_r($httpcode);
echo"\n";
$json = json_decode($result, true);
var_dump($json);
?>
Attempting to rewrite as Guzzle HTTP request:
My question is am I setting the Basic authentication correctly?
$accessToken = {{ACCESS_TOKEN}};
$refresh_token = {{ACCESS_TOKEN}};
$application_id = {{APPLICATION_ID}};
$shared_secret = {{SHARED_SECRET}};
$base_uri = "https://api.channeladvisor.com/oauth2/token";
$client_id = 'Basic ' . base64_encode("$application_id:$shared_secret");
$client = new Client(
['headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => $client_id
]
]
);
$result = $client->request('POST', $base_uri, [
'query' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);
$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
You're sending POST request, then I guess you should send FORM data, not QUERY data.
$response = $client->request('POST', $base_uri, [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $refresh_token
],
]);
I am trying to send sms with my laravel application. I have infobip testing account and using that details to sms sms but getting this error:
ClientException in RequestException.php line 111:
Client error: `POST https://api.infobip.com/sms/1/text/single` resulted in a `401 Unauthorized` response:
{"requestError":{"serviceException": {"messageId":"UNAUTHORIZED","text":"Invalid login details"}}}
CODE:
$data= '{
"from":"InfoSMS",
"to":"923227124444",
"text":"Test SMS."
}';
$userstring = 'myuserame:password';
$id =base64_encode ( 'myuserame:password' );
echo 'Basic '.$id;
$client = new \GuzzleHttp\Client();
$request = $client->post('https://api.infobip.com/sms/1/text/single',array(
'content-type' => 'application/json'
),['auth' => ['myusername', 'password']]);
$request->setHeaders(array(
'accept' => 'application/json',
'authorization' => 'Basic '.$id,
'content-type' => 'application/json'
));
$request->setBody($data); #set body!
$response = $request->send();
echo $res->getStatusCode(); // 200
echo $res->getBody();
return $response;
The username and pssword are right as I tried to send direct text message from the site and its working there.
Can anyone help me with what am I doing wrong?
Thanks!
So I tired solving the problem using curl and I got it working placing code for others.
Code:
$data_json = '{
"from":"Infobip",
"to":"9232271274444",
"text":"test msg."
}';
$authorization = base64_encode('username:password');
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Accept: application/json',"Authorization: Basic $authorization"));
//curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_URL, 'https://api.infobip.com/sms/1/text/single');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
//var_dump(curl_getinfo($ch));
var_dump($response);
curl_close($ch);*/
You don't need to pass username / password as you read in the infobip api developer manuals.
Try this:
$authEncoded = base64_encode('myuserame:password');
$data = array(
"from" => "InfoSMS",
"to" => "923227124444",
"text" => "Test SMS."
);
$request = new Request('POST', 'https://api.infobip.com/sms/1/text/single',
array(
'json' => $data,
'headers' => array(
'Authorization' => 'Basic ' . $authEncoded,
'Accept' => 'application/json',
'Content-Type' => 'application/json',
)
)
);
$client = new \GuzzleHttp\Client();
$response = $client->send($request);
echo $response->getBody();
I can't test it myself right now so keep me updated if it worked or you get an error.
I was using cURL for posting data to an API but have decided to switch to Guzzle. Using cURL I would do this
$data =
"<Lead>
<Name>$newProject->projectName</Name>
<Description>$newProject->projectName</Description>
<EstimatedValue>$newProject->projectValue</EstimatedValue>
</Lead>";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.someurl.com/lead.api/add?apiKey=12345&accountKey=12345");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($data)
));
$output = curl_exec($ch);
This is what I am currently attempting with Guzzle.
$data = "<Lead>
<Name>$campaign->campaignName</Name>
<Description>$campaign->campaignName</Description>
<EstimatedValue>$campaign->campaignValue</EstimatedValue>
</Lead>";
$client = new GuzzleHttp\Client();
$req = $client->request('POST', 'https://somurl', [
'body' => $data,
'headers' => [
'Content-Type' => 'text/xml',
'Content-Length' => strlen($data),
]
]);
$res = $client->send($req);
$output = $res->getBody()->getContents();
The first problem I am facing is that it is stating that arguement 3 for request needs to be an array, and I am passing it a string. Thats fine, but then how can I send my xml block? Additionally, I think I may have set the headers incorrectly?
I have gone through the documentation and see that parameter 3 needs to be an array, but I do not see how to post an XML string.
Any advice appreciated.
Thanks
You can create an array using the 'body' param:
$client->request('POST', 'http://whatever', ['body' => $data]);
Read more at: http://docs.guzzlephp.org/en/latest/quickstart.html?highlight=post#post-form-requests
To set headers, you can do something like:
$response = $client->request('POST', 'http://whatever', [
'body' => $data,
'headers' => [
'Content-Type' => 'text/xml',
'Content-Length' => strlen($data),
]
]);
$output = $response->getBody()->getContents();
Read more at: http://docs.guzzlephp.org/en/latest/request-options.html#headers
I'm trying to connect to the Talentlink Api. I'm able to do it on curl but I can't connect using GuzzleHttp. I'm using Guzzle through the m6web/guzzle-http-bundle on Symfony. My code is below. Does anybody have an idea?
CURL
$headers = [
'username: XXXXX',
'password: XXXXX'
];
$body = '{
"searchCriteriaSorting": {
"categoryListsSorting": "LABEL",
"customLovsSorting": "ORDER",
"standardLovsSorting": "ORDER"
}
}';
$tuCurl = curl_init();
curl_setopt($tuCurl, CURLOPT_URL, "https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXXX&lang=FR&postingTargetId=1");
curl_setopt($tuCurl, CURLOPT_VERBOSE, 1);
curl_setopt($tuCurl, CURLOPT_HEADER, 1);
curl_setopt($tuCurl, CURLINFO_HEADER_OUT, 1);
curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $headers);
$head = curl_exec($tuCurl);
$httpCode = curl_getinfo($tuCurl, CURLINFO_HTTP_CODE);
curl_close($tuCurl);
GUZZLE
$headers = [
'username' => 'XXXXXX',
'password' => 'XXXXXX'
];
try {
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXXX&lang=FR&postingTargetId=1',
array(
'debug' => true,
$headers
));
} catch (ClientException $e) {
die((string)$e->getResponse()->getBody()->getContents());
}
On Guzzle, I keep getting a page with a login form as if I wasn't connected. However, the status is always 200 so it's difficult to debug.
SOLUTION
It was a problem with the array I was sending. It should be like this wit the 'header' key:
$response = $client->request('GET',
'https://api3.lumesse-talenthub.com/CareerPortal/REST/FoAdvert/advertisement-by-id?api_key=XXXX&lang=FR&postingTargetId=1',
[
'headers' => $headers,
//'debug' => true
]);