I'm trying to access users playlist tracks by using the client credentials flow.
Spotify getting playlist documentation: https://developer.spotify.com/web-api/get-playlists-tracks/
Spotify getting client credentials documentation: https://developer.spotify.com/web-api/authorization-guide/
First question, is it possible to get a users playlist tracks using client credentials flow? I'm using this flow since I'm unable to pop up a login box for the user to login.
Secondly, I've tried using https://github.com/jwilsson/spotify-web-api-php client credentials flow (Docs: http://jwilsson.github.io/spotify-web-api-php/authorization.html) by practically copying the code at the bottom of that page:
<?php
include('vendor/autoload.php');
$session = new SpotifyWebAPI\Session('Tobys client id', 'Tobys secret', 'http://localhost/callback');
// Request a access token with optional scopes
$scopes = array(
'playlist-read-private',
'user-read-private'
);
$session->requestCredentialsToken($scopes);
$accessToken = $session->getAccessToken(); // We're good to go!
// Set the code on the API wrapper
$api->setAccessToken($accessToken);
$playlists = $api->getUserPlaylists('USER_ID', array(
'limit' => 5
));
foreach ($playlists->items as $playlist) {
echo '' . $playlist->name . ' <br>';
}
This gives me Notice: Undefined variable: api in /var/www/html/dev/testing.php on line 16
I've also tried creating the API variable using $api = new SpotifyWebAPI\SpotifyWebAPI(); but this says I need user information/ tokens.
Thanks.
First question, is it possible to get a users playlist tracks using
client credentials flow?
Yes, retrieving tracks for a playlist doesn't require user authentication as part of the access token.
I've also tried creating the API variable using $api = new
SpotifyWebAPI\SpotifyWebAPI(); but this says I need user information/
tokens.
Looking at the code (Session class, SpotifyWebapi class), it does look like you should set this up by doing
$api = new SpotifyWebAPI\SpotifyWebAPI();
$session = new SpotifyWebAPI\Session($clientId, $clientSecret, $redirectUri);
$api->setAccessToken($session->getAccessToken());
When that's set up you should be good to use the getUserPlaylists method like you're doing in your example code.
Related
I am building a portal where multiple users can log in to their multiple Gmail accounts. I have successfully retrieved the token value, However, I want to store that in my database but I am unable to store it.
Below is the code I am using:
function mInititalize(){
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://mail.google.com/');
$client->setClientId(Config('gmail.client_id'));
$client->setClientSecret(Config('gmail.client_secret'));
$client->setRedirectUri('http://localhost:81'.Config('gmail.redirect_url'));
$loginURL = $client->createAuthUrl();
return redirect($loginURL);
}
After Redirection or user login
function mGetToken(){
$token = $client->fetchAccessTokenWithAuthCode( 'code'); // here i get the 'code' from login URL
I pass this code to get token I successfully get token
$oAuth = new Google_Service_Oauth2( $client);
$userData = $oAuth->userinfo_v2_me->get(); // get current user detail
}
I want to store $token value in database, but I am getting error message
>Serialization of 'Closure' is not allowed
Please anyone help me to solve this issue. Thanks.
I would suggest storing OAuth credential information for the Google API, not in your database, but through the API itself. If you're intending to use it any authentication manner, you'll run into problems, as the docs state:
Access tokens periodically expire and become invalid credentials for a related API request. Google Identity Platform: Using OAuth 2.0 for Web Server Applications
But, the same docs also show a way that you can set or retrieve the token natively within the API. Since it's data relating to google's auth'ing process, and since it might go stale if you store it, it seems best to just let them handle it and work with the API. The same source:
If you need to apply an access token to a new Google_Client object—for example, if you stored the access token in a user session—use the setAccessToken method:
$client->setAccessToken($access_token);
$client->getAccessToken();
I am currently new to using php and Laravel and working with an API however I have been following the Spotify PHP tutorial https://github.com/jwilsson/spotify-web-api-php.
I've also put in bold some of my questions that I wanted to ask , hopefully someone can help.
I have followed all steps but need help just to get it working.
Put the following code in its own file, lets call it auth.php. Replace CLIENT_ID and CLIENT_SECRET with the values given to you by Spotify.
(Where abouts should I save this file?)
The REDIRECT_URI is the one you entered when creating the Spotify app, make sure it's an exact match.
(I used my localhost:8888/callback/ not sure if that is correct?) Obviously I haven't put me details in here on this website as for security reasons.
<?php
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ ID',
'CLIENT_SECRET',
'REDIRECT_URL'
);
$options = [
'scope' => [
'playlist-read-private',
'user-read-private',
],
];
header('Location: ' . $session->getAuthorizeUrl($options));
die();
?>
When the user has approved your app, Spotify will redirect the user together with a code to the specifed redirect URI. You'll need to use this code to request a access token from Spotify.
put this code in a new file called callback.php:
Do replace client id and secret with my detail? also how do I save the access token?
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session(
'CLIENT_ID',
'CLIENT_SECRET',
'REDIRECT_URI'
);
// Request a access token using the code from Spotify
$session->requestAccessToken($_GET['code']);
$accessToken = $session->getAccessToken();
$refreshToken = $session->getRefreshToken();
// Store the access and refresh tokens somewhere. In a database for example.
// Send the user along and fetch some data!
header('Location: app.php');
die();
In a third file, app.php, tell the API wrapper which access token to use, and then make some API calls!
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
require 'vendor/autoload.php';
$api = new SpotifyWebAPI\SpotifyWebAPI();
// Fetch the saved access token from somewhere. A database for example.
$api->setAccessToken($accessToken);
// It's now possible to request data about the currently authenticated user
print_r(
$api->me()
);
// Getting Spotify catalog data is of course also possible
print_r(
$api->getTrack('7EjyzZcbLxW7PaaLua9Ksb')
);
(Where abouts should I save this file?)
You can save this file in differents places in laravel, for testing you could write it in a controller (not the best but you can).
Do replace client id and secret with my detail?
Yes of course !
also how do I save the access token?
You can save in a database or in a session or where you want. If you store it in a session you will have to make a new request to get a new Access token if the user logged out of your application. In a database you can reuse it.
Many access token are only available for a specific duration. The spotify doc should speak of it.
(Where do i also save this file and how do I make these calls in my Laravel Controllers?)
For testing you can do this in your controller, but it's a good idea to have a service layer where you put the business logic of your application.
Do not copy require 'vendor/autoload.php'; in your file laravel handle the composer autoload already.
I've got a php web app (hosted on Azure) using the microsoft/microsoft-graph SDK for one of my authentication providers.
I am able to get a token and pull some of the user properties, but the 'id' value seems to be returning a blank string:
$me = $provider->get("me", $token);
printf('<br>Hello %s!', $me['displayName']);
printf('<br>First Name: %s', $me['givenName']);
printf('<br>Last Name: %s', $me['surname']);
printf('<br>ID: %s', $me['id']); // returns nothing
printf('<br>Email: %s', $me['userPrincipalName']);
printf('<br>Country: %s', $me['country']);
printf('<br>Postal Code: %s', $me['postalCode']);
According to the User reference, I should be able to get the user ID value as a string.
I am also using thenetworg/oauth2-azure as part of the project and the following does return a GUID. Is it the same ID that I'm looking for? The unique user ID from Graph? Or is it a different ID?
printf('<br>ID: %s', $resourceOwner->getId());
Ideally, I'd like to get the ID value directly from Graph like all the other properties. Is there something I'm missing that I need to do special for the ID property? (well, obviously...) Is the issue with Graph, with the php library, or something else?
Thanks for your assistance.
[Update]
OK, so backing up a step: I've got two pages:
Page 1 has links to a number of authentication options.
Page 2 is a redirect from one of those options - the Microsoft Work and School option.
Page 1 now uses the following to create the link:
$mscallbackUrl = $urlcore . '/ms-callback.php';
$provider = new TheNetworg\OAuth2\Client\Provider\Azure([
'clientId' => $msAppId,
'clentSecret' => $msAppSecret,
'redirectUri' => $mscallbackUrl
]);
$provider->urlAPI = "https://graph.microsoft.com/v1.0/";
$provider->resource = "https://graph.microsoft.com/";
$authUrl = $provider->getAuthorizationUrl();
Page 2 uses the exact same code above to set up $provider then uses the following to connect to Graph:
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
try {
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($token->getToken());
$me = $graph->createRequest("GET", "/me")
->setReturnType(Model\User::class)
->execute();
printf('<br>Hello %s!', $me->getDisplayName());
printf('<br>ID: %s', $me->id);
This code is failing on $me = $graph->createRequest
One reference I found said it could be failing because of an issue with the token.
I think there are a few things that may be causing the confusion. By default, the oauth2-azure library authenticates for the AAD Graph resource (https://graph.windows.net) instead of the Microsoft Graph resource (https://graph.microsoft.com), so you will want to verify that you request an access token for the correct resource.
Secondly, AAD Graph does not return an id field so this will return null. I believe the correlated equivalent field to MS Graph is oid.
Third, you are using the oauth2-azure library to access AAD Graph instead of the microsoft-graph library for Microsoft Graph. Once you get your access token, you can pass that into a new Graph instance like so:
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($token->getToken());
$me = $graph->createRequest("GET", "/me")
->setReturnType(Model\User::class)
->execute();
echo $me->id;
I have made a request to google adwords and got a refresh token (without using GetRefreshToken.php from the php library). I have copied and pasted the refresh_token, developerToken, client_id and client_secret into the auth.ini file.
But when I run the following part:
$user = new AdWordsUser();
$campaignService = $user->GetService('CampaignService', 'v201603');
// Create selector.
$selector = new Selector();
$selector->fields = array('Id', 'Name');
$selector->ordering[] = new OrderBy('Name', 'ASCENDING');
// Create paging controls.
$selector->paging = new Paging(0, AdWordsConstants::RECOMMENDED_PAGE_SIZE);
// Make the get request.
$page = $campaignService->get($selector);
In return I get the following error:
OAuth2Exception in SimpleOAuth2Handler.php line 119:
{
"error" : "invalid_grant"
}
The library is: Library. And the SimpleOAuth2Handler.php is here: Oauth
Any ideas why?
Have you tried passing the values directly into the adwords constructor function to make sure they are valid or at least are you setting the customer account number ? . The refresh token is used to obtain an access token which is good for about an hour. Caching this would help performance as you would not need to fetch a new access token every request.
Try adding the following -
$user->SetClientCustomerId('set your account number here');
// also if you are sure your oAuth data is valid
$user->SetOAuth2Info('pass your oauth data')
I am new to PHP and facebook API'S
I am trying to get data from my ads account on faceobook using PHP
I just want to know how much $ every ads spent
First of all - I did not understand if I must have facebook app in order to get data from my personal ad account ?
I assumed yes so I created one now..,
I am geting the acess token like this :
require_once("facebook.php");
$config = array();
$config['appId'] = 'myapp_id';
$config['secret'] = 'myappsecret';
$config['fileUpload'] = false; // optional
$facebook = new Facebook($config);
// Set a new app secret
$facebook->setApiSecret($config['secret']);
// If you do above, also set the app id
$facebook->setAppId( $config['appId']);
$access_token = $facebook->getAccessToken();
But when I am trying a get request like this:
https://graph.facebook.com/act_[my_account_number]/adgroups
I am getting a premisson exception that tell me
An access token is required to request his resource
But where do I put the access token ?
You need to add it at the end of the url as a url parameter:
"https://graph.facebook.com/act_[my_account_number]/adgroups" . "?access_token=" . $access_token
However, from the code I think you are getting an App Access Token, and you need a Page Access Token or a User Access Token to get the ads related to your Facebook Page.
Please refer to https://developers.facebook.com/docs/facebook-login/access-tokens/ for more information.