I'm trying to make a guide on how to integrate Facebook SDK v5 with Laravel 5.0. Have anyone done this before?
First of all i added "facebook/php-sdk-v4" : "~5.0" in composer.json see documentatione here: https://developers.facebook.com/docs/php/gettingstarted
{
"require" : {
"facebook/php-sdk-v4" : "~5.0"
}
}
Next step composer install in CMD
composer install
Next i added a route:
Route::get('/test', 'Facebookintegration#test');
Next i returned a view:
public function test() {
return view('testpage');
}
Next i try to run the info in the view testpage
<?php
require_once URL::asset('vendor/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'YOUR_APP_ID',
'app_secret' => 'YOUR_APP_SECRET',
'default_graph_version' => 'v2.5',
]);
?>
Here is where the problems start and this is my current error
main(): Failed opening required 'http://localhost/fbintegration/vendor/autoload.php' (include_path='.;C:\php\pear')
anyone know how to correctly link yo the files?
https://github.com/SammyK/LaravelFacebookSdk
Use this package for Laravel instead.
The code below is to post to facebook after retrieving token from my DB
Route
Route::post('schedulePost', 'HomeController# exampelSchedulePost');
Composer.json
"require": {
"sammyk/laravel-facebook-sdk": "^3.0"
}
Provider and aliases , refer to Docs
'providers' => [
SammyK\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class,
];
'aliases' => [
'Facebook' => SammyK\LaravelFacebookSdk\FacebookFacade::class,
];
public function exampelSchedulePost(Request $request)
{
$postPermission = 0;
$profileToken = DB::table('profiles')->where('user_id',Auth::user()->id)->first();
$fb = App::make('SammyK\LaravelFacebookSdk\LaravelFacebookSdk');
if($profileToken){
try {
$response = $fb->get('/'.$profileToken->uid.'/permissions', $profileToken->access_token);
$permissions = $response->getGraphEdge();
foreach ($permissions as $item) {
if($item['permission'] == 'publish_actions'){
if($item['status']== 'declined'){
$login_link = $fb->getLoginUrl(['email,publish_actions'], 'http://www.URL.com/facebook/callback');
return redirect($login_link);
//Get Permission again
}
}
}
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
dd($e->getMessage());
}
}else{
$login_link = $fb->getLoginUrl(['email,publish_actions'], 'http://www.URL.com/facebook/callback');
return redirect($login_link);
}
It looks like the path issue when you want to require file in your view.
You can try something like this in you view template:
require_once ($app['path.base'].'/vendor/facebook/graph-sdk/src/Facebook/autoload.php');
And the I believe you can get Facebook\Facebook class without problem.
Related
I am building an Android app that is interfaced with a CakePHP 3 web API. Since a RESTful API cannot rely on cookies, I understand that I need JSON web tokens (JWT) to make this happen, and would much prefer to use a google login. I already got the Android side to request a token from Google's API, but now I am lost on how to incorporate this into my API for authentication.
I've searched around for some tutorials, such as this one: http://blog.jainsiddharth21.com/2013/04/29/login-with-google-in-cakephp/, but it relies on session data. I'm building the API in CakePHP 3, so I've looked at some of the plugins, such as ADmad/JwtAuth, so maybe I could extend on this to allow google authentication, but I am not sure how.
Login With Gmail and Specific email address to allowed to login in CakePHP 3.x
Composer to install
"google/apiclient": "^2.0"
Required gmail with login
https://console.developers.google.com/apis/credentials?project=mdpms-187410&organizationId=1095988912954
Create project and create secret key and client id
Project in set name and redirect URL
NOTE:- redirect URL must be .com and .org domain
If you develop in local machine then create follow type of virtual host
example.com and example.org
Virtual host create then
Follow this step:
Set configuration file in app_globle.php
'Google' =>
[
'googleClientID' => '123456.apps.googleusercontent.com',
'googleClientSecret' => 'abcdefghi',
'googleRedirectUrl' => 'http://example.com/oauth2callback'
]
Gmail login route
//Google login
$routes->connect('/account/google-login', ['controller' => 'Account', 'action' => 'googlelogin'], ['_name' => 'account-google-login']);
$routes->connect('/oauth2callback', ['controller' => 'Account', 'action' => 'confirmlogin'], ['_name' => 'account-google-redirect-url']);
Google login action code:
/**
* Gmail login method
*/
public function googlelogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->se
tScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$url = $client->createAuthUrl();
$this->redirect($url);
}
Google redirect url Action
/**
* Gmail auth redirect action
* #return type gmail auth data
*/
public function confirmlogin()
{
$client = new Google_Client();
$client->setClientId(Configure::read('Google.googleClientID'));
$client->setClientSecret(Configure::read('Google.googleClientSecret'));
$client->setRedirectUri(Configure::read('Google.googleRedirectUrl'));
$client->setScopes([
"https://www.googleapis.com/auth/userinfo.profile",
'https://www.googleapis.com/auth/userinfo.email'
]);
$client->setApprovalPrompt('auto');
$usersTable = TableRegistry::get('Users');
if (isset($this->request->query['code'])) {
$client->authenticate($this->request->query['code']);
$this->request->Session()->write('access_token', $client->getAccessToken());
}
if ($this->request->Session()->check('access_token') && ($this->request->Session()->read('access_token'))) {
$client->setAccessToken($this->request->Session()->read('access_token'));
}
if ($client->getAccessToken()) {
$this->request->Session()->write('access_token', $client->getAccessToken());
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
try {
if (!empty($user)) {
if ((preg_match("/(#example\.com)$/", $user['email'])) || (preg_match("/(#example\.in)$/", $user['email']))) {
$result = $usersTable->find('all')
->where(['email' => $user['email']])
->first();
if (!empty($result)) {
$this->AccessControl->setUser($result->toArray(), false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$data = [];
$data['email'] = $user['email'];
$data['first_name'] = $user['givenName'];
$data['last_name'] = $user['familyName'];
$data['socialId'] = $user['id'];
$data['role_id'] = Configure::read('Role.loginWithGmailUserRole');
//$data matches my Users table
$entity = $usersTable->newEntity($data);
if ($usersTable->save($entity)) {
$data['id'] = $entity->id;
$this->AccessControl->setUser($data, false);
$this->Flash->set(__('You have successfuly logged in.'), ['element' => 'success']);
$this->redirect(['_name' => 'dashboard']);
} else {
$this->Flash->error(__('Invalid login.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
}
} else {
$this->Flash->error(__('Your email is invalid for this application.'));
//redirect to login action
$this->redirect(['_name' => 'account-login']);
}
} else {
$this->Flash->error(__('Gmail infos not found.'));
//redirect to login action
return $this->redirect(['_name' => 'account-login']);
}
} catch (\Exception $e) {
$this->Flash->error(__('Gmail error.'));
return $this->redirect(['_name' => 'account-login']);
}
}
}
We are trying to use dynamic facebook app credentials for Laravel 5.1 socialite.
config/services.php
'facebook' => [
'client_id' => 'xxxx',
'client_secret' => 'xxxx',
'redirect' => 'http://example.com/facebook-callback',
],
On my controller file:
public function getConnectFacebook()
{
return Socialite::driver('facebook')->redirect();
}
public function getFacebookCallback()
{
$user = Socialite::driver('facebook')->user();
}
We tried to overwrite the facebook driver this way:
public function getConnectFacebook()
{
Config::Set("services.facebook.client_id", "dynamic_app_id");
Config::Set("services.facebook.client_secret", "dynamic_app_secret");
Config::Set("services.facebook.redirect", "dynamic_app_redirect");
return Socialite::driver('facebook')->redirect();
}
But it was not working. Could you please let me know how we can achieve this?
Thanks.
like this
return Socialite::driver('facebook')->redirect()->setTargetUrl('your callback url');
Here is my solution.
private function makeFacebookDriver($domain){
//grab and set your config values from database or array. Don't do Config::Set.
$config['client_id'] = '';//grab fb id based from db based on domain
$config['client_secret'] = '';//grab fb secret from db based on domain
$config['redirect'] = 'http://'.$domain.'/fbcallback';
return Socialite::buildProvider(\Laravel\Socialite\Two\FacebookProvider::class, $config);
}
then use the function instead of calling Socialite::driver('Facebook');
$fb = $this->makeFacebookDriver('www.test.com');
return $fb->redirect();
just use it in your controller
use Laravel\Socialite\Two\FacebookProvider;
config
$config = [
'client_id' => '969935-d61celu1qck667krmbgql.apps.googlesercontent.com',
'client_secret' => 'sHrnnOz3Fmz4',
'redirect' => 'http://localhost:8000/api/login/facebook/callback'
];
$user= Socialite::buildProvider(FacebookProvider::class, $config)->stateless();
return $user->redirect();
stateless in callback
$userSocial =$config = [
'client_id' => '969d61celu1qck667krmbgql.apps.googlesercontent.com',
'client_secret' => 'sHrnnO3Fmz4',
'redirect' => 'http://localhost:8000/api/login/facebook/callback'
];
$user=Socialite::buildProvider(FacebookProvider::class, $config)-
>stateless()->user();
api or web.php
Route::get('login/{provider}', 'SocialController#redirect');
Route::get('login/{provider}/callback','SocialController#Callback');
You could also do a simple find and replace.
Let's say you have a config file like this
'facebook' => [
'client_id' => '{ID}',
'client_secret' => '{SECRET}',
'redirect' => '{REDIRECT}',
],
Now within your controller you can do something like this.
$fileName = 'path/to/file.php';
$configData = file_get_contents($file);
$configData = str_replace('{ID}','dynamic_id',$configData);
$configData = str_replace('{SECRET}','dynamic_secret',$configData);
$configData = str_replace('{REDIRECT}','dynamic_link',$configData);
file_put_contents($file, $configData);
That's it, nothing fancier.
I have wordpress 4.1 with the following plugin installed:
iThemes Security
WordPress SEO
I plugged in a function the facebook sdk.
This is the code:
//Footer
add_action('wp_footer', 'my_footer');
function my_footer() {
$post_to_check = get_post(get_the_ID());
if ( is_singular() && has_shortcode( $post_to_check->post_content, 'myshortcode' ) ) {
?>
<script>
var DEBUG = true;
jQuery(document).ready(function($){
$.ajax({
type : "POST",
url : "index.php",
data : { action : "value" },
success : function(response){
// the server has finished executing PHP and has returned something, so display it!
if(DEBUG){ console.log('AJAX done...'); }
}
});
});
</script>
<?php
}
}
//ajax
add_action('init', 'my_request');
function my_request() {
if ( isset($_POST['action']) && $_POST['action'] == 'value' ) {
session_start();
require_once __DIR__ . "/sdk/autoload.php";
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\GraphUser;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookSDKException;
$app_id = getAppId();
$app_secret = getAppSecret();
$rdr_fb_url = curPageURL();
$required_scope = 'public_profile, email';
if(empty($app_id) || empty($app_secret))
exit('Error.');
FacebookSession::setDefaultApplication($app_id , $app_secret);
$helper = new FacebookRedirectLoginHelper($rdr_fb_url);
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
die(" Error : " . $ex->getMessage());
} catch(\Exception $ex) {
// When validation fails or other local issues
die(" Error : " . $ex->getMessage());
}
var_dump($session);
if ($session){
$user_profile = (new FacebookRequest($session, 'GET', '/me'))->execute()->getGraphObject(GraphUser::className());
echo 'Hi'.$user_profile->getName();
}else{
//display login url
$login_url = $helper->getLoginUrl( array( 'scope' => $required_scope ) );
}
?>
<div class="login">
Login
</div>
<?php
exit();
}
}
Works fine if i use this outside of wordpress.
In wp var_dump($session); retrive always null. (no error given) Even after accepting the terms of the application. it is as if he could not get the code in the url.
I also tried to disable the plugin, but nothing.
I need php, please don't tell me to use javascript.
Sorry for my bad english :P
Edit:
I use the permalink:
http://www.myste.com/%year%/%monthnum%/%postname%/
I think the problem is the rewrite rule that hide a facebook get.
Solved: I entered the code outside of the ajax call, in function my_footer() {
I am following this tutorial to extend the Sugarcrm webservice to define the new service for my custom module.
Problem: But, as a preliminary check, I tried to call the existing login service and that itself fails. Please help in pointing where the issue is. I am stuck.
Tutorial I am following: http://support.sugarcrm.com/02_Documentation/04_Sugar_Developer/Sugar_Developer_Guide_6.5/02_Application_Framework/Web_Services/06_Extending_Web_Services/
As mentioned in the tutorial, I created the following files in the folder, custom/service/v4_1_custom
registry.php
<?php
require_once('service/v4_1/registry.php');
class registry_v4_1_custom extends registry_v4_1
{
protected function registerFunction()
{
parent::registerFunction();
$this->serviceClass->registerFunction('my_get_orders',
array(
'session' => 'xsd:string',
'module_name' => 'xsd:string',
'id' => 'xsd:string',
),
array(
'return' => 'xsd:string',
)
);
}
}
?>
soap.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
chdir('../../..');
require_once('SugarWebServiceImplv4_1_custom.php');
$webservice_class = 'SugarSoapService2';
$webservice_path = 'service/v2/SugarSoapService2.php';
$registry_class = 'registry_v4_1_custom';
$registry_path = 'custom/service/v4_1_custom/registry.php';
$webservice_impl_class = 'SugarWebServiceImplv4_1_custom';
$location = 'custom/service/v4_1_custom/soap.php';
require_once('service/core/webservice.php');
?>
SugarWebServiceImplv4_1_custom.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('service/v4_1/SugarWebServiceImplv4_1.php');
class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
/*
* Returns the id if authenticated
*
* #param id
* #return string $session - false if invalid.
*
*/
function my_get_orders($session, $module_name, $id)
{
$GLOBALS['log']->info('Begin: SugarWebServiceImplv4_1_custom->my_get_orders');
$error = new SoapError();
//authenticate
if (!self::$helperObject->checkSessionAndModuleAccess($session, 'invalid_session', '', '', '', $error))
{
$GLOBALS['log']->info('End: SugarWebServiceImplv4_1_custom->my_get_orders.');
return false;
}
return $id;
}
}
?>
My webservice client for testing the webservice: SoapTest.php
SoapTest.php
<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
require_once('../include/nusoap/nusoap.php'); //must also have the nusoap code on the ClientSide.
$user_name ='myuser';
$user_password = 'mypassword';
$hostname = 'http://127.0.0.1/sugarcrm/custom/service/v4_1_custom/soap.php?wsdl';
// Create the SOAP client instance
$soapclient = new nusoapclient($hostname, true);
// Login to the server
echo '<b>LOGIN:</b><BR>';
$result = $soapclient->call('login',array('user_auth'=>array('user_name'=>$user_name,'password'=>md5($user_password), 'version'=>'.01'), 'application_name'=>'SoapTest'));
echo '<BR><BR><b>HERE IS RESULT:</b><BR>';
echo print_r($result);
echo var_dump($result);
$session = $result['id'];
echo "sessionid is ".$session;
?>
Expected Result: Since I am calling the login, i expect to see the sessionid.
Note: I am not calling the custom method my_get_orders as the login itself fails. So i like to fix it first.
Actual Result: [while invoking http://127.0.0.1/sugarcrm/prash/SoapTest.php]
HERE IS RESULT:
1
boolean false
sessionid is
I put the same set of files under service/custom [ The existing versions are directly under service/ eg : service/v4_1 ].
Now it works, so earlier it was the case of file path resolving issue.
Iam new guy for Zend2 framework...I got an error which I didnt trace it...
Iam writing a controller named 'usertask' and in that fir index function i wrote the code like this
public function indexAction()
{
$sendRequest = new SendRequests;
$tableGrid = new DynamicTable();
$prop = array(
'customRequest' => 'GET',
'headerInformation' => array('environment: development', 'token_secret: abc')
);
$returnRequest = $sendRequest->set($prop)->requests('http://service-api/usertask');
$returnData = json_decode($returnRequest['return'],true);
$tableGrid->tableArray = $returnData['result'];
$dynamicTable = $tableGrid->tableGenerate();
$view = new ViewModel(array(
'usertask' => $dynamicTable
));
//print_r($view);exit;
return $view;
}
but it is not listing my usertasks...while Iam printing $returnRequest its giving me error message like
The server don't receive a Response / SendRequests
what it the mistake in my code...could anyone suggest me...please..iam using "zend2"
Sorry guys I found my mistake ...I got big code but I need something like
public function indexAction()
{
$view = new ViewModel(array(
'usertask' => $this->UserTable()->fetchall(),
));
return $view;
}
public function getUserTable()
{
if (!$this->userTable) {
$sm = $this->getServiceLocator();
$this->userTable = $sm->get('User\Model\UserTable');
}
return $this->userTable;
}
that's it...i got it as a list of users