oauth2-client for Google working in Codeigniter - php

Hi got a bit problem and I can't find any lead, here it goes
I'm working with OAuth2-client from here and I'm doing it in codeigniter
this is my controller :
public function index()
{
include(APPPATH.'libraries/League/OAuth2/Client/Provider/IdentityProvider.php');
include(APPPATH.'libraries/League/OAuth2/Client/Provider/Google.php');
$provider = new League\OAuth2\Client\Provider\Google(array(
'clientId' => '********************.apps.googleusercontent.com',
'clientSecret' => '**************************',
'redirectUri' => '**************************/oauth2callback'
));
if ( ! isset($_GET['code'])) {
// If we don't have an authorization code then get one
$provider->authorize();
} else {
try {
// Try to get an access token (using the authorization code grant)
$t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code']));
// NOTE: If you are using Eventbrite you will need to add the grant_type parameter (see below)
// $t = $provider->getAccessToken('authorization_code', array('code' => $_GET['code'], 'grant_type' => 'authorization_code'));
try {
// We got an access token, let's now get the user's details
$userDetails = $provider->getUserDetails($t);
foreach ($userDetails as $attribute => $value) {
var_dump($attribute, $value) . PHP_EOL . PHP_EOL;
}
} catch (Exception $e) {
// Failed to get user details
}
} catch (Exception $e) {
// Failed to get access token
}
}
}
I get the OAuth class and save it to my library folder
Somehow I manage to open the google "Choose Account" or "login" and the request for permission this
but when I click Accept the page reload to this url https://mysite.com/oauth2callback?state=****&code=***
and that is 404 in my end.
does anyone have better solution to this, could anyone help me.
this is my 1st try using OAUTH and working in google app engine so please spare me. Thanks in advance.

When the user approves the OAuth, Google redirects back to your app with the URL you registered with them, in your case this is /oauth2callback (this is actually the default). It looks as though, from the code you have posted, that the code to deal with this request is in the index() function.
So, to fix you code, you can either move the logic from the index function to a new handler / controller which responds to /oauth2callback, or change the redirectUri, both in your code and at google cloud console to point back to whatever URL calls the index() function.

404 mean you dont have "oauth2callback" controller or dont have index method in it
callback url is url you can get information requested to oauth provider
I see your url dont have index.php. If normal url of your project have it, you are putting wrong url. Solution is you need to put absolute callback url in callback param by using site_url function

There is a bug in the library, look at this: https://github.com/thephpleague/oauth2-client/issues/90
Anyway, i have the same problem: don't know how to code the callback controller.

Related

Retrieve posted parameters oauth2 (bshaffer) with access_token

I am in need of API provider for my web service(databse selects/inserts, folders/files editing/creation/delete actions etc.)
I found this library for oauth2
https://github.com/bshaffer/oauth2-server-php
So far i have been able to follow the tutorial/documentation trough and i can authenticate and access api.
Problem is that the example is simple and it does not show a way to pass in additional parameter such as mycustomaction=myustomvalue for the authenticated user.
The code that handles the resource is as follows
// include our OAuth2 Server object
require_once __DIR__.'/server.php';
// Handle a request to a resource and authenticate the access token
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
$server->getResponse()->send();
die;
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
Pseudo code of something similar that i need
// include our OAuth2 Server object
require_once __DIR__.'/server.php';
// Handle a request to a resource and authenticate the access token
if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) {
$server->getResponse()->send();
die;
}else{
if($customvalue){
//get the custom value and run code for it.
}
echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));
}
Is there a way to do what i need with this library?
P.S. I chose this library because it was the only one that had a working tutorial that i could follow trough. I can not install additional libraries on the client side(thus the simple include file)
the passed in extra values can be accessed like so
$server=OAuth2\Request::createFromGlobals();
echo var_dump($server->request);
However i don't know how correct this solution is.

Create a Facebook App that can post to a page I am an admin of

