Get google profile information from access token - php

I have a mobile application that makes use of Google SDK to authenticate the users. That application retrieve an access token from Google and then make a request to my API passing this token. How can I get, in my API, the user's profile using this access token?
I'm trying this:
$client = new \Google_Client();
$client->setClientId('CLIENT_ID');
$client->setClientSecret('CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
// the following token I get through the mobile authentication
$token = array(
'access_token' => 'ACCESS_TOKEN',
'refresh_token' => 'REFRESH_TOKEN',
'token_type' => 'TYPE',
'expires_in' => 'EXPIRES',
'id_token' => 'ID_TOKEN',
'created' => 'CREATED_AT'
);
$client->setAccessToken(json_encode($token));
$plus = new \Google_Service_Plus($client);
$person = $plus->people->get('ID');
But I'm getting an error, I think because of the configuration of the client in Google Developers ("installed application") since It's an mobile app.

Related

bigcommerce rest api v3 php

I have to implement bigcommerce API integration with PHP
and I am trying to use the official library from https://github.com/bigcommerce/bigcommerce-api-php
and I am not even able to start step 1 here.
Issues:
Basic Auth method
Bigcommerce::configure(array(
'store_url' => 'https://store.mybigcommerce.com',
'username' => 'admin',
'api_key' => 'd81aada4xc34xx3e18f0xxxx7f36ca'
));
So the question here is how to get a username? bigcommerece user only created using email address so how to get username here?
OAuth method
In order to obtain the auth_token you would consume Bigcommerce::getAuthToken method
$object = new \stdClass();
$object->client_id = 'xxxxxx';
$object->client_secret = 'xxxxx;
$object->redirect_uri = 'https://app.com/redirect';
$object->code = $request->get('code');
$object->context = $request->get('context');
$object->scope = $request->get('scope');
$authTokenResponse = Bigcommerce::getAuthToken($object);
Bigcommerce::configure(array(
'client_id' => 'xxxxxxxx',
'auth_token' => $authTokenResponse->access_token,
'store_hash' => 'xxxxxxx'
));
here the question is what is the $request variable? also, redirect_uri is the bigcommerce store URL or my site URL?
Please can anyone help to get started with this?
It's because that library is a bit out of date with how api accounts are managed. For the basic auth you would use "legacy accounts". You can just use the OAuth method without the oAuth flow (assuming you're trying to connect to your own store, not create an app).
Just the following will work:
Bigcommerce::configure(array(
'client_id' => 'client-id',
'auth_token' => 'access-token',
'store_hash' => 'store-hash'
));
You should get these after creating a user in the dashboard (you can ignore the secret for this use case)

Can't refresh access token for Google Calendar API on server side

My client application on iOS authorizes the user and receives the access token and the refresh token and sends it to my server, where it is stored in the database.
The server connects to the calendar and get the events.
The problem is that the access token is not refreshed in any way using the refresh token and this error is returned:
{
"error": "unauthorized_client",
"error_description": "Unauthorized"
}
public function sync($token, $expiresIn, $refreshToken, $created)
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar Synchroniser');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('../client_secret_***************.apps.googleusercontent.com');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setAccessToken(json_encode([
'access_token' => $token,
'created' => $created,
'expires_in' => $expiresIn,
'refresh_token' => $refreshToken
], true));
//create google calendar service
$service = new Google_Service_Calendar($client);
//filter for events searching
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'singleEvents' => true
);
//get events
$results = $service->events->listEvents($calendarId, $optParams);
}
You can check this related SO post about the response “unauthorized_client”.
And remember that you must give access to your application in the control panel of your domain by authorizing/delegating your application to avoid this error.

Microsoft graph 401 Unauthorized error while request users/{user_id}/calendars

Trying request calendars list, but get 401 Unauthorized error. I can get users, can create new user, but can't get or create calendars.
I'm using these libraries:
thephpleague/oauth2-client
msgraph-sdk-php
get token via Client Credentials Grant method, access without a user.
$this->oauthClient = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => $config['oauth_app_id'],
'clientSecret' => $config['oauth_app_password'],
'redirectUri' => $config['oauth_redirect_uri'],
'urlAuthorize' => $config['oauth_authority'].$config['tenantID'].$config['oauth_authorize_endpoint'],
'urlAccessToken' => $config['oauth_authority'].$config['tenantID'].$config['oauth_token_endpoint'],
'urlResourceOwnerDetails' => '',
'scopes' => $config['oauth_scopes']
]);
$newToken = $this->oauthClient->getAccessToken('client_credentials', [
'scope' => 'https://graph.microsoft.com/.default'
]);
$graph = new \Microsoft\Graph\Graph();
$graph->setAccessToken($newToken);
//This works
$users = $graph->createRequest('GET', '/users/')
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();
And this works
$users = $graph->createRequest('GET', '/users/{user_id}')
->setReturnType(\Microsoft\Graph\Model\User::class)
->execute();
But this not works
$calendars = $graph->createRequest('GET', '/users/{user_id}/calendars')
->setReturnType(\Microsoft\Graph\Model\Calendar::class)
->execute();
In apps.dev.microsoft.com and in Azure portal trying sets all permissions this not helps. In Graph Explorer same result.

