How to Retrieve HTTP Status Code with Guzzle? - guzzle

New to Guzzle/Http.
I have a API rest url login that answer with 401 code if not authorized, or 400 if missing values.
I would get the http status code to check if there is some issues, but cannot have only the code (integer or string).
This is my piece of code, I did use instruction here ( http://docs.guzzlephp.org/en/stable/quickstart.html#exceptions )
namespace controllers;
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\ClientException;
$client = new \GuzzleHttp\Client();
$url = $this->getBaseDomain().'/api/v1/login';
try {
$res = $client->request('POST', $url, [
'form_params' => [
'username' => 'abc',
'password' => '123'
]
]);
} catch (ClientException $e) {
//echo Psr7\str($e->getRequest());
echo Psr7\str($e->getResponse());
}

You can use the getStatusCode function.
$response = $client->request('GET', $url);
$statusCode = $response->getStatusCode();
Note: If your URL redirects to some other URL then you need to set false value for allow_redirects property to be able to detect initial status code for parent URL.
// On client creation
$client = new GuzzleHttp\Client([
'allow_redirects' => false
]);
// Using with request function
$client->request('GET', '/url/with/redirect', ['allow_redirects' => false]);
If you want to check status code in catch block, then you need to use $exception->getCode()
More about responses
More about allow_redirects

you can also use this code :
$client = new \GuzzleHttp\Client(['base_uri' 'http://...', 'http_errors' => false]);
hope help you

Related

Slim 3: How to access user information from request headers

I am using Slim 3.1 and able to authenticate correctly i.e. able to generate the token and use it for another POST request. Now I want to parse the request header to extract the user information so I can identify which user have sent the request.
Here is my code to get the token.
$app->post('/login/token', function (Request $request, Response $response,
array $args) {
$input = $request->getParsedBody();
$now = new DateTime();
$future = new DateTime("+10 minutes");
$server = $request->getServerParams();
$jti = (new Base62)->encode(random_bytes(16));
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"jti" => $jti,
"sub" => $input['username']
];
$sql = "SELECT * FROM user WHERE User_Name= :username";
$sth = $this->db->prepare($sql);
$sth->bindParam("username", $input['username']);
$sth->execute();
$user = $sth->fetchObject();
// verify email address.
if(!$user) {
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
// verify password.
if (!password_verify($input['password'],$user->User_Password)) {
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
$settings = $this->get('settings'); // get settings array.
//$token = JWT::encode(['User_ID' => $user->User_ID, 'username' => $user->User_Name], $settings['jwt']['secret'], "HS256");
$token = JWT::encode($payload, $settings['jwt']['secret'], "HS256");
return $this->response->withJson(['token' => $token, 'ACL' => $user->User_ACL]);
});
This returns me a token that I send in the following POST request
$app->group('/api', function(\Slim\App $app) {
$app->post('/createuser', function (Request $request, Response $response,
array $args) {
$headerValueArray = $request->getHeader('HTTP_AUTHORIZATION');
return $this->response->withJson(['success' => true, $token]);
});
});
The above POST request gives the following output
{
"success": true,
"0": ["Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MzU4Mjk0OTUsImV4cCI6MTUzNTgzNjY5NSwianRpIjoiMWc5ZFM3dUNLbzl1blRQZzBmYjU2diIsInN1YiI6InN5c2FkbWluIn0.vo3FBPhBkhfA2y7AG-afmjfeEhygIYY7lIaaVNX5i5k"]
}
I need to parse this token to extract the user information to see if its the valid user to perform this operation.In other words, how I can decode the above token.
Any help here will be much appreciated!

How to call soap api with BASIC authantication for WSDL URL

Blockquote
We are using Soap API but we can not connect to server.I am new in soap api.
We are using Code
username = testclient
password = tes#123
try {
$client=new SoapClient($wsdl,array('trace' => 1,"stream_context" => $context));
$result = $client->__call('getStatus', array());
} catch (Exception $e) {
echo $e->getMessage();
}
After passing header.
$client = new SoapClient(
'https://test/app/uat/test?wsdl',
array(
"exceptions" => 0,
"trace" => 1,
'stream_context' => stream_context_create(array(
'http' => array( 'header' => 'Authorization: Basic dGVzdGNsaWVudDp0ZXN0QDEyMw==' ),
)),
));
$result = $client->__soapCall('getBalance', array());
Also we have client and secret but How we can use for BASIC auth?
Where we can set user, pass and key and secret.
If you need any thing please let me know.
Thankyou

JWT: Why am I always getting token_not_provided?

I am sending a PUT request to an API endpoint I have created. Using jwt, I am able to successfully register and get a token back.
Using Postman, my request(s) work perfectly.
I am using Guzzle within my application to send the PUT request. This is what it looks like:
$client = new \Guzzle\Http\Client('http://foo.mysite.dev/api/');
$uri = 'user/123';
$post_data = array(
'token' => eyJ0eXAiOiJKV1QiLCJhbGc..., // whole token
'name' => 'Name',
'email' => name#email.com,
'suspended' => 1,
);
$data = json_encode($post_data);
$request = $client->put($uri, array(
'content-type' => 'application/json'
));
$request->setBody($data);
$response = $request->send();
$json = $response->json();
} catch (\Exception $e) {
error_log('Error: Could not update user:');
error_log($e->getResponse()->getBody());
}
When I log the $data variable to see what it looks like, this is what is returned.
error_log(print_r($data, true));
{"token":"eyJ0eXAiOiJKV1QiL...","name":"Name","email":"name#email.com","suspended":1}
Error: Could not suspend user:
{"error":"token_not_provided"}
It seems like all data is getting populated correctly, I am not sure why the system is not finding the token. Running the "same" query through Postman (as a PUT) along with the same params works great.
Any suggestions are greatly appreciated!
The token should be set in the authorization header, not as a post data parameter
$request->addHeader('Authorization', 'Basic eyJ0eXAiOiJKV1QiL...');

Facebook OAuth access_token error

Full code.
public function indexAction(){
echo 'Login met facebook ';
}
const FB_GRAPH_URL = "https://graph.facebook.com/";
public function fbloginAction() {
$fbCode = $this->_getParam("code");
$getStr = self::FB_GRAPH_URL. 'oauth/access_token?' .http_build_query(array(
'client_id' => 'APP_ID',
'type' => 'client_cred',
'client_secret' => 'SECRET_KEY',
'code' => $fbCode)
);
$accessToken = file_get_contents( $getStr );
krumo($accessToken) ;
$dbpath = "https://graph.facebook.com/me?$accessToken" ;
$cont = file_get_contents($dbpath ) ;
krumo($cont);
}
When i try make GET query to Facebook.
$dbpath = "https://graph.facebook.com/me?$accessToken" ;
$cont = file_get_contents($dbpath ) ;
I receive the error :
failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
in /home.....
When paste manually the $dbpath value(path) to web browser, i got next error:
{
"error": {
"message": "An active access token must be used to query information about the current user.",
"type": "OAuthException",
"code": 2500
}
}
How fix that error?
You probably want to use the Server-Side Authentication flow. By checking the calls in the documentation it is quite clear, which of your calls are wrong.
First, your call to the oauth/access_token endpoint takes no argument 'type' => 'client_cred', but it needs the parameter for your redirect_uri again:
$getStr = self::FB_GRAPH_URL . 'oauth/access_token?' . http_build_query(array(
'client_id' => 'APP_ID',
'redirect_uri' => 'REDIRECT_URI',
'client_secret' => 'SECRET_KEY',
'code' => $fbCode)
);
Then, you can't just take the answer of this call as your access_token, as there is much more in it:
access_token=USER_ACCESS_TOKEN&expires=NUMBER_OF_SECONDS_UNTIL_TOKEN_EXPIRES
and you only want the access_token part of it:
$response = file_get_contents($getStr);
$params = null;
parse_str($response, $params);
$dbpath = "https://graph.facebook.com/me?access_token=" . $params['access_token'];

Getting Response Body using Zend_http_Client

I am succesfully calling a REST API with the following code
$client = new Zend_Http_Client();
$client->setMethod(Zend_Http_Client::POST);
$client->setUri('http://www.example.com/api/type/');
$client->setParameterPost(array(
'useremail' => '******#*****.***',
'apikey' => 'secretkey',
'description' => 'TEST WEB API',
'amount' => '5000.00'
));
However I would like to get both the header value-(201) and Response Body that are returned after the execution.
How do I proceed with that?
I am assuming that you're actually executing the request via:
$response = $client->request();
At that point all you need is in the $response object,
//Dump headers
print_r($response->headers);
//Dump body
echo $response->getBody();
Refer to the Zend_Http_Response docs at:
http://framework.zend.com/apidoc/1.10/
for more methods that are available.
this should work...
$client->setUri ( $image_source_urls );
$response = $client->request ( 'GET' );
$folder_content = $response->getBody ();