Gets the OAuth bearer token, using cURL

@return string The OAuth bearer token
@throws \Exception
344738
protected function _oauth2TokenCurl()
  {
    if (self::$_consumer_key === null) {
      throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
    }
    $post_fields = [
      'grant_type' => 'client_credentials'
    ];
    $url        = self::$_endpoints['oauth'] . 'oauth2/token';
    $connection = $this->_getCurlInitialization($url);
    $this->_curl_setopt($connection, CURLOPT_POST, 1);
    $this->_curl_setopt($connection, CURLOPT_POSTFIELDS, $post_fields);

    $this->_curl_setopt($connection, CURLOPT_USERPWD, self::$_consumer_key . ':' . self::$_consumer_secret);
    $this->_curl_setopt($connection, CURLOPT_HTTPHEADER, [
      'Expect:'
    ]);
    $result = $this->_curl_exec($connection);

    // catch request errors
    if ($result === false) {
      throw new CodebirdAuthException('Request error for bearer token: ' . $this->_curl_error($connection));
    }

    // certificate validation results
    $validation_result = $this->_curl_errno($connection);
    $this->_validateSslCertificate($validation_result);

    $httpstatus = $this->_curl_getinfo($connection, CURLINFO_HTTP_CODE);
    $reply = $this->_parseBearerReply($result, $httpstatus);
    return $reply;
  }
920028
public function getAccessToken()
    {
        return $this->requestHandler->sendRequestAsync('POST', 'api/v4/oauth/access_token/')->then(
            function ($tokenValues) {
                parse_str($tokenValues, $tokenArray);
                $token = $tokenArray['oauth_token'];
                $tokenSecret = $tokenArray['oauth_token_secret'];
                $this->requestHandler->setAccessTokenCredentials($token, $tokenSecret);
                return $tokenArray;
            }
        );
    }
532094
public function getTokenForRequest()
    {
        if (!$this->jwt->isHealthy() && $this->request->headers->has('Authorization')) {
          list($jwt_token) = sscanf( $this->request->headers->get('Authorization'), 'Bearer %s');
          $this->jwt->setToken($jwt_token);
        }

        return $this->jwt->getToken();
    }
789691
protected function get_curl_obj()
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->curl_ssl_verify_peer);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this->curl_ssl_verify_host);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connect_timeout);

        if ($this->debug) {
            curl_setopt($ch, CURLOPT_VERBOSE, true);
        }

        if ($this->cookies != '') {
            curl_setopt($ch, CURLOPT_COOKIESESSION, true);
            curl_setopt($ch, CURLOPT_COOKIE, $this->cookies);
        }

        return $ch;
    }
1287924
static public function getToken()
    {
        if ( self::$token === null )
        {
            self::$token = sha1( self::getSecret() . self::getIntention() . session_id() );
        }

        return self::$token;
    }
786812
protected function _oauth2TokenNoCurl()
  {
    if (self::$_consumer_key == null) {
      throw new CodebirdCredentialsException('To obtain a bearer token, the consumer key must be set.');
    }

    $url      = self::$_endpoints['oauth'] . 'oauth2/token';
    $hostname = parse_url($url, PHP_URL_HOST);

    if ($hostname === false) {
      throw new CodebirdEndpointException('Incorrect API endpoint host.');
    }

    $contextOptions = [
      'http' => [
        'method'           => 'POST',
        'protocol_version' => '1.1',
        'header'           => "Accept: */*\r\n"
          . 'Authorization: Basic '
          . base64_encode(
            self::$_consumer_key
            . ':'
            . self::$_consumer_secret
          ),
        'timeout'          => $this->_timeouts['request'] / 1000,
        'content'          => 'grant_type=client_credentials',
        'ignore_errors'    => true
      ]
    ];
    list($reply, $headers) = $this->_getNoCurlInitialization($url, $contextOptions, $hostname);
    $result  = '';
    foreach ($headers as $header) {
      $result .= $header . "\r\n";
    }
    $result .= "\r\n" . $reply;

    // find HTTP status
    $httpstatus = $this->_getHttpStatusFromHeaders($headers);
    $reply      = $this->_parseBearerReply($result, $httpstatus);
    return $reply;
  }
1244078
protected function requestAuthorizationToken(): string
    {
        $result = $this->options->getAuthorizationToken();
        if ($result === '') {
            $authRequest = new AuthRequest();
            $authRequest->setAgent($this->options->getAgent())
                        ->setAccessKey($this->options->getAccessKey())
                        ->setEnabledModNames($this->options->getEnabledModNames());

            $authResponse = $this->fetchResponse($authRequest);
            if ($authResponse instanceof AuthResponse) {
                $result = $authResponse->getAuthorizationToken();
                $this->options->setAuthorizationToken($result);
            }
        }
        return $result;
    }
48102
public function token()
    {
        try {
            $response = $this->oauthServer->respondToAccessTokenRequest($this->request, new Response());

            $this->pruneTokens();

            return $response;
        } catch (\Exception $e) {
            // Rethrow the exception
            throw $e;
        }
    }