How to make a request with PHPLeague oAuth2 client?

I'm integrating with a affiliate platform for a client which provides an oAuth2 API, don't usually do massive amounts of work with oAuth2.
I've decided for my client, I'll use the PHP Leagues oAuth2 package: https://github.com/thephpleague/oauth2-client
Anyway, I've got an accessToken no problem! using the following:
$provider = new GenericProvider([
'clientId' => $this->config->affiliates->rakuten->clientId,
'clientSecret' => $this->config->affiliates->rakuten->clientSecret,
'redirectUri' => 'http://www.newintoday.com/',
'urlAuthorize' => 'https://api.rakutenmarketing.com/token', // Ignore
'urlAccessToken' => 'https://api.rakutenmarketing.com/token',
'urlResourceOwnerDetails' => 'https://api.rakutenmarketing.com/' // Ignore
]);
try {
// Try to get an access token using the resource owner password credentials grant.
$accessToken = $provider->getAccessToken('password', [
'username' => $this->config->affiliates->rakuten->username,
'password' => $this->config->affiliates->rakuten->password,
'scope' => $this->config->affiliates->rakuten->publisherId,
]);
$productSearchApiBaseUri = 'https://api.rakutenmarketing.com/productsearch/1.0';
$request = $provider->getAuthenticatedRequest('GET', $productSearchApiBaseUri, $accessToken, [
'body' => '?keyword=shirt',
]);
\Utils::dump($provider->getResponse($request));
} catch (IdentityProviderException $e) {
echo $e->getMessage();
}
My question is once we have the accessToken what do we use in it to make the request, I followed through the code and came up with the above but the API responds saying that the keyword is not specified? Is
$request = $provider->getAuthenticatedRequest('GET', $productSearchApiBaseUri, $accessToken, [
'body' => 'keyword=shirt',
]);
The correct way to provide it with a GET variable?
Thanks in advance.
Realised I could simply include the get vars in the URI alla:
$productSearchApiBaseUri = 'https://api.rakutenmarketing.com/productsearch/1.0?keyword=shirt';

Why can't I add an event as a page?

I'm trying to add an event to a page in the name of the page. I'm the admin of the page and I found a lot of stuff to the topic, but, no matter what I do, it ends in the PHP Exception:
Uncaught Exception: You must be an admin of the specified page to perform the requested action.
I can add events with my app in my own profile. So, I think the problem is the Access Token. I tried several ways, but to me the best way seems to be:
Open the Graph API Explorer
Select my Application
Request a new access code with permissions manage_pages, publish_actions, publish_stream, create_event
Request /me/accounts
Get the access_token from the page I want to post to and use it in my script
My test script, that works in my own profile:
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => $APPLICATION_ID,
'secret' => $APPLICATION_SECRET,
'cookie' => false,
'fileUpload' => true
));
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2013-12-04';
$event_privacy = "OPEN";
$ret_obj = $facebook->api('/'.$page_id.'/events?access_token='.$access_token, 'POST',
array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
if(isset($ret_obj['id'])) {
echo 'Event with added. ID: ' . $ret_obj['id'];
} else {
echo 'Couldn\'t create event';
}
What I did wrong?
You need a page access token.
Page Access Token – These access tokens are similar to user access
tokens, except that they provide permission to APIs that read, write
or modify the data belonging to a Facebook Page. To obtain a page
access token you need to start by obtaining a user access token and
asking for the manage_pages permission. Once you have the user access
token you then get the page access token via the Graph API.
Doc: https://developers.facebook.com/docs/facebook-login/access-tokens/
Then use GET /me/accounts to get the access token associated to your page.
I found the solution in How to programmatically add an event to a page using Graph API?. I had to add the access_token direct into the event array and everything works as expected:
$ret_obj = $facebook->api('/'.$page_id.'/events', 'POST',
array(
'access_token' => $access_token,
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
Thanks for the help!

Categories