Upgrade a authorization token from oauth 2.0 to an access token

@param string $code the code returned from the oauth authenticaiton
@return boolean true if token is upgraded succesfully
431711
public function upgrade_token($code) {
        $callbackurl = self::callback_url();
        $params = array('code' => $code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $callbackurl->out(false),
        );

        if ($this->basicauth) {
            $idsecret = urlencode($this->clientid) . ':' . urlencode($this->clientsecret);
            $this->setHeader('Authorization: Basic ' . base64_encode($idsecret));
        } else {
            $params['client_id'] = $this->clientid;
            $params['client_secret'] = $this->clientsecret;
        }

        // Requests can either use http GET or POST.
        if ($this->use_http_get()) {
            $response = $this->get($this->token_url(), $params);
        } else {
            $response = $this->post($this->token_url(), $this->build_post_data($params));
        }

        if ($this->info['http_code'] !== 200) {
            throw new moodle_exception('Could not upgrade oauth token');
        }

        $r = json_decode($response);

        if (is_null($r)) {
            throw new moodle_exception("Could not decode JSON token response");
        }

        if (!empty($r->error)) {
            throw new moodle_exception($r->error . ' ' . $r->error_description);
        }

        if (!isset($r->access_token)) {
            return false;
        }

        if (isset($r->refresh_token)) {
            $this->refreshtoken = $r->refresh_token;
        }

        // Store the token an expiry time.
        $accesstoken = new stdClass;
        $accesstoken->token = $r->access_token;
        if (isset($r->expires_in)) {
            // Expires 10 seconds before actual expiry.
            $accesstoken->expires = (time() + ($r->expires_in - 10));
        }
        $accesstoken->scope = $this->scope;
        // Also add the scopes.
        self::$upgradedcodes[] = $code;
        $this->store_token($accesstoken);

        return true;
    }
599912
public function getTokenForCode($code, $state)
    {
        if ($state != $_SESSION['oauth2_lockme_state']) {
            unset($_SESSION['oauth2_lockme_state']);
            throw new \Exception("Wrong state");
        }
        unset($_SESSION['oauth2_lockme_state']);

        $this->accessToken = $this->provider->getAccessToken('authorization_code', [
        'code' => $code
    ]);
        return $this->accessToken;
    }
857227
public function getAccessToken($code, $state = null, $redirectUri = null)
    {
        // No state provided
        // Should probably be
        // handled explicitly
        if (!is_null($state)) {
            //Decode the State
            $state = $this->decodeState($state);

            //CSRF Token
            $csrfToken = $state['csrfToken'];

            //Set the URL State
            $this->urlState = $state['urlState'];

            //Validate CSRF Token
            $this->validateCSRFToken($csrfToken);
        }

        //Fetch Access Token
        $accessToken = $this->getOAuth2Client()->getAccessToken($code, $redirectUri);

        //Make and return the model
        return new AccessToken($accessToken);
    }
1173698
public function authenticate($code)
    {
        if ( $code )
        {
            $this->client->authenticate($code);

            $access_token = $this->client->getAccessToken();

            $this->session->put('googleapi_token', $access_token);

            return true;
        }

        return false;
    }
615123
protected function getAuthCode($code)
    {
        if (null === $code = $this->app['repo.api-oauth-codes']->find($code)) {
            return null;
        }

        return [
            'redirect_uri' => $code->getRedirectUri(),
            'client_id'    => $code->getAccount()->getApplication()->getClientId(),
            'expires'      => $code->getExpires(),
            'account_id'   => $code->getAccount()->getId(),
        ];
    }
161862
private function getAccessToken($code)
    {

        $data        = [
            "client_id"     => $this->clientId,
            "client_secret" => $this->clientSecret,
            "code"          => $code
        ];
        $data_string = json_encode($data);

        //This needs to be replaced with Guzzle or something async
        $ch = curl_init('https://github.com/login/oauth/access_token');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            [
                'Content-Type: application/json',
                'Content-Length: ' . strlen($data_string)
            ]
        );

        $result = curl_exec($ch);
        parse_str($result, $resultArray);

        if (isset($resultArray['access_token'])) {
            return $resultArray['access_token'];
        } else {
            return false;
        }
    }
125944
public function getAuthorizationCode($code)
    {
        if (!isset($this->authorizationCodes[$code])) {
            return false;
        }

        return array_merge(array(
            'authorization_code' => $code,
        ), $this->authorizationCodes[$code]);
    }
