1<?php
2
3namespace OAuth\OAuth2\Service;
4
5use OAuth\OAuth2\Token\StdOAuth2Token;
6use OAuth\Common\Http\Exception\TokenResponseException;
7use OAuth\Common\Http\Uri\Uri;
8use OAuth\Common\Consumer\CredentialsInterface;
9use OAuth\Common\Http\Client\ClientInterface;
10use OAuth\Common\Storage\TokenStorageInterface;
11use OAuth\Common\Http\Uri\UriInterface;
12
13/**
14 * Amazon service.
15 *
16 * @author Flávio Heleno <flaviohbatista@gmail.com>
17 * @link https://images-na.ssl-images-amazon.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf
18 */
19class Amazon extends AbstractService
20{
21    /**
22     * Defined scopes
23     * @link https://images-na.ssl-images-amazon.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf
24     */
25    const SCOPE_PROFILE     = 'profile';
26    const SCOPE_POSTAL_CODE = 'postal_code';
27
28    public function __construct(
29        CredentialsInterface $credentials,
30        ClientInterface $httpClient,
31        TokenStorageInterface $storage,
32        $scopes = array(),
33        UriInterface $baseApiUri = null
34    ) {
35        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);
36
37        if (null === $baseApiUri) {
38            $this->baseApiUri = new Uri('https://api.amazon.com/');
39        }
40    }
41
42    /**
43     * {@inheritdoc}
44     */
45    public function getAuthorizationEndpoint()
46    {
47        return new Uri('https://www.amazon.com/ap/oa');
48    }
49
50    /**
51     * {@inheritdoc}
52     */
53    public function getAccessTokenEndpoint()
54    {
55        return new Uri('https://www.amazon.com/ap/oatoken');
56    }
57
58    /**
59     * {@inheritdoc}
60     */
61    protected function getAuthorizationMethod()
62    {
63        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
64    }
65
66    /**
67     * {@inheritdoc}
68     */
69    protected function parseAccessTokenResponse($responseBody)
70    {
71        $data = json_decode($responseBody, true);
72
73        if (null === $data || !is_array($data)) {
74            throw new TokenResponseException('Unable to parse response.');
75        } elseif (isset($data['error_description'])) {
76            throw new TokenResponseException('Error in retrieving token: "' . $data['error_description'] . '"');
77        } elseif (isset($data['error'])) {
78            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
79        }
80
81        $token = new StdOAuth2Token();
82        $token->setAccessToken($data['access_token']);
83        $token->setLifeTime($data['expires_in']);
84
85        if (isset($data['refresh_token'])) {
86            $token->setRefreshToken($data['refresh_token']);
87            unset($data['refresh_token']);
88        }
89
90        unset($data['access_token']);
91        unset($data['expires_in']);
92
93        $token->setExtraParams($data);
94
95        return $token;
96    }
97}
98