As part of the website I am working on, I need to be able to post directly to the wall of my clients Facebook Page.
I have created an App and am successfully posting to my own dummy profile by simply using:
$request = new FacebookRequest(
$session, 'POST', '/me/feed', array(
'link' => 'my_url',
'message' => 'my_message'
);
Now I need to modify this to post to my clients page, im assuming I cant just change 'me' to by their page ID because that would be a massive security flaw so I need to get permission somehow to post to their page. I am an admin for the page, how can I do this? Or do I actually need to be logged in with the user account that created the page?
I have looked all around in the developer section at creating an app but there doesn't seem to be any way of creating an app for a different account.
Any advice would be greatly appreciated on this.
Many thanks
In order to post to a Facebook page, you need to go through a two steps process -
login as the user using the extended user token,
get the user's token for the page
post to the page using the page's token.
The following code should be able to post a message to your page. I HAVEN'T DEBUGGED IT since it is simplified from my own web site :-) Don't forget to include the Facebook SDK files:
function extract_access_token_of_facebook_page_by_id($array_of_all_user_pages,$page_id){
$num_of_pages=count($array_of_all_user_pages['data']);
$the_page_token="";
for ($i=0; $i<$num_of_pages; $i++){
if ($array_of_all_user_pages['data'][$i]['id']==$page_id){
$the_page_token=$array_of_all_user_pages['data'][$i]['access_token'];
}
}
return $the_page_token;
}
$facebook = new Facebook(array(
'appId' => $YOUR-APP-ID,
'secret' => $YOUR-APP-SECRET,
));
try
{
$facebook->setAccessToken($THE-USER-TOKEN);
$page_id = YOUR-PAGE-ID;
$fanpage_access_token=extract_access_token_of_facebook_page_by_id($facebook->api("/me/accounts"),$page_id);
$args = array();
$args['access_token'] = $fanpage_access_token;
$args['message'] = "THE TEXT YOU WANT TO POST";
$api_url="/".$page_id."/feed";
$api_response = $facebook->api($api_url, 'post', $args);
}
catch (FacebookApiException $e)
{
echo 'Error facebookservice'.$e;
}
Please look into Application developer section. It will help you. Create on developer account and you will be able to access page.
you code is for old sdk version i think, it not work for me : Fatal error: Class 'Facebook' not found

POST Facebook Notification using Graph API

I'm trying to post notification using facebook graph api post method but I'm getting
(#15) This method must be called with an app access_token.
However the access_token which I'm sending in querystring is app access token which is fetched using this method
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=".FB_APP_ID."&client_secret=".FB_SECRET."&grant_type=client_credentials";
I 've seen few guys have implemented it but don't know why its not working for me, someone pls tell me where I'm wrong in it.
Thanks
EDIT
I got it working, here is the change
This line of code will never work, because the internal access_token will override the app access_token which we are trying to pass in query string.
$this->facebook->api("/".$to_userId."/notifications?access_token=$app_token_url&template=message",'POST');
So Use this code
$data = array(
'href'=> 'https://apps.facebook.com/MY_APP/',
'access_token'=> $app_token,
'template'=> 'test'
);
try {
$this->facebook->api("/".$to_userId."/notifications",'POST',$data);
} catch (FacebookApiException $e) {
}
Is your app accidentally configured as a 'native/desktop' app in the app settings? if so, change it back to 'web'

Facebook PHP SDK 3.1.1 "Error validating access token" after Go to App page

I'm having some strange issues building an iframe app for Facebook. The app seems to get stuck in an infinite loop on the Go To App page.
After the user authorizes the app in the Go To App page, and returns to the app, the /me api call throws the "Error validating access token" exception. I checked and there is a valid access token in the Signed Request (tested with the facebook access token debuggin tool). I tried setting that with the setAccessToken() method unsuccessfully.
The getUser() method successfully returns the user ID, but it still hangs on the /me api call.
This doesn't happen in every browser, i'm just seeing it in Chrome sometimes in a no clear pattern. I fixed it in IE using the P3P header. It works fine in Firefox.
I pretty much stuck and i'm out of hair to pull out so any ideas are welcome. Thanks a lot.
The full error message: "Error validating access token: You cannot access the app till you log in to www.facebook.com and follow the instructions given."
Some code below.
$this->_facebook = new Facebook(
array(
'appId' => $this->_config['appId'],
'secret' => $this->_config['secret'],
'cookie' => true,
'fileUpload' => true
)
);
$this->_signedRequest = $this->_facebook->getSignedRequest();
// Doing something with signed request, not FB related
$this->_userId = $this->_facebook->getUser();
if($this->_userId) {
try{
// At this line the "Error validating access token" error shows up
$this->_user = $this->_facebook->api('/me');
// Some more irrelevant code here
} catch (Exception $e){
$this->_facebook->destroySession();
$this->_facebookLogin(false);
}
} else {
$this->_facebook->destroySession();
$this->_facebookLogin(false);
}
// The _facebookLogin method
public function _facebookLogin($perms = 'email,user_birthday,publish_stream,video_upload'){
$data = array(
'fbconnect' => 0,
'redirect_uri' => 'aredirecturl.com'
);
if(!empty($perms)) {
$data['scope'] = $perms;
}
echo '<script type="text/javascript">window.top.location.href = "'.$this->_facebook->getLoginUrl($data).'";</script>';
exit;
}
Edit this part
// At this line the "Error validating access token" error shows up
$this->_user = $this->_facebook->api('/me');
to this
// At this line the "Error validating access token" error shows up
$this->_user = $this->facebook->api('/me','GET');
What about destroying your session by hand? Did you debug these parameters?
unset($_SESSION['fb_'.$YOUR_API_KEY.'_code']);
unset($_SESSION['fb_'.$YOUR_API_KEY.'_access_token']);
unset($_SESSION['fb_'.$YOUR_API_KEY.'_user_id']);
unset($_SESSION['fb_'.$YOUR_API_KEY.'_state']);
I am almost using the same code as you,but I'm not using fileUpload and cookie parameters.

Automatic Soundcloud PHP Api authentication without user interaction

In my application i want to use the Soundcloud API with my own Soundcloud user. The Soundcloud API authentication process involves a user being redirected to the Soundcloud homepage, login and authorize the application, so that the page can use the API for this user.
I want to automate the whole process, because my own user is the only user which gets authenticated. Is that possible?
Here is my code so far:
$soundcloud = new \Services_Soundcloud(
'**',
'**',
'http://**'
);
$authorizeUrl = $soundcloud->getAuthorizeUrl();
$accessToken = $soundcloud->accessToken();
try {
$me = json_decode($soundcloud->get('me'), true);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
But the line $accessToken = $soundcloud->accessToken(); throws an exception:
The requested URL responded with HTTP code 401.
500 Internal Server Error - Services_Soundcloud_Invalid_Http_Response_Code_Exception
Hi All,
Here I am going to share my experience with Soundcloud API (PHP)
See my Question: Link
Recently I started to work with Sound cloud API (PHP) and I decided to use PHP API by
https://github.com/mptre/php-soundcloud.
But When I was trying to get access token from Sound cloud server by this code:
// Get access token
try {
$accessToken = $soundcloud->accessToken($_GET['code']);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
I had check the $_GET['code'] value. But strange there is nothing in
$_GET['code'] this is blank. The Soundcloud was returning "The
requested URL responded with HTTP code 0" error. That time I was
testing Soundcloud on WAMP Localhost.
Allot of Goggling I found a solution to fix "The requested URL
responded with HTTP code 0" issue. I had download 'cacert.pem' file
and put inside our demo project folder (inside Services/Soundcloud/).
Then after I added some code in 'class Services_Soundcloud'
function protected function _request($url, $curlOptions = array()).
// My code in side function
$curlPath = realpath(getcwd().'\Services\cacert.pem');
$curlSSLSertificate = str_replace("\\", DIRECTORY_SEPARATOR, $curlPath);
curl_setopt($ch, CURLOPT_CAINFO, $curlSSLSertificate);
Saved 'class Services_Soundcloud' file and moved on live server. After
move my project from WAMP to Live server I start to check it again.
When I open my index.php it's ask me to login
I use my Facebook account to login.
after login it was asking to connect with Soundcloud
after connect everything working smooth, I got my info with
$me = json_decode($soundcloud->get('me'));
but a new problem start to occurring which was that my access token
being expire again and again. Then I use session :D
// code for access token
$code = $_GET['code'];
// Get access token
try {
if(!isset($_SESSION['token'])){
$accessToken = $soundcloud->accessToken($code);
$_SESSION['token'] = $accessToken['access_token'];
}else{
$soundcloud->setAccessToken($_SESSION['token']);
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
exit($e->getMessage());
}
And now everything working awesome. i can get all my details, tracks everything from SC server
Hope it will help you to fight with Soundcloud API Cheers!!!! :)
I'm looking for the same thing, but according to the soundcloud's api (check the Authenticating without the SoundCloud Connect Screen paragraph):
// this example is not supported by the PHP SDK
..and is not supported by the Javascript neither.
I've tryed to auth with python:
# create client object with app and user credentials
client = soundcloud.Client(client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
username='YOUR_USERNAME',
password='YOUR_PASSWORD')
..then the uploading python method:
# upload audio file
track = client.post('/tracks', track={
'title': 'This is my sound',
'asset_data': open('file.mp3', 'rb')
})
and it works just fine.
So, for now, you have 2 ways:
Use another language, Python or Ruby (the only 2 sdk that actually support this feature) or use a small python/ruby script as a bridge for this particular need;
Add this funcionaliy to the PHP SDK (i'm trying to do it quick'n'dirty, if i get success, i'll share ;)
There is no magic behind its implementation in Python and Ruby SDK's.
What's happening is that POST request is sent to http://api.soundcloud.com/oauth2/token with the following params:
client_id='YOUR_CLIENT_ID'
client_secret='YOUR_CLIENT_SECRET'
username='YOUR_USERNAME'
password='YOUR_PASSWORD'
And Content-Type: application/x-www-form-urlencoded
The response body contains access_token, that can be used for the further authorization of your requests. Thus, your GET request to /me endpoint will look like: /me?oauth_token=YOUR_ACCESS_TOKEN&client_id=YOUR_CLIENT_ID. (I believe, client_id is redundant here but all their apps keep adding it).
Here is the Postman Doc I created for demonstration: https://documenter.getpostman.com/view/3651572/soundcloud/7TT5oD9

Categories