1163322
public function getAuthorizationCode($code)
	{
		// auth model
		$authorizationCode = \Components\Developer\Models\Authorizationcode::oneByCode($code);

		// fetch by code
		if (!$authorizationCode->get('id'))
		{
			return false;
		}

		// get the application's client id
		$application = \Components\Developer\Models\Application::oneOrFail($authorizationCode->get('application_id'));
		$authorizationCode->set('client_id', $application->get('client_id'));

		// format expires to unix timestamp for authorization code grant type
		$authorizationCode->set('expires', with(new Date($authorizationCode->get('expires')))->toUnix());

		// return code
		return $authorizationCode->toArray();
	}
1033245
public function confirmByCode($code)
    {
        $identity = ['confirmation_code' => $code];

        $account = $this->findByIdentity($identity);

        if($account){

            return $this->confirm($account);
        } else{

            return false;
        }
    }
304090
public function getAccessTokenResponse(string $code)
    {
        $response = $this->getHttpClient()->post($this->getTokenUrl(), [
            'headers' => ['Accept' => 'application/json'],
            'form_params' => $this->getTokenFields($code),
        ]);
        return json_decode($response->getBody(), true);
    }
524197
public function getOauth2AccessToken($code, $grantType = 'authorization_code')
    {
        $result = $this->httpGet(self::WECHAT_OAUTH2_ACCESS_TOKEN_PREFIX, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'code' => $code,
            'grant_type' => $grantType
        ]);
        return !array_key_exists('errcode', $result) ? $result : false;
    }
660137
public function getAuthorizationCode($code)
    {
        if (isset($this->authorizationCodes[$code])) {
            return $this->authorizationCodes[$code];
        }

        return null;
    }
1016712
public function getAccessToken($code)
    {
        $postKey = (version_compare(ClientInterface::VERSION, '6') === 1) ? 'form_params' : 'body';

        $response = $this->getHttpClient()->post($this->getTokenUrl(), [
            $postKey => $this->getTokenFields($code),
        ]);

        return $this->parseAccessToken($response->getBody());
    }
444142
public function authenticate($authorizationCode)
    {
        $tokens = $this->client->requestTokens(
            $authorizationCode,
            $this->clientId,
            $this->clientSecret,
            $this->redirectUrl
        );

        $this->accessToken = $tokens->access_token;
        $this->refreshToken = $tokens->refresh_token;
        $this->expires = $tokens->expires_at;

        $this->client->authenticate($this->accessToken);
    }
1154434
public function authenticate($code)
    {
        if (empty($code)) {
            throw new NostoException('Invalid authentication token');
        }

        $request = new HttpRequest();
        $request->setUrl(Nosto::getOAuthBaseUrl() . self::PATH_TOKEN);
        $request->setReplaceParams(
            array(
                '{cid}' => $this->clientId,
                '{sec}' => $this->clientSecret,
                '{uri}' => $this->redirectUrl,
                '{cod}' => $code
            )
        );
        $response = $request->get();
        $result = $response->getJsonResult(true);

        if ($response->getCode() !== 200) {
            throw ExceptionBuilder::fromHttpRequestAndResponse($request, $response);
        }
        if (empty($result['access_token'])) {
            throw new NostoException('No "access_token" returned after authenticating with code');
        }
        if (empty($result['merchant_name'])) {
            throw new NostoException('No "merchant_name" returned after authenticating with code');
        }

        return NostoOAuthToken::create($result);
    }
53499
public function confirm($code = '')
    {
        if (!$this->confirmationAttribute || !$this->validateConfirmationCode($code)) {
            return false;
        }
        $this->confirmation = static::$confirmTrue;
        return $this->save();
    }
265586
public function acquireAccessToken($code)
    {
        if (! $this->credentials) {

            $this->credentials = new Credentials('authorization_code');

            // Get API endpoints
            $this->endpointDiscovery();

            // Acquire the tokens and expiration and save
            $body = $this->acquireToken($code);
            $this->credentials->set($body);

            // Get user Info
            $userInfo = $this->acquireUserInfo();
            $this->credentials->set('userInfo', $userInfo);

            // Add credentials to the session
            $creds = serialize($this->credentials);
            Session::put('creds', $creds);
        }

        return $this;
    }