php google api contacts 403 in php, working with postman - php

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.

Related

converting a $_GET cURL request to Laravel 8.x http request not working as expected (returns 403 error)

I have the following cURL request in Postman which works perfectly fine, however I am having issues getting the same response data once I have converted this cURL request into a Laravel 8.x format using the HTTP facade.
curl request
<?php
$client = new http\Client;
$request = new http\Client\Request;
$request->setRequestUrl('https://proclubs.ea.com/api/fifa/clubs/info?platform=ps4&clubIds=1741008');
$request->setRequestMethod('GET');
$request->setOptions(array());
$request->setHeaders(array(
'Referer' => 'https://www.ea.com/'
));
$client->enqueue($request)->send();
$response = $client->getResponse();
echo $response->getBody();
Laravel HTTP request
// have added use Illuminate\Support\Facades\Http; at the top of class
$url = 'https://proclubs.ea.com/api/fifa/clubs/info';
$params = [
'platform' => 'ps4',
'clubIds' => 1741008
];
$response = Http::withHeaders([
'Referrer' => 'https://www.ea.com/',
])->get($url, $params)->json();
dd($response);
expected output
{
"1741008": {
"name": "BanterburyFC",
"clubId": 1741008,
"regionId": 4344147,
"teamId": 112092,
"customKit": {
"stadName": "Wanda Metropolitano",
"kitId": "1836515329",
"isCustomTeam": "0",
"customKitId": "7623",
"customAwayKitId": "7623",
"customKeeperKitId": "5012",
"kitColor1": "1987272",
"kitColor2": "0",
"kitColor3": "16777215",
"kitAColor1": "16734520",
"kitAColor2": "0",
"kitAColor3": "16777215",
"dCustomKit": "0",
"crestColor": "1987272",
"crestAssetId": "99040402"
}
}
}
actual output
null // getting a 403 error response
When running the debug() command in Laravel I can see the following error
old SSL session ID is stale, removing * Mark bundle as not supporting multiuse < HTTP/1.1 403 Forbidden - how do I fix this?
You have misspelled the header name. It is Referer with one r not two. Change your code to this and it should work:
$response = Http::withHeaders([
'Referer' => 'https://www.ea.com/',
])->get($url, $params)->json();

PHP: How to make an api call with api key authorization using Guzzle?

I'm trying to create a client to connect an IBM-Watson bot service using Guzzle for an application constructed in Laravel, but it fails when attempting to create a new session of the service, I got the error 401: Unauthorized. I'm not using basic authorization, instead I'm trying to connect by api-key authorization.
function start_bot_session() {
//Api Key de Watson.
$api_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
//ID bot (Watson).
$assistant_id = '9c1c426d-cd33-49ec-a3bc-f0835c3264b5';
//URL service.
$url = 'https://gateway.watsonplatform.net/assistant/api/v2/assistants/';
//Method for start a new session.
$method = $assistant_id.'/sessions?version=2019-02-28';
$client = new \GuzzleHttp\Client(["base_uri" => $url]);
$response = $client->request('POST', $method, [
'headers' => [
'Authorization:' => $api_key
]
]);
return response;
}
Is there any way I can fix this?
Can you tell me some alternatives to make api call instead of using Guzzle?

guzzle getbody function accessing the diffrenet elements of response

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
...
}

Reddit Api endpoint returns 302 found

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

Laravel - POST data is null when using external request

I'm new to laravel, and I'm trying to implement a simple rest api.
I have the controller implemented, and tested via unit testing.
My problem is with the POST request.
Via the tests Input:json has data, via an external rest client it returns null.
This is the code on the unit test
$newMenu = array(
'name'=>'Christmas Menu',
'description'=>'Christmas Menu',
'img_url'=>'http://www.example.com',
'type_id'=>1,
);
Request::setMethod('POST');
Input::$json = $newMenu;
$response = Controller::call('menu#index');
What am I doing wrong?
UPDATE:
This is realy driving me crazy
I've instanciated a new laravel project and just have this code:
Routes
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Controller:
class Home_Controller extends Base_Controller {
public $restful = true;
public function get_index()
{
return Response::json(['test'=>'hello world']);
}
public function post_index()
{
return Response::json(['test'=>Input::all()]);
}
}
CURL call:
curl -H "Accept:application/json" -H"Content-type: application/json" -X POST -d '{"title":"world"}' http://localhost/laravel-post/public/test
response:
{"test":[]}
Can anyone point me to what is wrong.
This is really preventing me to use laravel, and I really liked the concept.
Because you are posting JSON as your HTTP body you don't get it with Input::all();
You should use:
$postInput = file_get_contents('php://input');
$data = json_decode($postInput, true);
$response = array('test' => $data);
return Response::json($response);
Also you can use
Route::any('test', 'home#index');
instead of
Route::get('test', 'home#index');
Route::post('test', 'home#index');
Remove header Content-type: application/json if you are sending it as key value pairs and not a json
If you use : Route::post('test', 'XYZController#test');
Send data format : Content-type : application/json
For example : {"data":"foo bar"}
And you can get the post (any others:get, put...etc) data with :
Input::get('data');
This is clearly written in here : http://laravel.com/docs/requests
. Correct Content-type is very important!
I am not sure your CURL call is correct. Maybe this can be helpful : How to POST JSON data with Curl from Terminal/Commandline to Test Spring REST?
I am using Input::get('data') and it works.
I was facing this problem, my response of post was always null. To solve that I put the body key in guzzle object, like this
$client = new Client([
'headers' => [
'Content-Type' => 'application/json',
'Authorization' => config('app.callisto_token'),
]
]);
$body = [
'firstResult'=> 0,
'data' => '05/05/2022'
];
$response = $client->post('http://'.$this->ip.'/IntegracaoERP'.'/status_pedido',
['body' => json_encode($body)]
);
Don't forget the json_encode in body key.
Hope this helps.

Categories