I am trying to get user access token so I can send CURL request through Guzzle to Facebook's Graph API to get user's friends that are using the app. But I can't seem to be able to obtain it.
Here's my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;
use Socialite;
class SocialFriendsController extends Controller
{
public function getFacebookFriends()
{
$user = Socialite::driver('facebook')->user();
$access_token = $user->token;
$client = new Client();
$body = $client->get('https://graph.facebook.com/v2.11/me/friends', [
'query' => [
'access_token' => '$access_token',
]
])->getBody();
$result = \GuzzleHttp\json_decode($body, 1);
return view('pages.admin.posts.create', ['result' => $result]);
}
}
Once you have followed the previous answer to fix the reference to $access_token you can do the following steps with the facebook SDK to retrieve a long lived token from Facebook so you can make many calls to the API. The default auth token will work for 2 hours after which you will need to re-initiate the oAuth flow to get a new token. A long lived token gets you 2 months of access before having to do the oAuth again.
https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension
$facebook = new \Facebook\Facebook();
$client = $facebook->getOAuth2Client();
$twoMonthToken = $client->getLongLivedAccessToken($twoHourToken);
Update the user with the $twoMonthToken
A couple of things to note. First of all, the following part of your code won't work the way you expect it to:
'access_token' => '$access_token',
You're trying to do variable interpolation, which doesn't work when you use single quotes ('). You should use double quotes ("$access_token") instead, or since you're not actually doing anything else with that string, you could just remove the quotes altogether.
Secondly, when doing Facebook logins (In your case, using Socialite) the access token you receive from Facebook is single use (I think so anyway - at least from my own experience). When you do Socialite::driver('facebook')->user(), Socialite is actually using the access token to grab the user object. If you attempt to use it again, Facebook will return an error.
Socialite is probably not the way to go to achieve what you're trying to do. I would suggest using the Facebook SDK directly to get what you're after.
$user = Socialite::driver('facebook')->userFromToken($access_token);
You can simply pass your access_token like above that will return user info.
Related
I had to install shopify-cli for develop shopify app with laravel. installation and test app are created successfully but when am i calling the API of shopify in Laravel app i got this error.
I am check header but no authorisation token pass. So my question how to get authenticate token get in Laravel starter app and call API of Shopify and i was follow PHP guide REST Admin API reference but without session i can not access shopify REST Admin API reference.
my code show like this...
Route::get('/rest-example', function (Request $request) {
/** #var AuthSession */
// $session = $request->get('shopifySession'); // Provided by the shopify.auth middleware, guaranteed to be active
$session = OAuth::callback(
$request->cookie(),
$request->query(),
['App\Lib\CookieHandler', 'saveShopifyCookie'],
);
$client = new Rest($session->getShop(), $session->getAccessToken());
$result = $client->get('products', [], ['limit' => 5]);
return response($result->getDecodedBody());
})->middleware('shopify.auth:online')->name('rest-api');
I think you want to create Custom App (not embedded) for your store.
You can read here about difference. I spent the whole day searching for solutions until get the idea.
All you need to do is to create a Custom App in your store, then get Admin API access token with you can use for REST API calls.
Here is my small example how I get it.
use Shopify\Clients\Rest;
Route::get('/test', function(Request $request) {
$client = new Rest(
env('SHOPIFY_APP_HOST_NAME'),
env('SHOPIFY_APP_ADMIN_ACCESS_TOKEN') // shpat_***
);
dd($client->get('products')->getDecodedBody());
});
I'm using Hybridauth 3 in my PHP app to make some periodical tweets on behalf of my account.
The app has all possible permissions. I'm giving it all permissions when it asks for them on the first auth step.
After that Twitter redirects me to the specified callback URL and there I'm getting a pair of access_token and access_token_secret.
But when I'm trying to make a tweet using these tokens - it gives me:
{"errors":[{"code":220,"message":"Your credentials do not allow access to this resource."}]}
Here's how I'm trying to make a tweet:
$config = [
'authentication_parameters' => [
//Location where to redirect users once they authenticate
'callback' => 'https://mysite/twittercallback/',
//Twitter application credentials
'keys' => [
'key' => 'xxx',
'secret' => 'yyy'
],
'authorize' => true
]
];
$adapter = new Hybridauth\Provider\Twitter($config['authentication_parameters']);
//Attempt to authenticate the user
$adapter->setAccessToken(/*tokens I've got from getAccessToken() on /twittercallback/*/);
if(! $adapter->isConnected()) {
// never goes here, so adapter is connected
return null;
}
try{
$response = $adapter->setUserStatus('Hello world!');
}
catch (\Exception $e) {
// here I've got the error
echo $e->getMessage();
return;
}
Tried to recreate tokens and key\secret pairs and passed auth process for the app many times, including entering password for my Twitter account (as suggested in some posts on stackoverflow) but still have this error.
P.S. According to this, Hybridauth has fixed the issue in the recent release.
It looks like you are using application authentication as opposed to user authentication. In order to post a tweet, you must authenticate as a user. Also, make sure your Twitter app has read/write privileges.
After comparing headers of outgoing requests from my server with the ones required by Twitter, I've noticed that Hybris doesn't add very important part of the header: oauth_token. At least it's not doing this in the code for Twitter adapter and for the scenario when you apply access token with setAccessToken(). It's just storing tokens in the inner storage but not initializing corresponding class member called consumerToken in OAuth1 class.
So to initialize the consumer token properly I've overridden the apiRequest method for Twitter class (before it used the defalut parent implementation) and added a small condition, so when consumer token is empty before the request - we need to try to init it.
public function apiRequest($url, $method = 'GET', $parameters = [], $headers = [])
{
if(empty($this->consumerToken)) {
$this->initialize();
}
return parent::apiRequest($url, $method, $parameters, $headers);
}
I'm not sure that I've fixed it the best way, but as long as it's working - that's fine.
For your info setAccessToken was fixed in v3.0.0-beta.2 (see PR https://github.com/hybridauth/hybridauth/pull/880)
I faced the same error when implementing a sample app in clojure and the following resource was a huge help to sort out my confusion about application-only auth vs user authentication: https://developer.twitter.com/en/docs/basics/authentication/overview/oauth
I am trying to create a web-app with a simple dashboard with Analytics data for the accounts who logged in with Google. I am using Laravel with Socialite package, and I can log the users in with Google currently. I have my developer client-key and client-secret. I set scopes for Analytics read-only, and offline access, and I store customer name, email, Google ID, access token and refresh token in my database. I can log the user in without any problem.
What I want to do is for now, just access the profiles an Analytics account currently has. I followed Analytics API documentation examples but could not get it working. Since I am storing an access token and a refresh token, I think I should be able to authenticate the current user and get their Analytics data, but I could not find any simple methods from the Client and Analytics libraries. I will need to access their Analytics data offline, and this is why I think I should be able to authorize my requests with access token and refresh token, but I do not get any Analytics specific data from user login process. I am completely lost now, how do I authorize my requests to Anayltics API? I have been using AdWords API for more than 8 months, and everything is crystal clear in AdWords API documentation, but I could not get anything working with Analytics API.
These are my user login methods:
public function redirectToProvider()
{
$parameters = ['access_type' => 'offline'];
return Socialite::driver('google')
->scopes(['https://www.googleapis.com/auth/analytics.readonly'])
->with($parameters)
->redirect();
}
/**
* Obtain the user information from Google.
*
* #return Response
*/
public function handleProviderCallback()
{
$outsiderLogin = Socialite::driver('google')->stateless()->user();
$user = User::where('googleID', $outsiderLogin->id)->first();
// Register the user if there is no user with that id.
if (!$user) {
$user = new User;
$user->name = $outsiderLogin->name;
$user->googleID = $outsiderLogin->id;
$user->email = $outsiderLogin->email;
$user->token = $outsiderLogin->token;
$user->refreshToken = $outsiderLogin->refreshToken;
$user->save();
}
// Log the user in.
Auth::login($user);
return redirect('/home');
}
Thank you very much.
I have found the solution for now. At first, I figured that I needed the code that returns with authentication URL from Google, and when I inspect the Socialite package, I have found a protected method getCode() in \vendor\laravel\socialite\src\Two\AbstractProvider.php, which returns the code from the URL. I edited the source file of the package and changed the method type from protected to public, and that made it possible to use that method outside of the class, which allowed me to access the code from the URL, then store it in DB for further authentication requirements. But there were issues with this setup, first of all, I should find a way to keep that package without any update, since any update will rollback the changes I made to the source file. The second problem I faced was the way I store tokens. By default, Google Client API returns an array which contains the fields access_token, refresh_token, expires_in, id and created, and with these fields, it authenticates the requests to Analytics server. In my scenario, there were no standard array returning from the basic Socialite login process. There were access_token, refresh_token and expires variables and I stored them all in my database as well. This caused an issue with Google library, it asked for a structured array and I did not even have the variables expires_in and created, this is why I setup a fake array which tells Google to refresh token with every request, and this was not a good practice either.
At the end, I could not understand how to use any package online and I wrote my own simple authentication, and I do not know if it has any vulnerabilities, but it works for me, it may also work for those who needs it.
Here are my routes lines:
Route::get('auth/google', [
'as' => 'googleLogin',
'uses' => 'Auth\AuthController#redirectToProvider'
]);
Route::get('auth/google/callback', [
'as' => 'googleLoginCallback',
'uses' => 'Auth\AuthController#handleProviderCallback'
]);
And these are the AuthController methods:
/**
* Redirect the user to the Google authentication
*/
public function redirectToProvider()
{
// Create the client object and set the authorization configuration from JSON file.
$client = new Google_Client();
$client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth/google/callback');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->addScope("email");
$client->addScope("profile");
$client->setAccessType("offline");
$auth_url = $client->createAuthUrl();
return redirect($auth_url);
}
/**
* Obtain the user information from Google.
*
* #return redirect to the app.
*/
public function handleProviderCallback()
{
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
return redirect('auth/google');
} else {
// Authenticate the client, and get required informations.
$client = new Google_Client();
$client->setAuthConfig('/home/vagrant/Analytics/client_secret.json');
$client->authenticate($_GET['code']);
// Store the tokens in the session.
Session::put('token', $client->getAccessToken());
$service = new Google_Service_Oauth2($client);
$userInfo = $service->userinfo->get();
$user = User::where('googleID', $userInfo->id)->first();
// If no match, register the user.
if(!$user) {
$user = new User;
$user->name = $userInfo->name;
$user->googleID = $userInfo->id;
$user->email = $userInfo->email;
$user->refreshToken = $client->getRefreshToken();
$user->code = $_GET['code'];
$user->save();
}
Auth::login($user);
return redirect('/home');
}
}
I have placed the client_secret.json file I have downloaded from Google API Console into the specified folder, this may be different for you. I have also modified the migration file in order to match the required segemnts. After these steps, I am able treat that user as it is a simple user that registered with the basic Laravel auth.
Now I can query, say, the accounts in the user's Google Analytics account like this:
/**
* #var $client to be authorized by Google.
*/
private $client;
/**
* #var $analytics Analytics object to be used.
*/
private $analytics;
public function __construct()
{
$this->client = $this->AuthenticateCurrentClient();
$this->analytics = new Google_Service_Analytics($this->client);
}
private function AuthenticateCurrentClient(){
$user = Auth::user();
$token = Session::get('token');
// Authenticate the client.
$client = new Google_Client();
$client->setAccessToken($token);
$client->authenticate($user->code);
return $client;
}
public function GetAccounts(){
try {
$accountsObject = $this->analytics->management_accounts->listManagementAccounts();
$accounts = $accountsObject->getItems();
return $accounts;
} catch (apiServiceException $e) {
print 'There was an Analytics API service error '
. $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error '
. $e->getCode() . ':' . $e->getMessage();
}
}
There were thousands of times Stack Overflow has helped me, I hope this helps someone to get things working.
You're not really going to find what you're looking for with the Socialite package shipped with Laravel (which is more used for logins and that's about it).
You can however find many Google Analytic packages (along with many other Laravel bundles) here which should help you make API calls:
http://packalyst.com/s/google%20analytics
More specifically, this package: https://github.com/spatie/laravel-analytics
That, or run your own Guzzle and cURL scripts. I use Guzzle when I need something quick without building a full blown API.
However, there's an interesting post here about using Socialite to access GA data. But you're quite limited. If you're creating user driven dashboards, I'd opt for a separate package.
https://laracasts.com/discuss/channels/tips/how-i-made-google-analytics-work-with-socialite
I'am also trying to do the same thing. By far, I've user authentication at place with oAuth 2.0 and Socialite package. I need the list of sites to be fetched from GA. And am totally stuck there. It would really be great if you can guide me as on how should I move on further..
I'm new to using API's and am currently trying to use the Trade Me API on a new application I am developing.
Their authorisation guidelines say they use OAuth to authenticate the API calls and that these can either be specified in the query string or the authorization header.
Being fairly new to API calls, I tried using the guzzlehttp/oauth-subscriber but failed miserably when trying to make the call.
So currently I am just trying to append the details to the query string.
The call I am trying to make requires:
oauth_consumer_key
oauth_signature
oauth_signature_method
Where oauth_consumer_key is the consumer key and oauth_signature is the consumer secret.
When I try to visit this URL to test the URL is correct - https://api.tmsandbox.co.nz/v1/Listings/123.json?oauth_consumer_key=XXX&oauth_signature=XXX&oauth_signature_method=PLAINTEXT
I get an error that:
"ErrorDescription":"Invalid PLAINTEXT signature."
I've obviously replaced my keys in the above URL but I can't see what is wrong with the above, it seems to match their documentation.
Can someone either point out what I am doing wrong?
Assuming you're using Guzzle and Laravel, as the comments stated, this would be a very simple example of how to achieve this (just put it in routes.php):
Route::get( '/', function ()
{
$client = new GuzzleHttp\Client( ["base_uri" => "https://api.tmsandbox.co.nz/v1/"] );
$response = $client->request( "GET", "Listings/123.json", ["headers" => ["Authorization" => 'OAuth oauth_consumer_key="YOUR-CONSUMER-KEY", oauth_signature_method="PLAINTEXT", oauth_signature="YOUR-CONSUMER-SECRET&"']] );
return Response::json($response->getBody()->getContents());
} );
According to the documentation the endpoint looks like
GET /debug_token?
input_token={input-token}&
access_token={access-token}
where
input_token: the access token you want to get information about
access_token: your app access token or a valid user access token from a developer of the app
Assuming I don't have a "valid user access token from a developer of the app" - just because I don't want to refresh it every 2 months and keep always it in mind - how would I perform it using "app access token"?
The getApplicationAccessToken() method is protected, so there is no way to access it without overriding it to public.
Any elegant solution that I'm missing?
PS: a call example that would fail with "You must provide an app access token or a user access token that is an owner or developer of the app" error due to lack of access token:
$tokenDebug = $fb->api('debug_token', array(
'input_token' => $token,
));
PPS: the "interesting" thing is that the error from above would appear not for every $token but for some, and I cannot see any obvious distinction between tokens that fail and that succeed.
PPPS: $token is a user access token
PPPPS: Created a feature request for FB PHP SDK https://developers.facebook.com/bugs/637897982899835
PPPPPS: Probably it could be better to create a pull request instead, but it's 1:30am and I'm too tired for that
OK, so if one needs an app access token, app_id|app_secret (both values concatenated with a pipe symbol in the middle) always works.
The method getApplicationAccessToken seems to have been protected in the PHP SDK up to 3.2.2 – whereas getAppId and getAppSecret are already public in that version; so those could be the alternative to hard-coding id and secret in place.
The PHP SDK has the getOAuth2Client() client method, that returns a \Facebook\Authentication\OAuth2Client instance.
This has the debugToken($accessToken) method, that returns a \Facebook\Authentication\AccessTokenMetadata instance that contains data about the access token.
$appid = '123456789';
$appsecret = 'foobar';
$api = new Facebook(['app_id' => $appid, 'app_secret' => $appsecret]);
$oauth = $api->getOAuth2Client();
$meta = $oauth->debugToken($accessToken);
$meta->validateAppId($appid); // Will throw a FacebookSDKException if invalid
$meta->getIsValid(); // boolean
$meta->getExpiresAt(); // \DateTime|null