ApiController.php in Facebook Instant Articles 8.2
File
src/Controller/ApiController.php
View source
<?php
namespace Drupal\fb_instant_articles\Controller;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class ApiController extends ControllerBase {
protected $configFactory;
public function __construct(ConfigFactoryInterface $config_factory) {
$this->configFactory = $config_factory;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'));
}
public function facebookLogin() {
$config = $this->configFactory
->getEditable('fb_instant_articles.settings');
$fb = new Facebook([
'app_id' => $config
->get('app_id'),
'app_secret' => $config
->get('app_secret'),
'default_graph_version' => 'v2.5',
]);
$helper = $fb
->getRedirectLoginHelper();
try {
$access_token = $helper
->getAccessToken();
if ($access_token == NULL) {
$error_msg = $this
->t('We failed to authenticate your Facebook account with this module. Please try again.');
$this
->messenger()
->addError($error_msg);
}
else {
$permissions = $fb
->get('/me/permissions', $access_token)
->getGraphEdge();
$rejected_permissions = [];
foreach ($permissions as $permission) {
if ($permission
->getField('status') != 'granted') {
$rejected_permissions[] = $permission
->getField('permission');
}
}
if (!empty($rejected_permissions)) {
$error_msg = $this
->t('You did not grant the following required permissions in the Facebook authentication process: @permissions. Please try again.', [
'@permissions' => implode(', ', $rejected_permissions),
]);
$this
->messenger()
->addError($error_msg);
}
else {
$config
->set('access_token', $access_token
->getValue())
->save();
$this
->messenger()
->addStatus('Facebook authentication was successful. Access token obtained.');
}
}
} catch (FacebookResponseException $e) {
$error_msg = $this
->t('We received the following error while attempting to authenticate your Facebook account: @error', [
'@error' => $e
->getMessage(),
]);
$this
->messenger()
->addError($error_msg);
} catch (FacebookSDKException $e) {
$error_msg = $this
->t('We received the following error while attempting to authenticate your Facebook account: @error', [
'@error' => $e
->getMessage(),
]);
$this
->messenger()
->addError($error_msg);
}
return new RedirectResponse(Url::fromRoute('fb_instant_articles.api_settings_form')
->toString());
}
}