Using Google's API through laravel/hybridauth - php

I want to create an app that uses Google+ APIs through hybridauth.
I'm using atticmedia/anvard version of hybridauth, that is already configured with Google's clientID and secretKey that have been generated through Google Developer Console (I have inserted these info inside the hybridauth.php file inside the config folder of laravel). I have setted the scope too (as Google suggest).
"scope" => "https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
I do the following in a laravel route:
if (!$hybridauth->isConnectedWith('Google')) {
$adapter = $hybridauth->authenticate('Google');
}
else {
$adapter = $hybridauth->getAdapter('Google');
}
$profile = $adapter->getUserProfile();
Till now, everything goes well. The profile is correctely printed using the var_dump() function. So I can assume I am logged in. Now I want to make a call to Google APIs (for example this). In the same laravel route, after printing the user's profile, i do the following:
$answer= $adapter->api()->api('/people', 'get', array(
'query' => 'Google'
));
As shown in this page, I can use the api() method to do the call. But the only result I can print is "NULL". I suspect that somehow the request is not correct, but I tryed almost anything, and I have not found yet a "real" example of Google API in conjuction with laravel/hybridauth.

When calling $adapter->api in hybridauth to access Google APIs, you must use the full HTTP URL request.
$answer= $adapter->api()->api('https://www.googleapis.com/plus/v1/people/me');
For other services, such as Facebook, you don't need to
$answer= $adapter->api()->api('/me');
I'm using Laravel 4.2.11 and hybridauth dev-master
Reference: http://hybridauth.sourceforge.net/userguide/tuts/advanced-access-google-api.html

Related

Facebook Platform - Verifying Facebook User Access Token in v2.2

