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;
Related
With help from #CarlZhao I am finally getting a good understanding of the difference between OAuth and Graph. I am building the capability in my app for users to post messages to a team channel. So far I can list teams, channels, and delete channels. I am having a hard time trying to send a chatMessage. I understand that because sending a chatMessage is a delegated permission and not an application permission so from my understanding I have to use the accessToken created from OAuth when the user authenticated with my app.
What I am doing is saving that token in my database so I can call it when I am trying to send a chatMessage. Not sure if that is correct. So in my code, I am creating a new Graph instance, but I am using the access token of the user and not the token of the graph.
$useraccesstoken = "************************************";
// create a new OAuth graph from useraccesstoken
$graph_message = new Graph();
$graph_message->setAccessToken($useraccesstoken);
// post message
$data = [
'body' => [
'content' => 'This is a message from the API I made it works'
],
];
$message = $graph_message->createRequest("POST", "/teams/$group_id/channels/$channel_id/messages")
->addHeaders(array("Content-Type" => "application/json"))
->attachBody($data)
->setReturnType(Model\User::class)
->execute();
This is producing no errors, but nothing happens and the chatMessage is not posted. I have double-checked and my $group_id and $channel_id are correct.
Am I using the $useraccesstoken correctly? can I start a new Graph() instance with the $useraccesstoken?
Yes, you could start a new Graph() instance with the $useraccesstoken.
The graph API of sending messages doesn't return User::class. Try your code with
->setReturnType(Model\ChatMessage::class)
The access token is invalid for one hour by default, see here. You could not use it all the time, so it seems you don't need to store in the database. It's better to refresh token before the access token expires, and this step shows you how to refresh token.
The default is 1 hour - after 1 hour, the client must use the refresh
token to (usually silently) acquire a new refresh token and access
token.
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'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.
I am using following php code :
$vk = new VK($app_id, $api_secret);
$user_wall = $vk->api('newsfeed.get', array(
//'owner_id' => $o->profile_uid,
'count' => 100,
'filters' => 'post,photo,wall_photo,friend',
'access_token' => $o->profile_token
));
echo '<pre>';
print_r($user_wall);
exit;
I am getting error when trying above code. I have successfully completed auth and stored user profile info in mysql table. I notice that when I see Api.Console permission in App> Setting, I see Access the Wall permission. But in application I used to retrieve data, I do not see this permission.
Error description : Permission to perform this action is denied
Error code : 7
The documentation is poorly described. Even which field is required or optional I can not determine. And what is difference between wall.get with filter "others" vs newsfeed.get ?
LOGIN CODE:
$AuthURL = $vk->getAuthorizeURL('notify,friends,photos,audio,video,docs,notes,pages,status,offers,questions,wall,groups,notifications,stats,ads,offline', $redirect_uri);
AUTH CODE:
$vk_code = $_REQUEST['code'];
$vk = new VK($app_id, $app_secret);
$access_token = $vk->getAccessToken($vk_code, $redirect_uri);
$uid = $access_token['user_id'];
$token = $access_token['access_token'];
$user_info = $vk->api('users.get', array(
'user_ids' => $uid,
'fields' => 'nickname, screen_name, sex, bdate (birthdate), city, country, timezone, photo, photo_medium, photo_big, has_mobile, contacts, education, online, counters, relation, last_seen, activity, can_write_private_message, can_see_all_posts, can_post, universities, counters'
));
First you must register application: vk.com/editapp?act=create
Then you need get authorize code. To do this follow link:
oauth.vk.com/authorize?client_id={APP_ID}&scope={API_SETTINGS}
Where {APP_ID} — your application id (see on app settings page),
{API_SETTINGS} — access rights requested by your app (through comma). If need infinite token use key "offline". For newsfeed need use key "wall,friends,offline".
Opens page. Copy string in URL AFTER #code=
Later you need get access token. Go to link:
https://oauth.vk.com/access_token?client_id={APP_ID}&client_secret={API_SECRET}&code={CODE}
Where {API_SECRET} — secret application key (see on app settings page),
{CODE} — code that was copied in step 2.
Copy access_token.
To get newsfeed data request link:
https://api.vk.com/method/newsfeed.get.xml?access_token={ACCESS_TOKEN}
Where {ACCESS_TOKEN} — token that was in step 3.
NOTE: USE HTTPS WHEN USING THIS ACTIONS
You need the following rights to call this method: wall and friends. (Read more on rights)
You must generate authorization with wall and friends...
https://oauth.vk.com/authorize?client_id=APP_ID&scope=wall,friends,offline
Just replace APP_ID with your appilication and then get your token
When I try to update the profile description of a soundcloud account via their php sdk, I get a 403 error every time. The app is authenticated and I am able to do things like place comments, but I'm not able to update anything on the profile (particularly the description field).
I'm using the standard code, found in their official documentation:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('YOUR_ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->post('me', array(
'description' => 'I am using the SoundCloud API!'
)));
print $user->description;
Please help me find out where the error comes from, because I'm all out of ideas.
Our bad, the user documentation that you point to there had two problems:
Updates to the user resource should use the PUT method, not POST.
Arguments need to be namespaced properly.
I've modified the documentation to fix these two problems. New code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with access token
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setAccessToken('ACCESS_TOKEN');
// get the current user
$user = json_decode($client->get('me'));
// update the user's profile description
$user = json_decode($client->put('me', array(
'user[description]' => 'I am using the SoundCloud API!'
)));
print $user->description;
Hope that helps and sorry again for the confusion. Let me know if you run into any more problems.
To update user related information you need to login to Sound Cloud as user and then authenticate your application to use your personal data, else you will get 403 for all user related information while updating / delete. For posting any comments you don't need this authentication
http://developers.soundcloud.com/docs#authentication
Refer
Getting Information about the Authenticated User
Once the user has signed into SoundCloud and approved your app's authorization request, you will be able to access their profile and act on their behalf. We have provided a convenient endpoint for accessing information about the authenticated user.