Php unit test 401 - php

When I try to test my api with the following code:
$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1', [
'form_params' => [
'currentUserId' => 1
]
]); //line 22
$obj = json_decode($res->getBody());
$result = $obj->{'result'}->{'message'};
$this->assertEquals('Error', $result);
It is not going further then line 22 (see comment). When I post to the same url in postman the result is (with status code 401):
{
"result": {
"message": "Error",
"school": "Error show school"
}
}
But why is it not going further in my unit test? when I make 200 as response it is going further!

I can't comment your question so I will need to ask in my answer. What kind of error do you receive in line 22 or why does the script break? Do you have enabled error-reporting and/or checked the log-files?
Try to dump $res if there is no error/exception thrown.

Found an answer! You have to add:
['http_errors' => false]
Method now:
$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1',['http_errors' => false], [
'form_params' => [
'currentUserId' => 1
]
]);

Although Jamie's answer seems to work but there is a very small detail you should be careful of. If you use :
$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1',['http_errors' => false], [
'form_params' => ['currentUserId' => 1]
]);
as in Jamie's answer, you will always get 200 status code, even if you provide wrong credentials and you was supposed to get 401, that's why this code will never block your process but that doesn't mean your motive to check against 401 status is fulfilled.
If you really wanna check if it returns 401 by phpunit, you should use it like this:
$client = new Client();
$res = $client->request('POST', $this->url.'/api/v1/school/1',[
'http_errors' => false,
'form_params' => ['currentUserId' => 1]
]);
$status = $response->getStatusCode();
$this->assertEquals(401,$status);
This will result OK as it will actually match returned code against 401.
I hope it's clear and helps

Related

How to convert cURL to Guzzle GET

