Wraps the HTTP Client, creates a new PSR-7 request adding authentication, signatures, etc.

@param \Psr\Http\Message\RequestInterface $request

@return \Psr\Http\Message\ResponseInterface
546368
public function send(\Psr\Http\Message\RequestInterface $request)
    {
        if ($this->credentials instanceof Container) {
            if (strpos($request->getUri()->getPath(), '/v1/calls') === 0) {
                $request = $request->withHeader('Authorization', 'Bearer '.$this->credentials->get(Keypair::class)->generateJwt());
            } else {
                $request = self::authRequest($request, $this->credentials->get(Basic::class));
            }
        } elseif ($this->credentials instanceof Keypair) {
            $request = $request->withHeader('Authorization', 'Bearer '.$this->credentials->get(Keypair::class)->generateJwt());
        } elseif ($this->credentials instanceof SharedSecret) {
            $request = self::signRequest($request, $this->credentials);
        } elseif ($this->credentials instanceof Basic) {
            $request = self::authRequest($request, $this->credentials);
        }

        //todo: add oauth support

        //allow any part of the URI to be replaced with a simple search
        if (isset($this->options['url'])) {
            foreach ($this->options['url'] as $search => $replace) {
                $uri = (string) $request->getUri();

                $new = str_replace($search, $replace, $uri);
                if ($uri !== $new) {
                    $request = $request->withUri(new Uri($new));
                }
            }
        }

        $response = $this->client->sendRequest($request);

        return $response;
    }
1006845
public function getParsedResponse(RequestInterface $request)
    {
        try {
            $response = $this->getResponse($request);
        } catch (BadResponseException $e) {
            $response = $e->getResponse();
        }

        $parsed = $this->parseResponse($response);

        $this->checkResponse($response, $parsed);

        return $parsed;
    }
32417
protected function sendRequest(RequestInterface $request)
    {
        try {
            $response = $this->httpClient->send(
                $request,
                $this->getRequestOptions()
            );

            $this->multipartResources = [];

            return json_decode($response->getBody());
        } catch (RequestException $e) {
            $this->throwRequestException($e);
        }
    }
1199334
public function sendRequest(RequestInterface $request):ResponseInterface{
		$uri     = $request->getUri();
		$method  = $request->getMethod();
		$headers = $this->getRequestHeaders($request);

		$body    = \in_array($method, ['DELETE', 'PATCH', 'POST', 'PUT'], true)
			? $request->getBody()->getContents()
			: null;

		$context = \stream_context_create([
			'http' => [
				'method'           => $method,
				'header'           => $headers,
				'content'          => $body,
				'protocol_version' => '1.1',
				'user_agent'       => $this->options->user_agent,
				'max_redirects'    => 0,
				'timeout'          => 5,
			],
			'ssl' => [
				'cafile'              => $this->options->ca_info,
				'verify_peer'         => $this->options->ssl_verifypeer,
				'verify_depth'        => 3,
				'peer_name'           => $uri->getHost(),
				'ciphers'             => 'HIGH:!SSLv2:!SSLv3',
				'disable_compression' => true,
			],
		]);

		$requestUri = (string)$uri->withFragment('');

		\set_error_handler(function ($severity, $msg, $file, $line){
			throw new \ErrorException($msg, 0, $severity, $file, $line);
		});

		try{
			$responseBody    = \file_get_contents($requestUri, false, $context);
			$responseHeaders = $this->parseResponseHeaders(\get_headers($requestUri, 1, $context));
		}
		catch(\Exception $e){
			$this->logger->error('StreamClient error #'.$e->getCode().': '.$e->getMessage());

			throw new ClientException($e->getMessage(), $e->getCode());
		}

		\restore_error_handler();

		$response = $this->responseFactory
			->createResponse($responseHeaders['statuscode'], $responseHeaders['statustext'])
			->withProtocolVersion($responseHeaders['httpversion'])
		;

		$response->getBody()->write($responseBody);
		$response->getBody()->rewind();

		return $response;
	}
