src/Infrastructure/Service/AppleHelper.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Infrastructure\Service;
  3. use Firebase\JWT\JWT;
  4. use GuzzleHttp\Client;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\Routing\RouterInterface;
  7. class AppleHelper
  8. {
  9.     private ?string $secret;
  10.     private ?string $appId;
  11.     private ?string $signInId;
  12.     private ?string $privateKey;
  13.     private ?string $keyId;
  14.     private RouterInterface $router;
  15.     private const APPLE_LOGIN_URL 'https://appleid.apple.com/auth/authorize';
  16.     public function __construct(RouterInterface $routerContainerInterface $container)
  17.     {
  18.         $this->secret $_ENV['APPLE_SHARED_SECRET'];
  19.         $this->appId $_ENV['APPLE_APP_ID'];
  20.         $this->signInId $_ENV['APPLE_SIGN_IN_ID'];
  21.         $this->privateKey file_get_contents($container->getParameter('kernel.project_dir').'/var/resources/apple_private_key.txt');
  22.         $this->keyId $_ENV['APPLE_KEY_ID'];
  23.         $this->router $router;
  24.     }
  25.     public function generateLoginLink()
  26.     {
  27.         return self::APPLE_LOGIN_URL.'?'.http_build_query(
  28.             [
  29.                 'response_type' => 'code',
  30.                 'response_mode' => 'form_post',
  31.                 'client_id' => $this->signInId,
  32.                 'scope' => 'email',
  33.             ]
  34.         ).'&redirect_uri='.$_ENV['APP_HOST'].$this->router->generate('site_apple_sign_in');
  35.     }
  36.     public function getIdentityToken(string $authCode)
  37.     {
  38.         $client = new Client();
  39.         $headers = ['Content-Type' => 'application/x-www-form-urlencoded'];
  40.         $body = [
  41.             'code' => $authCode,
  42.             'client_id' => $this->signInId,
  43.             'client_secret' => $this->createClientSecret(),
  44.             'grant_type' => 'authorization_code',
  45.         ];
  46.         $response $client->request('POST''https://appleid.apple.com/auth/token', [
  47.             'headers' => $headers,
  48.             'form_params' => $body,
  49.         ]);
  50.         return json_decode($response->getBody()->getContents(), true)['id_token'];
  51.     }
  52.     private function createClientSecret()
  53.     {
  54.         return JWT::encode(
  55.             [
  56.                 'iss' => '286VD7A6CN',
  57.                 'iat' => time(),
  58.                 'exp' => time() + 3600,
  59.                 'aud' => 'https://appleid.apple.com',
  60.                 'sub' => $this->signInId,
  61.             ],
  62.             $this->privateKey,
  63.             'ES256'
  64.         );
  65.     }
  66. }