Pay an order.

@author yansongda <me@yansongda.cn>

@param string $endpoint
@param array  $payload

@throws GatewayException
@throws InvalidArgumentException
@throws InvalidSignException
@throws Exception

@return Response
338355
public function pay($endpoint, array $payload): Response
    {
        $payload['appid'] = Support::getInstance()->appid;
        $payload['trade_type'] = $this->getTradeType();

        if ($this->mode === Wechat::MODE_SERVICE) {
            $payload['sub_appid'] = Support::getInstance()->sub_appid;
        }

        $pay_request = [
            'appid'     => $this->mode === Wechat::MODE_SERVICE ? $payload['sub_appid'] : $payload['appid'],
            'partnerid' => $this->mode === Wechat::MODE_SERVICE ? $payload['sub_mch_id'] : $payload['mch_id'],
            'prepayid'  => $this->preOrder($payload)->get('prepay_id'),
            'timestamp' => strval(time()),
            'noncestr'  => Str::random(),
            'package'   => 'Sign=WXPay',
        ];
        $pay_request['sign'] = Support::generateSign($pay_request);

        Events::dispatch(Events::PAY_STARTED, new Events\PayStarted('Wechat', 'App', $endpoint, $pay_request));

        return JsonResponse::create($pay_request);
    }
52157
protected function sendRequest($endpoint, array $queryParams)
    {
        return $this->flexClient->sendRequest(
            $this->getApiName(),
            $this->getApiVersion(),
            $endpoint,
            $queryParams
        );
    }
332031
protected function request(string $method, string $endpoint, $json = null)
    {
        $uri = $this->buildUri($endpoint);
        $options = $json != null ? ['json' => $json] : [];

        try {
            $response = $this->client->request($method, $uri, $options);
        } catch (ClientException $exception) {
            throw $this->determineException($exception);
        }

        $body = (string) $response->getBody();

        return $this->jsonValidator($body) ? json_decode($body, true) : $body;
    }
634827
public function api($endpoint, array $params = [], $method = Method::GET)
    {
        $headers = $this->getApiHeaders();
        $options = $this->prepareOptions($params, $method);
        Method::isMethodSupported($method);
        if ($this->isUsingTokenParam()) {
            $params['oauth2_access_token'] = $this->accessToken->getToken();
        } else {
            $headers['Authorization'] = 'Bearer ' . $this->accessToken->getToken();
        }
        $guzzle = new GuzzleClient([
            'base_uri' => $this->getApiRoot(),
            'headers' => $headers,
        ]);
        if (!empty($params) && Method::GET === $method) {
            $endpoint .= '?' . build_query($params);
        }
        try {
            $response = $guzzle->request($method, $endpoint, $options);
        } catch (RequestException $requestException) {
            throw Exception::fromRequestException($requestException);
        }
        return self::responseToArray($response);
    }
400324
public function send(string $method, string $endpoint, array $parameters = null)
    {
        /** @var string|array $parameters */
        $data = $this->processor->prepare($method, $parameters);

        switch ($method) {
            case 'get':
                return $this->adapter->get(
                    $this->getEndpoint() . '/' . trim($endpoint, '/') . trim($data, '/')
                );
            case 'post':
                return $this->adapter->post(
                    $this->getEndpoint() . '/' . trim($endpoint, '/'),
                    $data ?? []
                );
        }
    }
771277
public function setEndpoint($endpoint)
    {
        if (!in_array($endpoint, [self::ENDPOINT_SANDBOX, self::ENDPOINT_PRODUCTION])) {
            throw new InvalidArgumentException('Endpoint inválido.');
        }

        $this->endpoint = $endpoint;

        return $this;
    }
347039
public function performApiRequest($endpoint, $payload)
    {
        $this->setupRequest($payload);
        $this->apiEndpoint = $endpoint;

        return $this->doDropboxApiRequest();
    }
