oc-social-plugin/formwidgets/InstagramLogin.php

76 lines
2.0 KiB
PHP

<?php namespace Zoomyboy\Social\FormWidgets;
use \Session;
use Backend\Classes\FormWidgetBase;
use Zoomyboy\Social\Classes\InstagramService;
use Zoomyboy\Social\Models\InstagramUser;
use Zoomyboy\Social\Models\Page;
use Zoomyboy\Social\Models\Setting;
/**
* InstagramLogin Form Widget
*/
class InstagramLogin extends FormWidgetBase
{
/**
* @inheritDoc
*/
protected $defaultAlias = 'zoomyboy_social_instagram_login';
/**
* @inheritDoc
*/
public function init()
{
if (request()->has('code') && request()->query('state') == Session::get('instagram_auth_state')) {
$accessToken = app(InstagramService::class)->authenticate();
$this->storeUser($accessToken);
}
}
public function render()
{
$this->prepareVars();
return $this->makePartial('instagramlogin');
}
/**
* Prepares the form widget view data
*/
public function prepareVars()
{
$state = str_random('20');
Session::put('instagram_auth_state', $state);
$this->vars['name'] = $this->formField->getName();
$this->vars['value'] = $this->getLoadValue();
$this->vars['model'] = $this->model;
$this->vars['client_id'] = app(InstagramService::class)->clientId();
$this->vars['redirect_url'] = app(InstagramService::class)->redirectUri();
$this->vars['state'] = $state;
}
public function loadAssets()
{
$this->addCss('css/facebooklogin.css', 'zoomyboy.social');
$this->addJs('js/facebooklogin.js', 'zoomyboy.social');
}
public function getSaveValue($value)
{
return $value;
}
private function storeUser(string $accessToken): void
{
$me = app(InstagramService::class)->me($accessToken);
Page::create([
'access_token' => $accessToken,
'type' => app(InstagramService::class)->getType(),
'name' => $me['username'],
'remote_id' => $me['id'],
]);
}
}