681150
public function transducer(RequestInterface $request)
    {
        $response = null;
        if (count($this->middleware)) {
            $md = array_pop($this->middleware);
            $next = function (RequestInterface $request) {
                return $this->transducer($request);
            };

            if (is_callable($md)) {
                $response = $md($request, $next);
            } elseif (is_array($md)) {
                list($class, $action) = $md;
                $instance = is_object($class) ? $class : new $class();
                $response = $instance->$action($request, $next);
            }

            if ($response instanceof Generator) {
                $response = Poroutine::resolve($response);
            }
        }

        return $response ?? new Response();
    }
792349
public function authenticate(RequestInterface $request)
    {
        $token = $this->token();

        if (!$token && !$this->findMatchingArea($request)) {
            return $this;
        }

        if (!$token) {
            throw new AuthenticationException('Unable to authenticate, token is missing');
        }

        foreach ($this->providers as $provider) {
            if (!$provider->supportsToken($token)) {
                continue;
            }

            if (!$provider->authenticate($token)) {
                $this->stash()
                     ->destroy();

                throw new AuthenticationException(sprintf('Token could not be authenticated in provider "%s", destroying token', get_class($provider)));
            }

            $this->user = $provider->get($token);

            return $this;
        }

        $this->stash()
             ->destroy();

        throw new AuthenticationException(sprintf('Missing provider supporting token "%s", destroying token', get_class($token)));
    }
1302191
protected function createUrl(RequestInterface $request)
    {
        $query = $request->buildQuery();

        if ($this->hasKey()) {
            $query['key'] = $this->key;
        }

        $url = $this->createBaseUrl($request).'?'.http_build_query($query, '', '&');

        if ($this->hasBusinessAccount()) {
            $url = $this->businessAccount->signUrl($url);
        }

        return $url;
    }
816292
protected function authenticateRequest(RequestInterface $request)
    {
        $uri = $request->getUri();
        parse_str($uri->getQuery(), $query);

        $query['key'] = Configuration::get('key');
        $query['token'] = Configuration::get('token');

        $uri = $uri->withQuery(http_build_query($query));

        return $request->withUri($uri);
    }
952685
public function build(RequestInterface $request): ResponseInterface
    {
        return $this->responseFactory->createResponse(
            $this->getMockStatusForRequest($request),
            '',
            $this->getMockHeadersForRequest($request),
            $this->getMockBodyForRequest($request)
        );
    }
9481
public function signRequest(
        RequestInterface $request,
        SigningSecretKey $secretKey
    ): RequestInterface {
        $signature = \ParagonIE_Sodium_Compat::crypto_sign_detached(
            (string) $request->getBody(),
            $secretKey->getString(true)
        );
        return $request->withAddedHeader(
            (string) static::HEADER_SIGNATURE_NAME,
            Base64UrlSafe::encode($signature)
        );
    }
512983
protected function createCurlHandle(RequestInterface $request)
    {
        $wrapper = CurlHandle::factory($request);
        $this->handles[$request] = $wrapper;
        $this->resourceHash[(int) $wrapper->getHandle()] = $request;

        return $wrapper;
    }
175100
protected function authentication(RequestInterface $request)
	{
		if ($this->tokenRequired)
		{
			return $request->withHeader('Authorization', sprintf('OAuth %s', $this->getAccessToken()));
		}

		return $request;
	}
67620
public function getTokenFromRequest( RequestInterface $request ) {
		if ( $request->get( $this->key ) ) {
			return $request->get( $this->key );
		}

		if ( $request->post( $this->key ) ) {
			return $request->post( $this->key );
		}

		if ( $request->headers( $this->header ) ) {
			return $request->headers( $this->header );
		}

		return '';
	}