1235133
public function pay($endpoint, array $payload): Collection
    {
        $payload['spbill_create_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
        $payload['trade_type'] = $this->getTradeType();

        return $this->preOrder('pay/unifiedorder', $payload);
    }
1031817
public function pay($endpoint, array $payload): Collection
    {
        $payload['wxappid'] = $payload['appid'];

        if (php_sapi_name() !== 'cli') {
            $payload['client_ip'] = Request::createFromGlobals()->server->get('SERVER_ADDR');
        }

        if ($this->mode === Wechat::MODE_SERVICE) {
            $payload['msgappid'] = $payload['appid'];
        }

        unset($payload['appid'], $payload['trade_type'],
              $payload['notify_url'], $payload['spbill_create_ip']);

        $payload['sign'] = Support::generateSign($payload);

        Events::dispatch(Events::PAY_STARTED, new Events\PayStarted('Wechat', 'Redpack', $endpoint, $payload));

        return Support::requestApi(
            'mmpaymkttransfers/sendredpack',
            $payload,
            true
        );
    }
154526
protected function doRequest($method, $endpoint, array $params = array(), $isVault = false)
    {
        if (empty($method) || !is_string($method)) {
            throw new InvalidArgumentException("HTTP METHOD must a string and a valid HTTP METHOD Value");
        }

        if (empty($endpoint) || !is_string($endpoint)) {
            throw new InvalidArgumentException("Endpoint must be a string and a valid api endpoint");
        }

        $credentials = $this->getConfiguration()->getApiUsername() . ':' . $this->getConfiguration()->getApiPassword();

        $url = $this->getConfiguration()->getApiEndpoint();

        if ($isVault) {
            $url = $this->getConfiguration()->getSecureVaultEndpoint();
        }

        $userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'HiPayFullservice/1.0 (SDK PHP)';
        $finalUrl = $url . $endpoint;

        // set appropriate options
        $options = array(
            CURLOPT_URL => $finalUrl,
            CURLOPT_USERPWD => $credentials,
            CURLOPT_HTTPHEADER => array(
                'Accept: ' . $this->getConfiguration()->getApiHTTPHeaderAccept(),
                'User-Agent: ' . $userAgent
            ),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FAILONERROR => false,
            CURLOPT_HEADER => false,
        );

        // add post parameters
        if (strtolower($method) == 'post') {
            $options[CURLOPT_POST] = true;
            $options[CURLOPT_POSTFIELDS] = http_build_query($params);
        } else {
            $options[CURLOPT_POST] = false;
        }

        $proxyConfiguration = $this->getConfiguration()->getProxy();

        if (!empty($proxyConfiguration)) {
            $options[CURLOPT_PROXY] = $proxyConfiguration["host"];
            $options[CURLOPT_PROXYPORT] = $proxyConfiguration["port"];
            $options[CURLOPT_PROXYUSERPWD] = $proxyConfiguration["user"] . ":" . $proxyConfiguration["password"];
        }

        /**
         * Send a new request
         * $method can be any valid HTTP METHOD (GET, POST etc ...)
         * $uri The url/endpoint to request
         * $options Needed configuration
         */
        foreach ($options as $option => $value) {
            curl_setopt($this->_httpClient, $option, $value);
        }

        // execute the given cURL session
        if (false === ($result = curl_exec($this->_httpClient))) {
            throw new CurlException(curl_error($this->_httpClient), curl_errno($this->_httpClient));
        }

        $body = $result;

        $status = (int)curl_getinfo($this->_httpClient, CURLINFO_HTTP_CODE);
        $httpResponse = json_decode($body);

        if (floor($status / 100) != 2) {
            if (is_object($httpResponse) && isset($httpResponse->message, $httpResponse->code)) {
                $description = (isset($httpResponse->description)) ? $httpResponse->description : "";
                throw new ApiErrorException($httpResponse->message, $httpResponse->code, $description);
            } else {
                throw new HttpErrorException($body, $status);
            }
        }

        //Return a simple response object
        return new Response((string)$body, $status, array('Content-Type' => array('application/json; encoding=UTF-8')));
    }
1187238
public function post(
        string $endpoint,
        array $options
    )
    {
        $this->streamBody = $this->client
            ->post($endpoint, $options)
            ->getBody();
    }
304033
public function setAuthorizationEndpoint($endpoint)
    {
        if (!in_array($endpoint, [self::ENDPOINT_AUTHENTICATE, self::ENDPOINT_AUTHORIZE])) {
            throw new Exception(
                sprintf("'%s' is not a correct Twitter authorization endpoint.", $endpoint)
            );
        }

        $this->authorizationEndpoint = $endpoint;

        return $this;
    }
259473
public function get(string $endPoint)
    {
        $parsedEndPoint = self::parseEndPoint($endPoint);
        return $this->sendRequest($parsedEndPoint, "GET");
    }
753228
public function sendRequest($endpoint, $httpMethod, Payload $payload = null)
    {
        self::validateHttpMethod($httpMethod);

        $signedDataArr = RequestSigner::signRequest($this, $endpoint, $httpMethod, $payload);
        $requestHeaders = $this->generateRequestHeaders($signedDataArr[RequestSigner::SIGNED_MESSAGE_KEY]);
        $requestUrl = $this->connectApiUrl . $signedDataArr[RequestSigner::END_POINT_PATH_KEY];

        return $this->executeRequest($requestHeaders, $requestUrl, $httpMethod, $payload);
    }
1028268
public function post($endpoint, array $options = [])
    {
        $jsonValues = [];

        if (isset($options['json'])) {
            $jsonValues = $options['json'];
        }

        return $this->httpClient->request('POST', 'https://api.craftcms.com/v1/'.$endpoint, [
            'auth' => $this->setAuth(),
            'json' => $jsonValues
        ]);
    }
522308
public function sendRequest(
        string $endpoint,
        array $queryString = []
    ) {
        $headers = [
            'Accept' => 'application/json',
        ];

        if ($this->getApiKey() !== null) {
            $headers['Authorization'] = base64_encode($this->getApiKey());
        }

        $curl = curl_init();

        $host = $this->isSafe === true
            ? self::BASE_SAFE_HOST
            : self::BASE_HOST;

        $requestPath = $host . $endpoint . '?' . http_build_query($queryString);

        if ($this->curlConfigurator !== null) {
            ($this->curlConfigurator)($curl);
        }

        curl_setopt($curl, CURLOPT_URL, $requestPath);
        curl_setopt($curl, CURLOPT_HTTPGET, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->convertArrayToCurlHeaders($headers));

        $response = curl_exec($curl);

        if (mb_strlen($curlError = curl_error($curl)) > 0) {
            throw new RuntimeException(sprintf(
                'cURL request error: %s',
                $curlError
            ));
        }

        curl_close($curl);

        return json_decode($response, true);
    }
386159
private function performPostRequest($payload)
	{
	    $payload[] = ['type' => $this->apiXType, 'routing' => $this->apiXRoute, 'token' => $this->apiXToken];
		$this->response = $this->client->request('POST', [
            'query' => $payload
        ]);
	}