yii\authclient\OAuth2::fetchAccessToken PHP Method

fetchAccessToken() public method

Fetches access token from authorization code.
public fetchAccessToken ( string $authCode, array $params = [] ) : OAuthToken
$authCode string authorization code, usually comes at $_GET['code'].
$params array additional request params.
return OAuthToken access token.
    public function fetchAccessToken($authCode, array $params = [])
    {
        if ($this->validateAuthState) {
            $authState = $this->getState('authState');
            if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) {
                throw new HttpException(400, 'Invalid auth state parameter.');
            } else {
                $this->removeState('authState');
            }
        }
        $defaultParams = ['client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'code' => $authCode, 'grant_type' => 'authorization_code', 'redirect_uri' => $this->getReturnUrl()];
        $request = $this->createRequest()->setMethod('POST')->setUrl($this->tokenUrl)->setData(array_merge($defaultParams, $params));
        $response = $this->sendRequest($request);
        $token = $this->createToken(['params' => $response]);
        $this->setAccessToken($token);
        return $token;
    }

Usage Example

 /**
  * @inheritdoc
  */
 public function fetchAccessToken($authCode, array $params = [])
 {
     $authState = $this->getState('authState');
     if (!isset($_REQUEST['state']) || empty($authState) || strcmp($_REQUEST['state'], $authState) !== 0) {
         throw new HttpException(400, 'Invalid auth state parameter.');
     } else {
         $this->removeState('authState');
     }
     return parent::fetchAccessToken($authCode, $params);
 }
All Usage Examples Of yii\authclient\OAuth2::fetchAccessToken