How to get data from API google? - google-api

I have access_token and now to try get fata from Google API using this sample:
https://developers.google.com/android-publisher/api-ref/edits/details/get
I try to get data executing query to this URL:
https://www.googleapis.com/androidpublisher/v2/applications/packageName/edits/editId
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android&access_token='.$_SESSION['access_token']["access_token"]);
Where $_SESSION['access_token']["access_token"] is access_token
As a result I get message: Error: 404: HTTP/1.1 404 Not Found
How to get information from API?
This is full URL request, it does not work:
https://www.googleapis.com/androidpublisher/v2/applications/com.shazam.android/edits/1?access_token=ya29.Ci-5Azg5JoBiESM5cEzM3TQrP3SXHAFirFg0f-Fj83PxtrtINWQDe2L-3f5wP7oAtQ
{
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Full code is:
// Create the client object and set the authorization configuration
// from the client_secretes.json you downloaded from the developer console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android/edits/1/&access_token='.$_SESSION['access_token']["access_token"]);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
} else {
echo 'Response:' . "\n";
var_dump($curl->response);
}
// Create an authorized analytics service object.
//$analytics = new Google_Service_Analytics($client);
// Get the first view (profile) id for the authorized user.
//$profile = getFirstProfileId($analytics);
// Get the results from the Core Reporting API and print the results.
//$results = getResults($analytics, $profile);
//printResults($results);
} else {
$redirect_uri = 'http://localhost/play/oauth2callback.php';
header('Location: ' . $redirect_uri);
}
After getting access_token I try to make Curl request:
$curl = new Curl();
$curl->get('https://www.googleapis.com/androidpublisher/v1/applications/com.shazam.android/edits/1/&access_token='.$_SESSION['access_token']["access_token"]);

Well, another possible caused of error 403 or Insufficient Permission is that the scope that you are using is incorrect or you have not requested the scopes you need when you retrieved your access token. So try to double check the scope that you are using and enable all the API in the Dev Console that you are using.
You can check which scopes you have requested by passing your access_token to this endpoint:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
For more information, check the solution in these related SO question if it can help you.
Permission issue Google Play
Google API 'Insufficient Permission'?

Related

Zoho desk invalid oauth

I am testing out Zoho desk API. I have set up a dummy client in zoho console dashboard and using the self client option to generate a oauth_token. However when I try to use it, it always return an error code 401 with error code "INVALID_OAUTH".
I have checked for characters, and using it before even one minute of generation. Can somebody please help me with this?
{
url = "https://desk.zoho.in/api/v1/organizations"
payload = ""
headers = {
'Authorization': "Zoho-oauthtoken 1000.XXXXXabdbd925112
4ff.44d3eccd1e1a03bd25db1016f0f13322"
}
}
Response
{
"errorCode": "INVALID_OAUTH",
"message": "The OAuth Token you provided is invalid."
}

Laravel socialite 400 Bad Request response

i have created a laravel socialte setup .and it was working before perfectly now its showing error(below).
1)i have changed client_secret
2)created a new oauth credentials
still not working
public function redirectToGoogle()
{
return Socialite::driver('google')->redirect();
}
public function handleGoogleCallback()
{
$user = Socialite::driver('google')->stateless()->user();
$user->getId(); // 1472352
$user->getNickname(); // "overtrue"
$name= $user->getName(); // "安正超"
$emailid= $user->getEmail();
$pic= $user->getAvatar(); // "anzhengchao#gmail.com"
return->redirect('welcome');
}
i have created env file with client_secret and client id
"""
Client error: `POST https://accounts.google.com/o/oauth2/token` resulted in a `400 Bad Request` response:\n
{\n
"error" : "invalid_grant",\n
"error_description" : "Code was already redeemed."\n
}\n
"""
When Google return the Authentication Code code to your Socialite, it can only be used to exchange to Access Token once. Doing more than once will result in the error Code was already redeemed.
The flow should be:
User click the login button on your website
You redirect user to Google and Google is asking user to login/grant you access
If successful, Google redirects back to you with a one-time-use Authentication Code?code=.....
Socialite use the ?code and exchange it with Google to get user's Access Token. This can only be done once per flow.
You can now request user details using the access token requested in step 4.
Read similar answer: https://stackoverflow.com/a/32710034/534862

SoundCloud API 401 error in Codeigniter

