Get the Email-Id of the Client PHP - php

I want So I've followed the instructions given on the following page
https://developers.google.com/api-client-library/php/auth/web-app
However, it isn't too clear on how to get the currently signed in user's email id. The current scopes that I've set are for reading the person's profile, his email-id and gmail.readonly (reading all emails).
My question is, say I have the access token, and I've initialized the Google_Client object by setting the access token, how do I get the currently sign-in user's email?

Heh, looks like I just needed to find the proper Google Service. Got this by going through the documentation.
https://developers.google.com/resources/api-libraries/documentation/gmail/v1/php/latest/class-Google_Service_Gmail.html
The code now is:
$gmail = new Google_Service_Gmail($client);
if($client->getAccessCode()) {
$token_data = $client->verifyAccessToken();
$email = $token_data['email'];
}
Also, for some reason, the line with $token_data doesn't seem to work, so I ended up using the REST API to verify the access token. Just replace that line with
$token_data = json_decode(file_get_contents('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.urlencode($client->getAccessToken()["access_token"])), true);

Related

Need Email Address from Google with Access Token that we receive from Alexa Skill?

I was able to Link Account using Google Auth v2 in Alexa Skill. And I am able to get Access Token. Now I want to get the Google Email address with which user has used to link account. So how can I get that Google Email Address?
Use the Oauth2 Scope "https://www.googleapis.com/auth/userinfo.email".
Add the scope to your Google Client (Example with the Google Library for PHP):
$googleClient = new Google_Client();
// Your code here with Client ID, Secret, ...
$googleClient->addScope('https://www.googleapis.com/auth/userinfo.email');
That'll give you the E-Mail of the user.
if(isset($_GET['code'])) {
// Your code here, the login code is in $_GET['code']
/**
* Get access token
*/
$token = $googleClient->fetchAccessTokenWithAuthCode($_GET['code']);
$googleClient->setAccessToken($token['access_token']);
// Create Google Auth Service with the Google Client
$google_auth = new Google_Service_Oauth2($googleClient);
// Get the userinfo
$google_auth_info = $google_auth->userinfo->get();
// Get the E-Mail:
$email = $google_auth_info->email;
}
I think the part you're looking for is authinfo->get()->email, but i added a bit more context so you see how to use this.
Don't forget to enable this scope also in your Google Developers Console:
https://console.cloud.google.com/apis/credentials/consent -> Edit -> Step 2: Scopes

Storing the Google OAuth Authorization Token in Database

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();

Spotify API php - unable to request data and get access token

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.

Cannot add to another users calendar

I am attempting to allow a user add items to the calendars of other users.
A user logs in and get the token as follows
const AUTHORIZE_ENDPOINT = '/oauth2/v2.0/authorize';
const TOKEN_ENDPOINT = '/oauth2/v2.0/token';
const SCOPES = 'profile openid email User.Read Calendars.ReadWrite Calendars.Read Calendars.Read.Shared Calendars.ReadWrite Calendars.ReadWrite.Shared';
$graph = new Graph();
$graph->setAccessToken($token);
$response = $graph->createRequest("GET", "/me")->setReturnType(Model\User::class)->execute();
The logged in user can add to their own calendar using
$request = $graph->createRequest("post", '/me/events');
$request->attachBody($data);
$response = $request->execute();
But, when I try to add to another user with
$request = $graph->createRequest("post", '/anotheruser/events');
$request->attachBody($data);
$response = $request->execute();
I get the message
Resource not found for the segment
Have done the admin auth consent, so all should be fine.
Any suggestions?
If you want to access another user's data you have to use the following url:
/users/{id | userPrincipalName}
Your request was just in the wrong form and you ended up sending a request to an non existing resource, thus Graph didn't know what to do.
In your case you just need to prepend /users (for more information see documentation).
So your request could look like this:
$request = $graph->createRequest("post", '/users/anotheruser/events');
Keep in mind that if you are logged in as a user (token on behalf of a user), the calendar you try to access to must have been shared with the logged in user. Otherwise it will fail due to missing privileges as Graph only allows to edit Calendars that are shared with the user. You also need the Permissions Calendars.Read.Shared and/or Calendars.ReadWrite.Shared (which you seem to already have aquired).
Calendar sharing is unnecessary if you gain access without a user as you then automatically have full access to all users.
Currently the Graph API only supports access to shared Calendars but no operations to edit/change the sharing status or see which Calendars are shared with a user. However you can change the sharing status manually over outlook or the powershell.
Url should be something like Users('anotheruser')/events. Since you are directly saying anotheruser/events. The service is not recognizing another user as a valid segment and throwing the error.

Getting 403 error when trying to update profile description with Soundcloud PHP API

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.

Categories