I'm using CakePHP and I've already got a access token and a refresh token for the Reddit API, when I make a get request to a endpoint like '/subreddits/popular.json' it works and returns json. My problem is when I make a get request to /subreddits/mine/subscriber.json I get the following response:
302 Found
The resource was found at https://www.reddit.com/subreddits/login.json?dest=https%3A%2F%2Foauth.reddit.com%2Freddits%2Fmine%2Fsubscriber.json%3Fcount%3D100%26limit%3D100; you should be redirected automatically. "
Why is json not returned? or have I missed something the code used to send a get request is:
$endpoint = $this->ENDPOINT_OAUTH . '/subreddits/mine/subscriber.json';
$options = array(
'header' => array(
'Authorization' => $accessToken,
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=UTF-8'
)
);
$results = $HttpSocket->get($endpoint, $data, $options);
print_r('<pre>');
var_dump($results);
print_r('</pre>');
EDIT: if I add to my options array 'redirect' => true then it redirects to the 302 found url and then returns a 200 ok response but with no data
EDIT 2: After adding the 'redirect' => true I then removed the ':' from in front of Bearer TOKEN and it works
To get it working I needed to add redirect => true to my options parameter so that it sent the second GET request.
When setting my access token it was set like this:
$accessToken = 'Bearer: ' . $accessToken;
When I removed the ':' from the front of Bearer it then worked and returns the results
Related
I have a test which is trying to login and get details. I need to pass a bearer token in request header for this operation. Please see the below code. I could see that the header seldom has the headers that I set. Can anyone give me a pointer to fix this issue?
I am using Laravel 7.2.2, PHP 7.4,
And I am running php artisan test
Code:
public function a_user_can_get_details()
{
$this->create_user();
$response = $this->json('POST',
'/api/login',
[
"email" => "john.doe#example.com",
"password" => "john123"
]);
$response->assertSuccessful();
$token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token
];
$response = $this->withHeaders($headers)
->get('api/user');
$response->assertSuccessful();
$this->assertCount(1, User::all());
}
And here is the error I am getting. Actually, the test must pass. That is the right user name and password:
Response status code [403] is not a successful status code. Failed asserting that false is true.
at tests/Feature/UserTest.php:141
137|
138| $response = $this->withHeaders($headers)
139| ->get('api/user');
140|
> 141| $response->assertSuccessful();
142| $this->assertCount(1, User::all());
143|
144| }
145|
I solved this issue.
Cause: I had added a middleware condition in Spatie Permissions to check for a permission for that specific route. I had to remove that to get this working.
Instead of that, I now, check the logged in status of the user. So that the route could be hit and needed checks are done inside the route.
Thanks all for the questions/comments which helped me to solve this.
i am using guzzle to post some data to some api and recive some data back here is my code :
$response = $client->request('POST', 'http://url/api/v1/transaction/Verify', [
'headers' => ['Content-Type' => 'application/json'],
'body' => '{
"tn":"1905463527",
}'
]);
$responebody = $response->getBody();
i exacly dont know if i am getting string or object when ever i use getbody of guzzle but here is what i get when i echo the response :
{"errorCode":null,"errorMessage":"Canceled by user.","succeed":false,"tn":1905463527,"verifyCount":35,"amount":10000}
now here for example i want to access the "succeed " element and i want to know how can i access to check if it is true or not ,
You should check the Content-Type header and if it's application/json you can run json_decode on the body. Take this as an example
if ($response->getContentType() == 'application/json') {
$responseBody = json_decode($response->getContent());
// now you can access $responseBody->succeed
...
}
Using Google App Engine, when calling my API using POST method, it shows as GET - why?
This is my code:
function call_api($client_id, $client_secret, $data) {
$api_url = 'http://myapp.com/api.php';
$options = array(
'http' => array(
'header' => "Authorization: Basic " . Base64_encode("$client_id:$client_secret") . "\r\nContent-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($api_url, false, $context);
return $result;
}
The first line of api.php is:
echo "<pre>"; print_r($_SERVER); echo "</pre>";
And within that output, I see:
[REQUEST_METHOD] => GET
How/why could this be happening?
It's also worth mentioning that the method shows as POST when testing this code on GAE's SDK.
I worked it out and I need to answer my own question because it's a doozy!!
Whilst the url is http $api_url = 'http://myapp.com/api.php';, as per everything else, the GAE app.yaml file serves all scripts as https as per:
- url: /(.+\.php)$
script: \1
secure: always
This means that the page that calls my function above is https so the api call doesn't like the request because of Cross-orgin source sharing.
The solution was to simply change the $api_url to be https.
I want to query the google rest api endpoint to get user contacts:
public static function getContacts(string $token) {
$url = "https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=999999";
$opts = [
"http" => [
"method" => "GET",
"header" => "Authorization: Bearer {$token}"
]
];
$response = file_get_contents($url, false, stream_context_create($opts));
$contacts = json_decode($response);
return $contacts;
}
However, the request returns 403 even thought the token is valid and the request works when sending it via Postman.
Use curl to call api. i think it will work fine there.
I am trying to get the access token so I can start building an app that works with BigCommerce. I've been following the docs here: https://developer.bigcommerce.com/api/callback. I'm using the PHP client for Bigcommerce.
The response is HTTP/1.1 400 Bad Request {"error":"Invalid client id."}.
I swear I'm using the correct client id and client secret! Or at least they are what is displayed when I click "View Client ID" on my draft app in the developer portal.
What on earth am I doing wrong?
$request = $_REQUEST;
require_once 'vendor/autoload.php';
use Bigcommerce\Api\Connection;
$tokenUrl = "https://login.bigcommerce.com/oauth2/token";
$connection = new Connection();
$connection->verifyPeer();
$connection->useUrlencoded();
$response = $connection->post($tokenUrl, array(
"client_id" => "", //I won't type it here but it is correct
"client_secret" => "", //also correct
"redirect_uri" => "https://127.0.0.1/project-custom/oauth.php", //this is the Auth Callback URL
"grant_type" => "authorization_code",
"code" => $request["code"], //when I echo these variables out they work
"scope" => $request["scope"],
"context" => $request["context"],
));
print_r($connection->getLastError());
I figured it out!
I just removed the line $connection->useUrlencoded(); because it needed to be sent as "Content-Type: application/json" and I was sending it as "Content-Type: application/x-www-form-urlencoded"