<?php
namespace App\Infrastructure\Service;
use Firebase\JWT\JWT;
use GuzzleHttp\Client;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\RouterInterface;
class AppleHelper
{
private ?string $secret;
private ?string $appId;
private ?string $signInId;
private ?string $privateKey;
private ?string $keyId;
private RouterInterface $router;
private const APPLE_LOGIN_URL = 'https://appleid.apple.com/auth/authorize';
public function __construct(RouterInterface $router, ContainerInterface $container)
{
$this->secret = $_ENV['APPLE_SHARED_SECRET'];
$this->appId = $_ENV['APPLE_APP_ID'];
$this->signInId = $_ENV['APPLE_SIGN_IN_ID'];
$this->privateKey = file_get_contents($container->getParameter('kernel.project_dir').'/var/resources/apple_private_key.txt');
$this->keyId = $_ENV['APPLE_KEY_ID'];
$this->router = $router;
}
public function generateLoginLink()
{
return self::APPLE_LOGIN_URL.'?'.http_build_query(
[
'response_type' => 'code',
'response_mode' => 'form_post',
'client_id' => $this->signInId,
'scope' => 'email',
]
).'&redirect_uri='.$_ENV['APP_HOST'].$this->router->generate('site_apple_sign_in');
}
public function getIdentityToken(string $authCode)
{
$client = new Client();
$headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
$body = [
'code' => $authCode,
'client_id' => $this->signInId,
'client_secret' => $this->createClientSecret(),
'grant_type' => 'authorization_code',
];
$response = $client->request('POST', 'https://appleid.apple.com/auth/token', [
'headers' => $headers,
'form_params' => $body,
]);
return json_decode($response->getBody()->getContents(), true)['id_token'];
}
private function createClientSecret()
{
return JWT::encode(
[
'iss' => '286VD7A6CN',
'iat' => time(),
'exp' => time() + 3600,
'aud' => 'https://appleid.apple.com',
'sub' => $this->signInId,
],
$this->privateKey,
'ES256'
);
}
}