1175444
private function setOAuthHeaders(RequestInterface $request): RequestInterface
    {
        $now = new \DateTime();
        if ($this->now instanceof \DateTime) {
            $now = clone $this->now;
        }

        //Generate HTTP headers
        $encodedKey = \rawurlencode($this->oauthConsumerSecret).'&'.\rawurlencode($this->oauthAccessTokenSecret);
        $oauthParams = [
            'oauth_consumer_key' => $this->oauthConsumerKey,
            'oauth_token' => $this->oauthAccessToken,
            'oauth_nonce' => \sha1(\microtime(true).\rand(10000, 99999)),
            'oauth_timestamp' => $now->getTimestamp(),
            'oauth_signature_method' => 'PLAINTEXT',
            'oauth_version' => '1.0',
            'oauth_signature' => $encodedKey,
        ];

        $request = $request->withHeader('Authorization', $this->encodeOAuthHeaders($oauthParams));

        return $request->withHeader('Expect', '');
    }
619393
public function issueToken(ServerRequestInterface $request)
    {
        $response = $this->withErrorHandling(function () use ($request) {
            $input = (array) $request->getParsedBody();
            $clientId = isset($input['client_id']) ? $input['client_id'] : null;

            // Overwrite password grant at the last minute to add support for customized TTLs
            $this->server->enableGrantType(
                $this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId)
            );

            return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
        });

        if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
            return $response;
        }

        $payload = json_decode($response->getBody()->__toString(), true);

        if (isset($payload['access_token'])) {
            $tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
            $token = $this->tokens->find($tokenId);

            if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
                // We keep previous tokens for password clients
            } else {
                $this->revokeOrDeleteAccessTokens($token, $tokenId);
            }
        }

        return $response;
    }
1242200
private function onBefore(RequestInterface $request)
    {
        $headers = $request->getHeaders();

        //prepare Header
        $headers["Date"] = gmdate($this->config['dateTimeFormat']);
        $headers["Accept"] = 'application/octet-stream';
        $headers["x-acs-signature-method"] = $this->config['signatureMethod'];
        $headers["x-acs-signature-version"] = $this->config['signatureVersion'];
        $headers['x-acs-version'] = $this->config['Version'];

        if (isset($this->config['regionId'])) {
            $headers["x-acs-region-id"] = $this->config['regionId'];
        }

        $content = $request->getBody()->getContents();
        if ($content != null) {
            $headers["Content-MD5"] = base64_encode(md5(json_encode($content), true));
        }
        $headers["Content-Type"] = "application/octet-stream;charset=utf-8";

        //compose Url

        $signString = $request->getMethod() . self::$headerSeparator;
        if (isset($headers["Accept"])) {
            $signString = $signString . $headers["Accept"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Content-MD5"])) {
            $signString = $signString . $headers["Content-MD5"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Content-Type"])) {
            $signString = $signString . $headers["Content-Type"];
        }
        $signString = $signString . self::$headerSeparator;

        if (isset($headers["Date"])) {
            $signString = $signString . $headers["Date"];
        }
        $signString = $signString . self::$headerSeparator;

        $params = \GuzzleHttp\Psr7\parse_query($request->getUri()->getQuery());
        $signString = $signString . $this->buildCanonicalHeaders($headers);
        ksort($params);//参数排序
        $query = \GuzzleHttp\Psr7\build_query($params);
        $signString .= $query;

        $headers["Authorization"] = "acs " . $this->config['accessKeyId'] . ":"
            . base64_encode(hash_hmac('sha1', $signString, $this->config['accessSecret'], true));

        /** @var RequestInterface $request */
        $request = $request->withUri($request->getUri()->withQuery($query));
        foreach ($headers as $name => $val) {
            $request->withHeader($name, $val);
        }
        return $request;
    }
371685
public function onRequest( RequestInterface $request ) {
        $schema = $this->getEndpoint()->getSchema();

        return $request->withHeader( 'X-Schema-Version', $schema );
    }