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
Related
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
I read from here : http://www.phplab.info/categories/laravel/consume-external-api-from-laravel-5-using-guzzle-http-client
I try like this :
...
use GuzzleHttp\Client as GuzzleHttpClient;
use GuzzleHttp\Exception\RequestException;
...
public function testApi()
{
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', [
// 'query' => ['plain' => 'Ab1L853Z24N'],
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'auth' => ['test#gmail.com', '1234'], //If authentication required
// 'debug' => true //If needed to debug
]);
$content = json_decode($apiRequest->getBody()->getContents());
dd($content);
} catch (RequestException $re) {
//For handling exception
}
}
When executed, the result is null
How can I get the response?
I try in postman, it success get response
But I try use guzzle, it failed
Update :
I check on the postman, the result works
I try click button code on the postman
Then I select php curl and I copy it, the result like this :
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://myshop/api/auth/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"email\"\r\n\r\ntest#gmail.com\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"password\"\r\n\r\n1234\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"postman-token: 1122334455-abcd-edde-aabe-adaddddddddd"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
If it use curl php, the code like that
How can I get the response if it use guzzle?
I see at least one syntax mistake. The third argument of the request() method should look like this:
$requestContent = [
'headers' = [],
'json' = []
];
In your case it could be:
public function testApi()
{
$requestContent = [
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json'
],
'json' => [
'email' => 'test#gmail.com',
'password' => '1234',
// 'debug' => true
]
];
try {
$client = new GuzzleHttpClient();
$apiRequest = $client->request('POST', 'https://myshop/api/auth/login', $requestContent);
$response = json_decode($apiRequest->getBody());
dd($response);
} catch (RequestException $re) {
// For handling exception.
}
}
There are other parameters instead of json for your data, for example form_params. I suggest you take a look at the Guzzle documentation.
I am using the following api:http://apidocs.mifinity.com/#/doc/2 but its not working??
My API key
$data = array(
'key' => "1234567777"
);
$url = 'https://demo.mifinitypay.com/';
$ch = curl_init($url);
$postString = http_build_query($data, '', '&');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$request = new HttpRequest();
$request->setUrl('https://demo.mifinitypay.com/api/oauth/token');
$request->setMethod(HTTP_METH_POST);
$request->setHeaders(array(
'postman-token' => '6396dfb7-540b-0e7d-7333-5d0eeff4d606',
'cache-control' => 'no-cache',
'authorization' => 'Basic username:password encoded using Base64',
'x-api-version' => '1',
'accept' => 'application/json',
'content-type' => 'application/x-www-form-urlencoded'
));
$request->setContentType('application/x-www-form-urlencoded');
$request->setPostFields(array(
'grant_type' => 'client_credentials'
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
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'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
]);