How To Install Sylius and Fetch Access Token For API?
SYLIUS INSTALLATION
For installing Sylius the following points are necessary :
- The PHP version should be 7.2 or higher.
- The composer should have been installed.
Follow the below given points to install Sylius:
- To creating your new project, run the following command :
- $ composer create-project sylius/sylius-standard your_project_name
- Move inside your project directory
- $ cd your_project_name
- Now create .env.local file below .env file in the same directory and add/customise with variable you want to override like:
- DATABASE_URL=mysql://username:password@host/my_custom_sylius_database
- Run the following command to install Sylius:
- $ php bin/console sylius:install
- The above command will ask to provide more information and it sets currency as USD and default locale as English – US which can be changed later.
- For fully functional front-end run following commands:
- $ yarn install
- $ yarn build
By following above commands you will be able to access your Sylius shop after running the command symfony server:start and accessing http://127.0.0.1:8000 on your web browser.
How to use Sylius API?
To use Sylius API, one need to get access token for the same which can be fetched by following steps:
- Create OAuth client by running following command:
- $ php bin/console sylius:oauth-server:create-client –grant-type=”password” –grant-type=”refresh_token” –grant-type=”token”
- You will receive a response like : A new client with public id XYZ, secret ABC has been added.
Now, From your API Client ,
Register your API end point to get access token:
protected $endpoints = [
'getToken' => [
'url' => 'oauth/v2/token',
'method' => 'POST',
'requiredToken' => FALSE
],
];
Creating a function to get Access Token :
/**
* This function revokes the access key once expired
* and set it to $this->accessToken.
*/
public function revokeAccessKey($endpoint)
{
$this->ch = \curl_init();
$request = $this->createRequest($endpoint);
$this->setDefaultCurlSettings();
$response = $this->createResponse();
if (\curl_errno($this->ch)) {
$response['error'] = \curl_error($this->ch);
$response['code'] = 0;
}
\curl_close($this->ch);
if ($response['response_code'] == 200 && isset($response['access_token'])) {
$this->accessToken = $response['access_token'];
}
}
The above function call 3 major functions:
- Creating request for Access Token API.
- Default Curl Setting.
- Creating response for Access Token API.
Creating request for Access Token API.
protected function createRequest($endpoint)
{
if (! array_key_exists($endpoint, $this->endpoints)) {
return;
}
$method = $this->endpoints[$endpoint]['method'];
$endpoint = $this->endpoints[$endpoint]['url'];
$body = '';
//$this->url is your store URL
$url = $this->url . $endpoint;
$isAuthenticate = true;
if('oauth/v2/token' === $endpoint) {
$data = [
'grant_type' => 'password',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'username' => $this->username,
'password' => $this->password
];
$isAuthenticate = false;
}
$hasData = !empty($data);
// Setup authentication.
$this->authenticate($url, $isAuthenticate);
// Setup method.
$this->setupMethod($method);
// Include post fields.
if ($hasData) {
$body = json_encode($data);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $body);
}
return;
}
protected function authenticate($url, $isAuthenticate)
{
\curl_setopt($this->ch, CURLOPT_URL, $url);
\curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->getRequestHeaders($isAuthenticate));
}
/**
* Setup method.
*
* @param string $method Request method.
*/
protected function setupMethod($method)
{
if ('POST' == $method) {
\curl_setopt($this->ch, CURLOPT_POST, true);
\curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
} elseif (\in_array($method, ['PATCH', 'PUT', 'DELETE', 'OPTIONS'])) {
\curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $method);
}
}
Default Curl Setting.
/**
* This function sets default cURL settings.
*/
protected function setDefaultCurlSettings()
{
$verifySsl = !empty($this->options['verifySsl']) ? $this->options['verifySsl'] : false;
$timeout = !empty($this->options['timeout']) ? $this->options['timeout'] : 60 ;
$followRedirects = !empty($this->options['followRedirects']) ? $this->options['followRedirects'] : true;
\curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $verifySsl);
if (!$verifySsl) {
\curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $verifySsl);
}
if ($followRedirects) {
\curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, $followRedirects);
}
\curl_setopt($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);
\curl_setopt($this->ch, CURLOPT_TIMEOUT, $timeout);
\curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
\curl_setopt($this->ch, CURLOPT_HEADER, 1);
}
Creating response for Access Token API.
/**
* Create response.
*
* @return Response
*/
protected function createResponse()
{
$body = \curl_exec($this->ch);
$code = \curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
$code = \curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
$headers = substr($body, 0, $header_size);
$body = explode("\r\n", $body);
try {
$matches = array_values(preg_grep('/Link/', $body));
if (!empty($matches) && strpos($matches[0], '>; rel="next')) {
$link = explode(":", $matches[0], 2);
$start = strripos($link[1], 'page_info=');
$end = strripos($link[1], '>; rel="next', $start + 10);
$length = $end - $start;
$result = substr($link[1], $start + 10, $length - 10);
}
$count = count($body) - 1;
$body = json_decode($body[$count], true);
} catch (\Exception $e) {
$body = [];
}
if (!empty($body) && gettype($body) != 'integer' && gettype($body) != 'boolean') {
$response = array_merge(['response_code' => $code], $body);
if (!empty($result)) {
$response['link'] = $result;
}
} else {
$response = [ 'response_code' => $code ];
}
// Register response.
return $response;
}
This will set fetched Access Token into $this->accessToken variable which can be further used to manipulate Sylius Store Data with APIs.
NOTE – The older version of PHP will result in installing older version of Sylius.
Thanks for reading me. I hope this blog would help you with a better understanding of the Sylius Installation and getting Access Token. Please share your reviews on this, which will support me to write more.
Until next time. 👋