First of all: First question here in Stack Overflow, quite an honor! :D
How do i convert the following curl into Guzzle?
curl -u USER_KEY:USER_SECRET https://api.apiexample.com/example/oauth/oauth?grant_type=client_credentials
I tried the following, but i kept getting 403 - Forbidden error:
$res = $client->request('GET', 'https://api.apiexample.com/example/oauth/oauth',[
'auth' => ['USER_KEY', 'USER_SECRET'],
'header' => [
'Content-Type' => 'application/x-www-form-urlencoded'
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
What could be wrong with my code?
Edit: Forgot one thing: This request returns a token that lasts for 30 minutes. Any tip to run this function only when the token is about to expire?
I would recommend maybe reformatting your request by putting your constant values in the Client object declaration and also wrapping the request in a try-catch block. The try-catch block provides the added benefit that it will help you debug the response. Feel free to alter the catch statement as you wish.
$client = new Client([
'base_uri' => 'https://api.apiexample.com/example/',
'auth' => [
'USER_KEY',
'USER_SECRET'
]
]);
try {
$response = $client->request( 'GET', 'oauth/oauth', [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'grant_type' => 'client_credentials'
]
]);
} catch (Exception $e) {
error_log($e->getCode());
error_log($e->getMessage());
error_log(print_r($e->getTrace(), true));
}

Retrieve POST data sent with Guzzle (6.3) from Laravel

I am posting some data from my laravel app to another plain PHP page I have on my local server. The status code returned by Guzzle says it was successful but I am unable to access it. How can I do this?
I've tried using the Post method to retrieve value but no luck
Guzzle Function:
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
echo $response->getStatusCode();
Page Receiving POST DATA:
<?php
if (!empty($_POST['amnt'])) {
echo $_POST['amnt'];
}else
echo 'not found';
?>
I expect to be able to access the amount posted via post method but nothing is yielded.
Try somthing like that .
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
$contents = $response->getBody()->getContents();
$contents = json_decode($contents,true);
return ($contents);
On page Receiving POST DATA:
Response should be like this
return response()->json([
'status' => 'SUCCESS',
'code' => '200',
], 200);

Shapeshift API always returns "No Withdrawal Address Specified" error

I am using Shape Shift API for sending transaction with Guzzle. I am always getting the error given in title. My code given below:
$client = new GuzzleHttp\Client();
$data = [
"amount" => 1,
"withdrawal" => '0x23f016d7a8e408e5551ae7aa51b3fe1534165463',
"pair" => 'btc_eth',
"returnAddress" => '12stJs8vZNuuVfjZSSzpLPA96quNissk1b'
];
$result = $client->post( 'https://shapeshift.io/shift', [ 'Content-Type' => 'application/json' ],
[ 'json' => $data ] );
print "<pre>";
print_r( $result->getBody()->getContents() );
print "</pre>";
Same parameters work fine when using in Python.
You are doing the request wrong. The correct variant is with two parameters:
$result = $client->post('https://shapeshift.io/shift', ['json' => $data]);
Content type is configured automatically when you use json option.

Shopify Trying to create a script tag in shopify but returns an error

I am trying to build an app in shopify, so uing their API,
as shown here
But while I am requesting a POST request on that URL i.e.
https://demo-store.myshopify.com/admin/script_tags.json
It is returning an error with HTTP status code 400 (Bad Request)
{"errors":{"script_tag":"expected String to be a Hash"}}
Sample code
$access_token = "my-access-token";
$client = new \GuzzleHttp\Client();
try {
$response = $client->request($type, $url,[
'headers' => ['X-Shopify-Access-Token' => $access_token],
'form_params' => ['script_tag'=> \GuzzleHttp\json_encode(["event" => "onload", "src" => "https://app.dev/app.js"])],
]);
$result = json_decode($response->getBody()->getContents(), true);
var_dump($response, $result);
} catch (\Exception $ex) {
var_dump($ex);
}
When making POST or PUT requests to Shopify's API you will usually want a Content-Type: application/json header. Version 6 of Guzzle has a json option that adds the header automatically.
Here's an example of what that could look like when creating a script tag:
$client = new \GuzzleHttp\Client();
$script_tag = [
'script_tag' => [
'src' => 'https://sdks.shopifycdn.com/js-buy-sdk/v0/latest/shopify-buy.umd.polyfilled.min.js',
'event' => 'onload'
]
];
$response = $client->request('POST', 'https://45345345345.myshopify.com/admin/script_tags.json', [
'json' => $script_tag,
'headers' => ['X-Shopify-Access-Token' => $access_token]
]);

Returning GuzzleHttp response object causes ERR_INVALID_CHUNKED_ENCODING in browser

I'm using guzzle 6 in laravel 5 to send a post request but I'm getting ERR_INVALID_CHUNKED_ENCODING when I try to access the request() in the method that handles the post request.
Here's my code:
Routes.php
Route::get('/guzzle', [
'as' => 'guzzle-test',
'uses' => 'TestController#getTest'
]);
Route::post('/guzzle', [
'as' => 'guzzle-post-test',
'uses' => 'TestController#postTest'
]);
TestController.php
public function getTest()
{
$client = new Client();
$data = [
'hey' => 'ho'
];
$request = $client->post(route('guzzle-post-test'), [
'content-type' => 'application/json'
], json_encode($data));
return $request;
}
public function postTest()
{
dd(getTest());
}
I getting to the post request handler since I've tried to diedump a string and it gets there, but if i call the request() I get that error. For what I've researched It may have something to with the content length, but after reading guzzle's docs and some stuff around the web I could find how to get and pass the content length appropriately in the request. Any help would be very appreciated!
First off, here's some test code which you should be able to adapt for your purposes (also see form_params in the docs for GuzzleHttp):
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response;
}
I just ran into the same issue and found that trying to return the response object in Laravel gave me ERR_INVALID_CHUNKED_ENCODING. Whereas, doing a dd() on the response itself showed me what I was actually wanting to see:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
dd($response);
}
Unfortunately, without doing further research, I'm unable to explain why ERR_INVALID_CHUNKED_ENCODING keeps coming up when I try to return the client library's objects to the browser, but my initial inclination is that it's a data type issue.
As far as your question goes, you're not actually trying to get back the "request" but rather the response. According to http://docs.guzzlephp.org/en/latest/quickstart.html#using-responses, if you want to get the API response contained in the response object (or at least in my case, I did), you'll want to use the getBody() method:
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return $response->getBody();
}
And then of course, if you expect it to be a JSON response (i.e. REST), then simply pass it to json_decode() to get your associative array back.
public function validateRecaptcha()
{
$client = new Client;
$response = $client->request('POST', 'https://www.google.com/recaptcha/api/siteverify', [
'form_params' => [
'secret' => env('RECAPTCHA_SECRET'),
'response' => Request::input('g-recaptcha-response'),
'remoteip' => Request::ip()
]
]);
return json_decode($response->getBody(), true); // true = assoc. array
}
Hope that helps!

Categories