673547
private function acquireToken()
    {
        // Request the token
        $client = new Client(); //GuzzleHttp\Client

        try {
            $response = $client->post($this->token_endpoint, [
                'form_params' => $this->getOauthFields(),
                'curl' => $this->setOauthCurlopts(),
                'synchronous' => true,
            ]);

            // Get the token and type from the response
            $body = $this->parseTokenResponse($response);

        } catch (\GuzzleException $e) {
            return false;
        }

        return $body;
    }
380915
public function getAuthorizeUrl () {
		return sprintf('%s%s?%s', $this->host, $this->authorizePath, http_build_query([
			'response_type'			=> $this->code ?? static::RESPONSE_TYPE_CODE,
			'client_id'				=> $this->clientId,
			'redirect_uri'			=> $this->redirectUri,
			'scope'					=> implode(' ', (array) $this->scope),
			'state'					=> $this->state,
			'code_challenge'		=> $this->codeChallenge,
			'code_challenge_method'	=> $this->codeChallengeMethod ?? static::CODE_CHALLENGE_METHOD_SHA256,
		]));
	}
780641
public function getAuthToken()
    {
        if(!isset($this->__token))
        {
            $token   = false;
            $request = $this->getObject('request');

            if($request->headers->has('Authorization'))
            {
                $header = $request->headers->get('Authorization');

                if(stripos($header, 'jwt') === 0) {
                    $token = substr($header , 4);
                }
            }

            if($request->isSafe())
            {
                if($request->query->has('auth_token')) {
                    $token = $request->query->get('auth_token', 'url');
                }
            }
            else
            {
                if($request->data->has('auth_token')) {
                    $token = $request->data->get('auth_token', 'url');
                }
            }

            if($token) {
                $token = $this->getObject('lib:http.token')->fromString($token);
            }

            $this->__token = $token;
        }

        return $this->__token;
    }
1194206
protected function requestAccessToken() {
        $code = $this->getRequestVar('code');
        if (!empty($code)) {
            $res = $this->sendRequest('POST', $this->getUrl('oauth', 'token'), array(
                'code' => $code,
                'client_id' => $this->getClientId(),
                'client_secret' => $this->getClientSecret(),
                'grant_type' => 'authorization_code',
                'redirect_uri' => $this->redirectUri,
            ));
            $result = $res->getBody();
            if ($result && $result = json_decode($result, true)) {
                if (!empty($result['error'])) {
                    throw new Exception($result['error_description']);
                }

                return $result;
            }
        }
        return null;
    }
1246663
protected function getAuthorizationHeader()
    {
        if (empty($this->apiKeyHeader) || empty($this->apiKey)) {
            throw new \Exception('API key is not set.');
        }

        return [$this->apiKeyHeader => $this->apiKey];
    }
104890
public function getToken(): string
    {
        return $this->cache->remember($this->tokenKey, $this->tokenTTL, function () {
            return $this->fetchToken();
        });
    }
825835
public function getTokenFromServer()
    {
        $params = ['appid' => Yii::$app->wechat->appId, 'secret' => Yii::$app->wechat->appSecret, 'grant_type' => 'client_credential',];
        $response = $this->getHttpClient()->createRequest()
            ->setUrl(self::API_TOKEN_GET)
            ->setMethod('GET')
            ->setData($params)
            ->send();

        if (!$response->isOk || empty($response->data[$this->tokenJsonKey])) {
            throw new Exception('Request AccessToken fail. response: ' . $response->content, $response->statusCode);
        }
        return $response->data;
    }
1125964
public function getTwitterAccessToken()
    {
        $consumer_key    = urlencode($this->args['api_user']);
        $consumer_secret = urlencode($this->args['api_secret']);

        // Concatenate key and secret and base64 encode
        $bearer_token = $consumer_key . ':' . $consumer_secret;
        $base64_bearer_token = base64_encode($bearer_token);

        // Request access token
        $endpoint = 'https://api.twitter.com/oauth2/token';

        // Request headers
        $headers = array(
            "POST /oauth2/token HTTP/1.1",
            "Host: api.twitter.com",
            "User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
            "Authorization: Basic " . $base64_bearer_token,
            "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
        );

        // Postdata
        $data = array(
            'grant_type' => 'client_credentials'
        );

        // Curl and format response
        $curl = new \Modularity\Helper\Curl();
        $response = $curl->request('POST', $endpoint, $data, null, $headers);
        $response = json_decode($response);

        if (isset($response->errors)) {
            return $response;
        }

        return $response->access_token;
    }
1190538
protected function doCurl()
    {
        $response = curl_exec($this->curl);

        if (curl_errno($this->curl)) {
            throw new \Exception(curl_error($this->curl), 1);
        }

        $curlInfo = curl_getinfo($this->curl);

        $results = array(
            'curl_info' => $curlInfo,
            'response' => $response,
        );

        return $results;
    }