Callback.php in Instagram API 8
File
src/Controller/Callback.php
View source
<?php
namespace Drupal\instagram_api\Controller;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
class Callback extends ControllerBase {
protected $loggerFactory;
public function __construct(ConfigFactory $config, LoggerChannelFactoryInterface $loggerFactory) {
$this->config = $config
->get('instagram_api.settings');
$this->configEditable = $config
->getEditable('instagram_api.settings');
$this->loggerFactory = $loggerFactory;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('config.factory'), $container
->get('logger.factory'));
}
public function callbackUrl(Request $request) {
$code = $request
->get('code');
$token = $this
->getToken($code);
if ($token != FALSE) {
$this->configEditable
->set('access_token', $token)
->save();
$markup = $this
->t("Access token saved");
}
else {
$markup = $this
->t("Failed to get access token. Check log messages.");
}
return [
'#markup' => $markup,
];
}
public function getToken($code) {
$guzzleClient = new GuzzleClient([
'base_uri' => $this->config
->get('api_uri'),
]);
$parameters = [
'client_id' => $this->config
->get('client_id'),
'client_secret' => $this->config
->get('client_secret'),
'redirect_uri' => Url::fromUri('internal:/instagram_api/callback', [
'absolute' => TRUE,
])
->toString(),
'grant_type' => 'authorization_code',
'code' => $code,
];
try {
$response = $guzzleClient
->request('POST', 'access_token', [
'form_params' => $parameters,
]);
if ($response
->getStatusCode() == 200) {
$contents = $response
->getBody()
->getContents();
return Json::decode($contents)['access_token'];
}
} catch (GuzzleException $e) {
$this->loggerFactory
->get('instagram_api')
->error("@message", [
'@message' => $e
->getMessage(),
]);
return FALSE;
}
}
}
Classes
Name |
Description |
Callback |
Class Instagram Callback Controller. |