I'm trying to get Soundcloud to return a track ID, but can't get it to work. Documentation here (PHP tab): https://developers.soundcloud.com/docs/api/guide#errors
I've triple checked my credentials from soundcloud that I'm adding as args.
Function in my controller:
function formprocessor()
{
require_once (APPPATH.'third_party/Services/Soundcloud.php');
// create a client object with your app credentials
$client = new Services_Soundcloud('my client id', 'my client secret', 'http://127.0.0.1:8888/index.php/welcome/');
try {
$me = json_decode($client->get('me'), true);
}
catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
}
What would cause this to fail? I keep getting a 401
Here's a reference to the API: https://developers.soundcloud.com/docs/api/reference
you need to authenticate by sending the user (even if thats you) to "authorizeurl":
$authURL = $client->getAuthorizeUrl();
then set the access token with:
$accessToken = $client->accessToken($_GET['code']);
$client->setAccessToken($_SESSION['token']); //if you saved token in a session
Then you should at least be able to "get me" this part is working for me however i cannot access things such as /me/tracks/ or /me/followings/ at the moment.

How can I insert an interceptor with AngularJS to redirect to login page?

I have a login system that will hold the session for 2 hours. After 2 hours, when the client makes API calls, they get back an error:
{
"Success": false,
"Error": {
"ErrorCode": "002",
"ErrorMessage": "Session expired"
}
}
I need to then redirect the client to /login when that happens. The problem is that I get that error from individual API calls, so rather than change EVERY API call, is it possible to have a global interceptor?
Following the example for Interceptors found here, you can do something like the following in the response section of the interceptor:
response: function(resp){
// resp.data will contain your response object from the server
if(resp.data && !resp.data.Success){
// check for error code
if(resp.data.Error && resp.data.ErrorCode === '002'){
$location.path('/login');
return $q.reject(resp);
}
}
return resp || $q.when(resp);
},
This is assuming that your server is returning a 200 when you get this error message, not on a 401 or 403, but that's what it looks like you're doing. Hope that helps.

YouTube Retrieve a Refresh Token?

I am sending a delete request to the youtube api but I am receiving a 401 error (unauthorized). I'm not sure why. My key is set properly, I am able to access the analytics of the youtube channel. This is my code that fires on a button click
jQuery.ajax({
type: 'DELETE',
// must set api key
url: 'https://www.googleapis.com/youtube/v3/videos?id='+ thisUniqueID + '&key={<?php echo $oAuth2Key; ?>}',
});
I've used alert to check that my auth key is set properly (shown below).
alert('<?php echo $oAuth2Key; ?>');
and I can see in the returned address with the error that the url is proper. What could be the issue?
It looks like I need a refresh token. This is straight out of the docs: The API will return an HTTP 401 response code (Unauthorized) if you submit a request to access a protected resource with an expired access token. The following section explains how to refresh an access token.
Is there an easy way to retrieve a refresh token at the same time that I send a delete request? If not is there an easy way to retrieve one with out the need for the client id/client secret etc.
I somehow have gotten a key for analytics, but when I go to delete a video the key is not valid.
I would suggest you to use Data API v3 instead.
Yes, you can do AJAX calls. Here's the videos->delete call.
DELETE https://www.googleapis.com/youtube/v3/videos?id=VIDEO_ID&key={YOUR_API_KEY}
You find the documentation for using authorization at:
https://developers.google.com/youtube/v3/guides/authentication
You use the API key for access to public data !
Since you want to delete a video, you must use the access_token. An access_token is valid for a short time (1 hour). You can get a new one by using your refresh_token to request another one.
Store a refresh_token since it is valid until it gets revoked.
BTW.
Maybe use client.js, to handle the authorization for your requests ?
For JS, by adding:
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
The general documentation is at:
https://developers.google.com/api-client-library/javascript/start/start-js
An code example for YouTube is at:
https://developers.google.com/youtube/v3/code_samples/javascript
For reference of the video delete method see:
https://developers.google.com/youtube/v3/docs/#videos
The listed methods are: insert, list, delete, update , rate and getRating.
The delete method might be (This is NOT tested with a valid videoID):
var requestOptions = {
id: '012345678901', // replace VIDEOID
part: 'id'
};
var request = gapi.client.youtube.videos.delete (requestOptions);
request.execute(function(response) {
console.log("RESPONSE: " + response);
});
The response using a non-existing videoId is:
[
{
"error": {
"code": -32500,
"message": "Video not found",
"data": [
{
"domain": "youtube.video",
"reason": "videoNotFound",
"message": "Video not found",
"locationType": "parameter",
"location": "id"
}
]
},
"id": "gapiRpc"
}
]

Resources