File: D:/HostingSpaces/SBogers10/deensekroon.komma-mediadesign.nl/wwwroot/php/Vend/Auth/AuthService.php
<?php
namespace Vend\Auth;
include_once($_SERVER['DOCUMENT_ROOT'] . '/php/Vend/Auth/AuthRepository.php');
include_once($_SERVER['DOCUMENT_ROOT'] . '/php/Vend/Curl/CurlService.php');
include_once $_SERVER['DOCUMENT_ROOT'] . '/lib/Carbon/Carbon.php';
use Carbon\Carbon;
use Vend\Curl\CurlService;
class AuthService
{
private $clientId = 'FShjr89uPeq2S5sAB8Y8odxpf709YOrD';
private $clientSecret = 'kP6IOnc4fauaarXUpsz8HnroxpShUajh';
/**
* @var AuthRepository
*/
private $repository;
/**
* @var CurlService
*/
private $curlService;
public function __construct()
{
$this->repository = new AuthRepository();
$this->curlService = new CurlService();
}
/**
* Attempt authorization
* @return String
*/
public function token()
{
// Check for current token in the database
$lastAttempt = $this->repository->lastAttempt();
// Check if token is still valid
if($this->isValid($lastAttempt))
{
// Set token to access token
return $lastAttempt->access_token;
}
// If expired: update token with refresh_token
return $this->refreshToken($lastAttempt->refresh_token);
}
/**
* Check if attempt isn't expired
*
* @param $attempt
* @return bool
*/
private function isValid($attempt)
{
// Get created date
$expires = Carbon::createFromTimestamp($attempt->expires,'Europe/Amsterdam');
// If expired return false
if(Carbon::now('Europe/Amsterdam') >= $expires) return false;
// Return valid
return true;
}
/**
* Refresh token
*
* @param $refreshToken
* @return array
*/
private function refreshToken($refreshToken)
{
// Set data
$data = [
'refresh_token' => $refreshToken,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'grant_type' => 'refresh_token'
];
// Get JSON response
$response = $this->curlService->post('https://danishcrown.vendhq.com/api/1.0/token',$data);
if( ! isset($response[1])) return false;
// Decode JSON
$data = json_decode($response[1]);
// Update token in database
$this->repository->updateToken($data);
// Return token
return $data->access_token;
}
/**
* This code is a short-lived object (10 min.) and can only be used once.
* In practice this means that before requesting a new authorisation token
* you always have to request the code first.
*/
private function requestCode()
{
// Enter this url in browser
// https://secure.vendhq.com/connect?response_type=code&client_id=FShjr89uPeq2S5sAB8Y8odxpf709YOrD&redirect_uri=http://www.deensekroon.komma-mediadesign.nl/vend/api
}
}