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.
Related
my controller file inside api/v1/controller/
class ProfileController extends ActiveController
{
public $modelClass = 'app\models\Profile';
public function behaviors()
{
return [
[
'class' => 'yii\filters\ContentNegotiator',
'only' =>
['index', 'view', 'createnew','update','search'],
'formats' =>
['application/json' => Response::FORMAT_JSON,],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'index' => ['get'],
'view' => ['get'],
'createnew' => ['post'],
'update' => ['put'],
'delete' => ['delete'],
'deleteall' => ['post'],
'search' => ['get']
],
]
];
}
public function actionCreatenew() {
$model = new Profile();
$model->load(Yii::$app->request->post());
$model->asset = UploadedFile::getInstance($model, 'asset');
$name = $model->user_id;
if($model->asset) {
$model->asset->saveAs('uploads/'.$name.'.
'.$model->asset->extension);
$model->asset = $model->asset->name.'.'.
$model->asset->extension;
}
if($model->save()) {
echo json_encode(array('status'=>"Success",
'data'=>$model->attributes),JSON_PRETTY_PRINT);
} else {
echo json_encode(array('status'=>"Failure",
'error_code'=>400,
'errors'=>$model->errors),JSON_PRETTY_PRINT);
}
}
}
When I try to use access this from Postman like:
POST http://localhost/myapp/api/v1/profiles
I get Invalid Parameter – yii\base\InvalidParamException
Response content must not be an array.
What is the issue?? help would be grateful!! Thanks
You can easily receive single / multi-uploaded files using HTTP POST with form-data encoding in Yii2, directly in your Yii2 Controller / action.
Use this code:
$uploads = UploadedFile::getInstancesByName("upfile");
if (empty($uploads)){
return "Must upload at least 1 file in upfile form-data POST";
}
// $uploads now contains 1 or more UploadedFile instances
$savedfiles = [];
foreach ($uploads as $file){
$path = //Generate your save file path here;
$file->saveAs($path); //Your uploaded file is saved, you can process it further from here
}
If you use Postman API client to test how your API is working, you can configure the upload endpoint to work like this for multi-file uploads:
Note: The upfile[] square brackets are important! Postman will happily let you select multiple files for upload in one slot, but this will not actually work. Doing it the way shown in the screenshot makes an array of files available to the Yii2 action, through the UploadedFile mechanism. This is roughly equivalent to the standard PHP $_FILES superglobal variable but with easier handling.
Single files can be uploaded with or without the [] square brackets after the key name. And of course you can name upfile whatever you like, for your convention.
You should use \yii\web\UploadedFile::getInstanceByName('asset'); instead of getInstance() checkout this Link
Im following the tutorial from symfony's website to make my phpunit's test for my controller.
Im trying to test an upload on a form and i have 3 fields on this form : title,description and file.
I use :
public function testScenarioAdd() {
$client = static::createClient();
$x_wsse = 'UsernameToken Username="username#fai.fr", PasswordDigest="aeirugbjcUbfmùJK", Nonce="OTMzOGMwYzFkYTk2MzJmYzBh", Created="2013-11-12T10:22:15+01:00"';
//X_Wsse is for the connection systeme on my application.
$image = new UploadedFile(
'/past/to/your/images.jpg',
'images.jpg',
'image/jpeg',
100000
);
$crawler = $client->request('POST', '/ad/create', array('ad_form' => array('title' => 'test', 'description' => 'Test description')),array(), array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));
$response = $client->getResponse()->getContent();
$json_response = json_decode($response);
print_r($response);
}
When i launch it I have an error saying :
{"app_error":{"success":500,"result":[{"message":"Array to string conversion",...
Am i doing something wrong ? or missing something in my code ?
Thanks for your help :)
Edit :
Thanks but, what ive done there is working on another test without upload, i still tried it and its not working. I still have the error array to string... I think it come from the fonction UplaodedFile or maybe from my controller itself because when i try the other solution from symfony's web site with
$photo = array(
'tmp_name' => '/path/to/photo.jpg',
'name' => 'photo.jpg',
'type' => 'image/jpeg',
'size' => 123,
'error' => UPLOAD_ERR_OK
);
With putting the
$crawler = $client->request('POST', '/ad/create', array('ad_form[title]' => 'test', ad_form[description] => 'test description'),array('file' => $image),array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));
The important part of my controller is :
if ('POST' === $request->getMethod()) {
$form->bind($request);
if ($form->isValid())
{
$Ad->preCreate();
$odm->persist($Ad);
$odm->flush();
$odm->clear();
$data = $this->listAction($request, 1, 5);
Tags::setEvent($request, $this->container, 'member.create.ad', $user->getId(), $Ad->getId());
return $data;
} else {
$data = Errors::formatJson($form, $this->container);
}
}
}
return new JsonResponse(array('ad_create' => $data));
Im kinda new in symfony, i really dont know where this error can come from...
Client::Request method expects you to provide it with one-dimensional array of data. So try this code:
<?php
//...
$crawler = $client->request('POST', '/ad/create',
array('ad_form[title]' => 'test',
'ad_form[description]' => 'Test description'),
array(),
array('CONTENT_TYPE' => 'application/x-www-form-urlencoded', 'HTTP_X-WSSE' => $x_wsse));
I want to create a redirect using a query string in Zend 1.12. The optional parameters should be in the form of a query string.
This is my code:
if ($this->_request->getParam('partner')){
$controller = $this->getRequest()->getControllerName();
$action = $this->getRequest()->getActionName();
$module = $this->getRequest()->getModuleName();
$params = array(
"utm_source" => "affiliate",
"utm_medium" => "cpa",
"utm_term" => $this->_request->getParam('partner'),
"utm_campaign" => "partners",
"url" => $this->_request->getParam('url')
);¬
$this->_helper->redirector($action, $controller, $module, $params);
return false;
}
}
This produces an URL like
/content/agb/utm_source/affiliate/utm_medium/cpa/utm_term/foo
However I want this to look like:
/content/agb?utm_source=affiliate&utm_medium=cpa&utm_term=foo
How could I do that?
Thanks!
I've had better success with building the URL myself and using gotoUrlAndExit()
$this->_helper->redirector->gotoUrlAndExit('place?thing=value');
I have problem with Facebook PHP SDK. It always throws that exception. I tried many solutions listed here, but nothing works for me.
It seems that Facebook returns to me valid access token, because I tested it with Debug tool in dashboard of my application.
What's my scenario?
I want to post to publish simple content to user's wall by calling static function:
function social_publish($network, $title, $message, $link = '', $image = '') {
global $_config;
// Initialize Facebook SDK
$facebook = new Facebook(array(
'appId' => $_config['fb_app']['app_id'],
'secret' => $_config['fb_app']['app_security_key']
));
// Set data
$attachment = array(
'name' => $title,
'caption' => $title,
'message' => $message,
'link' => $link,
'picture' => $image,
'actions' => array('name' => 'Test', 'link' => 'Link')
);
try {
$access_token = $facebook->getAccessToken(); // returns valid access token
$uid = $facebook->getUser(); // always return 0
$result = $facebook->api( '/' . $_config['fb_profile'] . '/feed/', 'post', $attachment); // $_config['fb_profile'] procudes 'me' in this case
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
}
Just to note: I am not working on local environment.
problem solve it as asked in scope request to Facebook for authentication, as I decided to use the JavaScript SDK-and then, here's the solution:
FB.getLoginStatus(function(response) {
if ( ! response.authResponse ) {
FB.login(function(response) {
// handle the response if needed
}, {scope: 'publish_actions, publish_stream'});
}
});
Thank you! :-)
I'm using the Facebook Graph API and want to check if a user has authenticated my Facebook app by user ID. How do I do this?
You use:
SELECT is_app_user FROM user WHERE uid=USER_ID
This should return:
[
{
"is_app_user": true
}
]
If the user has logged in to your application.
Expanding on ifaour's answer, in PHP this query would look something like this:
<?php
$facebook = new Facebook(
'appID' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
);
$result = $facebook->api(array(
'method' => 'fql.query',
'query' => "SELECT is_app_user FROM user WHERE uid=$user_id"
));
$is_installed = $result[0]['is_app_user'];
Here you can batch multiple requests together and avoid using FQL.
Assuming you have already logged into facebook and set the access token to the application access token, you can do this:
$batch = array();
foreach($friendArray AS $friend) {
$batch[] = array(
'method' => 'GET',
'relative_url' => '/' . $friend . '?fields=installed'
);
}
FB()->useApplicationAccessToken();
$batchResponse = FB()->facebook()->api('?batch='.json_encode($batch), 'POST');
Then you can process the batch response with code like this:
$installedUsers = array();
$notInstalledUsers = array();
foreach ($batchResponse AS $response) {
$body = json_decode($response['body'], true);
if (!isset($body['id']))
continue;
$id = $body['id'];
if (isset($body['installed']))
$installedUsers[] = $id;
else
$notInstalledUsers[] = $id;
}