Question about the upgrade to v2.2 of the Facebook Platform, in particular, this part:
The previously deprecated REST API has been completely removed in
v2.1, and all apps still using it must migrate to using Graph API.
For the most part, in my Android and iOS app I am not using the REST API. I'm using the Android SDK and the iOS SDK. However, I do have one exception. When I call my server to login or really do basically anything, I try to assure that the person trying to login/access data is indeed the person they say they are. I do this:
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$response = file_get_contents("https://graph.facebook.com/debug_token?input_token=".$accessToken."&access_token=MY_APP_ACCESS_TOKEN", false, $context);
$jsonObject = json_decode($response, true);
$data = $jsonObject["data"];
$facebookId = $this->getFacebookId();
if(isset($data['is_valid']) && $data['is_valid'] === true) {
if(isset($data['user_id'])) {
if($data['user_id'] == $facebookId) {
return true;
A little bit of code missing there, but that's the gist of it. Get an access token and a facebook id. I use the access token to see if it's legitamite and the user_id assigned to that access token is the id of the person trying to get info. If so, I let them in.
My question is, am I understanding correctly that this is going away and I have to use the Graph API to somehow do the same thing? How is this done through the Graph API in PHP given an access token and facebook id from Android/iOS?
EDIT: Just realized this is actually in the 2.0 to 2.1 section, but question still stands, should I be concerned about my server side code?
Thanks!
I'm thinking I don't have anything to worry about. The approach I'm using is in the Facebook Platform docs here:
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#checktoken
Under inspecting access tokens. Nothing on this page talks about it being deprecated.

How to get user image with Twitter API 1.1?

In API 1.0, we can use users/profile_image/:screen_name
For example : http://api.twitter.com/1/users/profile_image/EA_FIFA_FRANCE
But, it doesn't work anymore in API 1.1.
Do you have a solution, please ?
You can also get the twitter profile image by calling this kind of url :
https://twitter.com/[screen_name]/profile_image?size=original
For instance : https://twitter.com/VancityReynolds/profile_image?size=original
Got the info from this post :
https://twittercommunity.com/t/how-to-get-user-image-original-size-with-api-1-1/10187/14
The user's profile image
Okay, so you want a user's profile image. You're going to need to take a look at the twitter REST API 1.1 docs. This is a list of all the different requests you can make to their API (don't worry, I'll get to how you actually do this later on).
There are multiple ways to get the user's profile image, but the most notable one is: users/show. According to the docs for this, the users/show method:
Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible.
Well, the user profile image must be in there somewhere, correct?
Let's have a look at a typical response to a request for this information, using the users/show url (we'll use my profile as an example).
I've cut off some from the bottom, because there is a lot of data to go through. Most importantly, you'll see what you require:
This is the profile_image_url key that you need to get access to.
So, how do you do all this? It's pretty simple, actually.
Authenticated Requests
As you rightly pointed out, as of June 11th 2013 you can't make unauthenticated requests, or any to the 1.0 API any more, because it has been retired. So OAuth is the way to make requests to the 1.1 API.
I wrote a stack overflow post with an aim to help all you guys make authenticated requests to the 1.1 API with little to no effort.
When you use it, you'll get back the response you see above. Follow the posts instructions, step-by-step, and you can get the library here (you only need to include one file in your project).
Basically, the previous post explains that you need to do the following:
Create a twitter developer account
Get yourself a set of unique keys from twitter (4 keys in total).
Set your application to have read/write access
Include TwitterApiExchange.php (the library)
Put your keys in a $settings array
Choose your URL and request method (Post/Get) from the docs (I put the link above!)
Make the request, that's it!
A practical example
I'm going to assume you followed the step-by-step instructions in the above post (containing pretty colour pictures). Here's the code you would use to get what you want.
// Require the library file, obviously
require_once('TwitterAPIExchange.php');
// Set up your settings with the keys you get from the dev site
$settings = array(
'oauth_access_token' => "YOUR_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
// Chooose the url you want from the docs, this is the users/show
$url = 'https://api.twitter.com/1.1/users/show.json';
// The request method, according to the docs, is GET, not POST
$requestMethod = 'GET';
// Set up your get string, we're using my screen name here
$getfield = '?screen_name=j7mbo';
// Create the object
$twitter = new TwitterAPIExchange($settings);
// Make the request and get the response into the $json variable
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
echo $result->profile_image_url;
That's pretty much it! Very simple. There's also users/lookup which effectively does the same thing, but you can:
Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.
If you ever need to get more than one user's details, use that, but as you only require one user's details, use users/show as above.
I hope that cleared things up a bit!
You say you want to use Twitter API 1.1 and yet you don't want to authenticate your requests.
Unauthenticated requests are not supported in API v1.1. So please adjust to the API change. See updates :
https://dev.twitter.com/blog/planning-for-api-v1-retirement
https://dev.twitter.com/docs/rate-limiting/1.1
You can get image from profile_image_url field of https://api.twitter.com/1.1/users/show.json request. Either a id or screen_name is required for this method. For example :
GET https://api.twitter.com/1.1/users/show.json?screen_name=rsarver
See details here https://dev.twitter.com/docs/api/1.1/get/users/show
I try the above methods to get the profile URL but it does not work for me. I think because Twitter changes API v1.1 to API v2.0.
I found a simple method to get a profile URL.
I use Twitter API v2 there User Lookup -> User by Username API part
Code Sample:
https://api.twitter.com/2/users/by/username/{user_name}?user.fields=profile_image_url
For Example:
https://api.twitter.com/2/users/by/username/TwitterDev?user.fields=profile_image_url
Of course, You should request with your Bearer Token then it properly work. For that, I recommend a platform it calls postman. It really helps for calling API.
Above example code return JSON like this:
{
"data": {
"name": "Twitter Dev",
"profile_image_url": "https://pbs.twimg.com/profile_images/1445764922474827784/W2zEPN7U_normal.jpg",
"username": "TwitterDev",
"id": "2244994945"
}
}
Additional:
If You want the Profile Image to be a higher size. Then you can put size in place of normal in the URL. For More Details read this one
Like This:
https://pbs.twimg.com/profile_images/1445764922474827784/W2zEPN7U_400x400.jpg
Give a vote to help more developers. 🍵
As the previous answers and comments point out:
Twitter API v1.0 is deprecated
Twitter API v1.1 requires OAuth
OP (#Steffi) doesn't want to authenticate
Pick any two; with all three it's a no-go. #Jimbo's answer is correct (and the proper way to do it), but excludes #3. Throwing out #1 means going back in time. But, we can throw out #2, and go directly to the source:
curl -s https://twitter.com/EA_FIFA_FRANCE |
sed -ne 's/^.*ProfileAvatar-image.*\(https:[^"]*\).*$/\1/p'
The sed command just says, find the line that contains "ProfileAvatar-image" and print the substring that looks like a quoted URL.
This is less stable than an authenticated API call, since Twitter may change their HTML at any time, but it's easier than dealing with OAuth, and no official rate limits!
The PHP translation should be straightforward.
try this
http://api.twitter.com/1/users/profile_image/{twitter_account}.xml?size=bigger
In API 1.1 the only way is to connect your application, retrieve the user by
https://dev.twitter.com/docs/api/1.1/get/users/show
and retrieve after his picture
profile_image_url
Hare is a very simple way to get Twitter Profile picture.
http://res.cloudinary.com/demo/image/twitter_name/w_300/{User_Name}.jpg
it's my Profile picutre:
Big: http://res.cloudinary.com/demo/image/twitter_name/w_300/avto_key.jpg
Small: http://res.cloudinary.com/demo/image/twitter_name/w_100/avto_key.jpg
you can regulate size by this part of URL - w_100, w_200, w_500 and etc.

Rendering SoundCloud widget for a private track using PHP API

I am trying to render a SoundCloud HTML5 widget using the PHP API, but every time I run the command I think should return the HTML for the widget, I simply get an Exception:
The requested URL responded with HTTP code 302
I realise this is a redirect. What I don't know is why that's all I ever get, or what to do about it to actually get the widget HTML.
The documentation on the API says that to embed the widget using PHP you should do this:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = $client->get('/oembed', array('url' => $track_url));
// render the html for the player widget
print $embed_info['html'];
I'm running this:
// NB: Fully authorised SoundCloud API instance all working prior to this line
// $this->api refers to an authorised instance of Services_Soundcloud
try {
$widget = array_pop(
json_decode( $this->api->get('oembed', array('url' => $track_url)) )
);
print_r($widget);
} catch (Exception $e)
{
print_r($e->getMessage());
}
where "track_url" is actually the URL I get back when asking SoundCloud for a track object earlier in the app using the same API.
I'm not actually sure this URL is correct in the first place, because the track object I get back gives the 'uri' in the form:
[uri] => https://api.soundcloud.com/tracks/62556508
The documentation examples all have a straight http://soundcloud.com/username/track-permalink URL - but even using a known path to a public track the attempt to run the API oembed method fails... I still get a 302 Exception.
Finally, there are mentions of setting "allow_redirects" to false in the 'get' command, but this has no effect when I add to the parameters used to build the query to the API. I also tried adding additional cURL options, but that too had no effect.
I have definitely enabled API access to the track within SoundCloud.
Kind of banging my head off the wall on this. If anyone has any pointers I'd be very grateful to hear them. Just for clarity's sake, I am able to access all the user data, comments etc. via the API instance I have created, so it appears to be working fine.
Thanks for pointing this out. There was a bug in the documentation that lead you astray. Sorry about that. I've updated the docs to fix the bug. Here's the updated code sample:
<?php
require_once 'Services/Soundcloud.php';
// create a client object with your app credentials
$client = new Services_Soundcloud('YOUR_CLIENT_ID', 'YOUR_CLIENT_SECRET');
$client->setCurlOptions(array(CURLOPT_FOLLOWLOCATION => 1));
// get a tracks oembed data
$track_url = 'http://soundcloud.com/forss/flickermood';
$embed_info = json_decode($client->get('oembed', array('url' => $track_url)));
// render the html for the player widget
print $embed_info->html;
Note the differences:
You need to set CURLOPT_FOLLOWLOCATION to 1 as mentioned in the comments above.
You need to wrap the return from $client->get in json_decode
The result is an stdClass object, not an Array and so the html property has to be accessed using the -> operator.
Hope that helps. Feel free to comment in case you're still having problems and I'll amend my answer.

How do I use Google's "Simple API Access key" to access Google Calendar info (PHP)?

I'm trying to use the Google API v3 to access one google calendar and according to the documentation here : http://code.google.com/apis/calendar/v3/using.html#intro and here : https://code.google.com/apis/console/, the solution I need is the "Simple API Access" & "Key for server apps (with IP locking)".
Now, when I create a page with this code :
session_start();
require_once 'fnc/google-api-php-client/src/apiClient.php';
require_once 'fnc/google-api-php-client/src/contrib/apiCalendarService.php';
$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);
if (isset($_SESSION['oauth_access_token'])) {$apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $apiClient->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
and in my "config.php" file I add ONLY my developper key (in place of the "X") :
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
But then I get errors and it tells me it's trying to authenticate using the "OAuth 2.0" system which I don't want to use. I only want to access one calendar with an API key.
And amazingly, when I search in google "Simple API Access key" I find nothing, nothing on their docs, no examples, no tutorials, nothing. Am I the only one using this thing?
So can someone tell me what I'm doing wrong?
(i know this is an old question but i would've been glad if someone
gave a real answer here so i'm doing it now)
I came on the same problem, Simple API access is not well documented (or maybe just not where i searched), but using the Google API Explorer i found a way to get what i need, which is in fact pretty straightforward. You don't need specific lib or anything : it's actually really simple.
In my case i simply needed to search a keyword on G+, so i just had to do a GET request:
https://www.googleapis.com/plus/v1/activities?query={KEYWORD}&key={YOUR_API_KEY}
Now, for a calendar access (see here), let's pretend we want to fetch access control rules list. We need to refer to calendar.acl.list which give us the URI :
https://www.googleapis.com/calendar/v3/calendars/{CALENDAR_ID}/acl?key={YOUR_API_KEY}
Fill in the blanks, and that's pretty much all you need to do. Get a server key (API Access submenu), store it somewhere in your project and call it within URIs you're requesting.
You cannot access your calendar information using API Key. API keys (or simple API acess key) are not authorized tokens and can only be used for some API calls such as a Google search query etc; API keys will not let you access any user specific data, which I am assuming is your objective through this calendar application.
Also, from what I see in your code, you are creating a client object which is going to use OAuth 2.0 authentication and hence you are getting authentication error messages.
There is no such a thing called Simple API Access key.
Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.
If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.
I got to this thread when trying to do the same today. Although this is way late, but the answer is YES, there is actually simple API key for those apis that does not need user authorizations, and the official client library support this.
The api library do this by Options, which is key, value pair.
Take the example of get information of a given youtube video, you would use this api: https://godoc.org/google.golang.org/api/youtube/v3#VideosListCall.Do
To use api key, simply make a type that implements the CallOption interface, and let it return the api key:
type APIKey struct {
}
func (k *APIKey) Get() (string, string) {
return "key", "YOU API KEY HERE"
}
Then when calling the API, supply the APIKey to it:
youtube, err := youtube.New(&http.Client{})
call := youtube.Videos.List("snippet,contentDetails,statistics").Id(id)
rsp, err := call.Do(opt)
This way, you can construct the youtube client with the vallina http client, rather than oauth client, and enjoy the simple api key.
The first answer said you can use http GET directly, but then you will need to handle the errors and parse the result yourself.
See below link which is helpfull to you. The Google API Client Library enables you to work with Google APIs such as Analytics, Adsense, Google+, Calendar, Moderator, Tasks, or Latitude on your server, in the language of your choice.
http://code.google.com/p/google-api-php-client/
Thanks,
Chintu

Twitter OAuth (PHP): Need good, basic example to get started

Using Facebook's PHP SDK, I was able to get Facebook login working pretty quickly on my website. They simply set a $user variable that can be accessed very easily.
I've had no such luck trying to get Twitter's OAuth login working... quite frankly, their github material is confusing and useless for someone that's relatively new to PHP and web design, not to mention that many of the unofficial examples I've tried working through are just as confusing or are outdated.
I really need some help getting Twitter login working--I mean just a basic example where I click the login button, I authorize my app, and it redirects to a page where it displays the name of the logged in user.
I really appreciate your help.
EDIT I'm aware of the existence of abraham's twitter oauth but it provides close to no instructions whatsoever to get his stuff working.
this one is the basic example of getting the url for authorization and then fetching the user basic info when once u get back from twitter
<?php
session_start();
//add autoload note:do check your file paths in autoload.php
require "ret/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//this code will run when returned from twiter after authentication
if(isset($_SESSION['oauth_token'])){
$oauth_token=$_SESSION['oauth_token'];unset($_SESSION['oauth_token']);
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
//necessary to get access token other wise u will not have permision to get user info
$params=array("oauth_verifier" => $_GET['oauth_verifier'],"oauth_token"=>$_GET['oauth_token']);
$access_token = $connection->oauth("oauth/access_token", $params);
//now again create new instance using updated return oauth_token and oauth_token_secret because old one expired if u dont u this u will also get token expired error
$connection = new TwitterOAuth($consumer_key, $consumer_secret,
$access_token['oauth_token'],$access_token['oauth_token_secret']);
$content = $connection->get("account/verify_credentials");
print_r($content);
}
else{
// main startup code
$consumer_key = 'your consumer key';
$consumer_secret = 'your secret key';
//this code will return your valid url which u can use in iframe src to popup or can directly view the page as its happening in this example
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$temporary_credentials = $connection->oauth('oauth/request_token', array("oauth_callback" =>'http://dev.crm.alifca.com/twitter/index.php'));
$_SESSION['oauth_token']=$temporary_credentials['oauth_token']; $_SESSION['oauth_token_secret']=$temporary_credentials['oauth_token_secret'];$url = $connection->url("oauth/authorize", array("oauth_token" => $temporary_credentials['oauth_token']));
// REDIRECTING TO THE URL
header('Location: ' . $url);
}
?>
I just tried abraham's twitteroauth from github and it seems to work fine for me. This is what I did
git clone https://github.com/abraham/twitteroauth.git
Upload this into your webhost with domain, say, www.example.com
Go to Twitter Apps and register your application. The changes that you need are (assuming that you will use abraham's twitteroauth example hosted at http://www.example.com/twitteroauth)
a) Application Website will be http://www.example.com/twitteroauth
b) Application type will be browser
c) Callback url is http://www.example.com/twitteroauth/callback.php (Callback.php is included in the git source)
Once you do this, you will get the CONSUMER_KEY and CONSUMER_SECRET which you can update in the config.php from the twitteroauth distribution. Also set the callback to be the same as http://www.example.com/twitteroauth/callback.php
Thats it. If you now navigate to http://www.example.com/twitteroauth, you will get a "Signin with Twitter", that will take you to Twitter , authorize the request and get you back to the index.php page.
EDIT:
Example will not work but do not worry. Follow the above steps and upload to server.
Make sure you rename the file from github repository i.e. config-sample.php->config.php
if you want to see a working sample, find it here
Here are some OAuth 1.0A PHP libraries with examples:
tmhOAuth
Oauth-php
Twitter async
Twitter async provides documentation on how to simply sign in a user as you asked for.
Here is the step by step guide to integrate Twitter OAuth API to Web-application using PHP. Please following tutorial.
http://www.smarttutorials.net/sign-in-with-twitter-oauth-api-using-php/
You need to create Twitter App First By going thorugh following URL
https://apps.twitter.com/
Then you need to provide necessary information for the twitter app. Once your provided all the information and then save it. You will get Twitter application Consumer Key and Consumer secret.
Please download the source file from above link, and just replace TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET and TWITTER_OAUTH_CALLBACK with your Consumer Key (API Key), Consumer Secret (API Secret) and callback URL. Then upload this to your server. Now it will work successfully.
Abraham's Twitteroauth has a working demo here:
https://github.com/abraham/twitteroauth-demo
Following the steps in the demo readme worked for me. In order to run composer on macOS I had to do this after installing it: mv composer.phar /usr/local/bin/composer
IMO the demo could be a lot simpler and should be included in the main twitteroauth repo.
I recently had to post new tweets to Twitter via PHP using V2 of their API but couldn’t find any decent examples online that didn’t use V1 or V1.1. I eventually figured it out using the great package TwitterOAuth.
Install this package via composer require abraham/twitteroauth first (or manually) and visit developer.twitter.com, create a new app to get the credentials needed to use the API (see below). Then you can post a tweet based on the code below.
use Abraham\TwitterOAuth\TwitterOAuth;
// Connect
$connection = new TwitterOAuth($twitterConsumerKey, // Your API key
$twitterConsumerSecret, // Your API secret key
$twitterOauthAccessToken, // From your app created at https://developer.twitter.com/
$twitterOauthAccessTokenSecret); // From your app created at https://developer.twitter.com/
// Set API version to 2
$connection->setApiVersion('2');
// POST the tweet; the third parameter must be set to true so it is sent as JSON
// See https://developer.twitter.com/en/docs/twitter-api/tweets/manage-tweets/api-reference/post-tweets for all options
$response = $connection->post('tweets', ['text' => 'Hello Twitter'], true);
if (isset($response['title']) && $response['title'] == 'Unauthorized') {
// Handle error
} else {
var_dump($response);
/*
object(stdClass)#404 (1) {
["data"]=>
object(stdClass)#397 (2) {
["id"]=>
string(19) "0123456789012345678"
["text"]=>
string(13) "Hello Twitter"
}
}
*/
}

Categories