Completed
Pull Request — master (#572)
by Frédéric
01:32
created

Docusign::parseAccessTokenResponse()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.8497
c 0
b 0
f 0
cc 6
nc 5
nop 1
1
<?php
2
3
namespace OAuth\OAuth2\Service;
4
5
use OAuth\OAuth2\Token\StdOAuth2Token;
6
use OAuth\Common\Http\Exception\TokenResponseException;
7
use OAuth\Common\Http\Uri\Uri;
8
use OAuth\Common\Consumer\CredentialsInterface;
9
use OAuth\Common\Http\Client\ClientInterface;
10
use OAuth\Common\Storage\TokenStorageInterface;
11
use OAuth\Common\Http\Uri\UriInterface;
12
use OAuth\OAuth2\Service\Exception\MissingRefreshTokenException;
13
use OAuth\Common\Token\TokenInterface;
14
15
/**
16
 * Docusign service.
17
 *
18
 * @author Naveen Gopala <[email protected]>
19
 * @link https://images-na.ssl-images-docusign.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf
20
 */
21
class Docusign extends AbstractService
22
{
23
    /**
24
     * Defined scopes
25
     * @link https://images-na.ssl-images-docusign.com/images/G/01/lwa/dev/docs/website-developer-guide._TTH_.pdf
26
     */
27
    const SCOPE_SIGNATURE = 'signature';
28
29
    /**
30
     * @param CredentialsInterface  $credentials    credentials
31
     * @param ClientInterface       $httpClient     httpclient
32
     * @param TokenStorageInterface $storage        storage
33
     * @param array                 $scopes         scopes
34
     * @param UriInterface          $baseApiUri     base api uri
35
     */
36
    public function __construct(
37
        CredentialsInterface $credentials,
38
        ClientInterface $httpClient,
39
        TokenStorageInterface $storage,
40
        $scopes = array(),
41
        UriInterface $baseApiUri = null
42
    ) {
43
        parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri);
44
45
        if (null === $baseApiUri) {
46
            // account-d.docusign.com for the developer sandbox
47
            // account.docusign.com for the production platform.
48
            $this->baseApiUri = new Uri('https://account-d.docusign.com');
49
        }
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getAuthorizationUri(array $additionalParameters = array())
56
    {
57
        $parameters = array_merge(
58
            $additionalParameters,
59
            array(
60
                'client_id'     => $this->credentials->getConsumerId(),
61
                'redirect_uri'  => $this->credentials->getCallbackUrl(),
62
                'response_type' => 'code',
63
            )
64
        );
65
66
        $parameters['scope'] = implode(' ', $this->scopes);
67
68
        // Build the url
69
        $url = clone $this->getAuthorizationEndpoint();
70
        foreach ($parameters as $key => $val) {
71
            $url->addToQuery($key, $val);
72
        }
73
74
        return $url;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getAuthorizationEndpoint()
81
    {
82
        return new Uri('https://account-d.docusign.com/oauth/auth');
83
    }
84
85
    /**
86
     * {@inheritdoc}
87
     */
88
    public function getAccessTokenEndpoint()
89
    {
90
        return new Uri('https://account-d.docusign.com/oauth/token');
91
    }
92
93
    /**
94
     * {@inheritdoc}
95
     */
96
    protected function getAuthorizationMethod()
97
    {
98
        return static::AUTHORIZATION_METHOD_HEADER_BEARER;
99
    }
100
101
    /**
102
     * {@inheritdoc}
103
     */
104
    protected function parseAccessTokenResponse($responseBody)
105
    {
106
        $data = json_decode($responseBody, true);
107
108
        if (null === $data || !is_array($data)) {
109
            throw new TokenResponseException('Unable to parse response.');
110
        } elseif (isset($data['error_description'])) {
111
            throw new TokenResponseException('Error in retrieving token: "' . $data['error_description'] . '"');
112
        } elseif (isset($data['error'])) {
113
            throw new TokenResponseException('Error in retrieving token: "' . $data['error'] . '"');
114
        }
115
116
        $token = new StdOAuth2Token();
117
        $token->setAccessToken($data['access_token']);
118
        $token->setLifeTime($data['expires_in']);
119
120
        if (isset($data['refresh_token'])) {
121
            $token->setRefreshToken($data['refresh_token']);
122
            unset($data['refresh_token']);
123
        }
124
125
        unset($data['access_token']);
126
        unset($data['expires_in']);
127
128
        $token->setExtraParams($data);
129
130
        return $token;
131
    }
132
133
    /**
134
     * Docusign use a different endpoint for refresh a token
135
     *
136
     * {@inheritdoc}
137
     */
138
    public function refreshAccessToken(TokenInterface $token)
139
    {
140
        $refreshToken = $token->getRefreshToken();
141
142
        if (empty($refreshToken)) {
143
            throw new MissingRefreshTokenException();
144
        }
145
146
        $parameters = array(
147
            'grant_type'    => 'refresh_token',
148
            'type'          => 'web_server',
149
            'client_id'     => $this->credentials->getConsumerId(),
150
            'client_secret' => $this->credentials->getConsumerSecret(),
151
            'refresh_token' => $refreshToken,
152
        );
153
154
        $responseBody = $this->httpClient->retrieveResponse(
155
            new Uri($this->baseApiUri.'/oauth/token'),
156
            $parameters,
157
            $this->getExtraOAuthHeaders()
158
        );
159
        $token = $this->parseAccessTokenResponse($responseBody);
160
        $this->storage->storeAccessToken($this->service(), $token);
161
162
        return $token;
163
    }
164
165
}
166