dolibarr/htdocs/includes/stripe/stripe-php/lib/ApiRequestor.php

527 lines
16 KiB
PHP
Raw Normal View History

2017-04-18 05:44:08 +02:00
<?php
namespace Stripe;
/**
2021-01-03 23:37:44 +01:00
* Class ApiRequestor.
2017-04-18 05:44:08 +02:00
*/
class ApiRequestor
{
2019-05-03 02:22:27 +02:00
/**
2021-01-03 23:37:44 +01:00
* @var null|string
2019-05-03 02:22:27 +02:00
*/
2017-04-18 05:44:08 +02:00
private $_apiKey;
2019-05-03 02:22:27 +02:00
/**
* @var string
*/
2017-04-18 05:44:08 +02:00
private $_apiBase;
2019-05-03 02:22:27 +02:00
/**
* @var HttpClient\ClientInterface
*/
2017-04-18 05:44:08 +02:00
private static $_httpClient;
2019-05-03 02:22:27 +02:00
/**
* @var RequestTelemetry
*/
private static $requestTelemetry;
2021-01-03 23:37:44 +01:00
private static $OPTIONS_KEYS = ['api_key', 'idempotency_key', 'stripe_account', 'stripe_version', 'api_base'];
2019-05-03 02:22:27 +02:00
/**
* ApiRequestor constructor.
*
2021-01-03 23:37:44 +01:00
* @param null|string $apiKey
* @param null|string $apiBase
2019-05-03 02:22:27 +02:00
*/
2017-04-18 05:44:08 +02:00
public function __construct($apiKey = null, $apiBase = null)
{
$this->_apiKey = $apiKey;
if (!$apiBase) {
$apiBase = Stripe::$apiBase;
}
$this->_apiBase = $apiBase;
}
2019-05-03 02:22:27 +02:00
/**
2021-01-03 23:37:44 +01:00
* Creates a telemetry json blob for use in 'X-Stripe-Client-Telemetry' headers.
*
2019-05-03 02:22:27 +02:00
* @static
*
* @param RequestTelemetry $requestTelemetry
2021-01-03 23:37:44 +01:00
*
2019-05-03 02:22:27 +02:00
* @return string
*/
private static function _telemetryJson($requestTelemetry)
{
2021-01-03 23:37:44 +01:00
$payload = [
'last_request_metrics' => [
2019-05-03 02:22:27 +02:00
'request_id' => $requestTelemetry->requestId,
'request_duration_ms' => $requestTelemetry->requestDuration,
2021-01-03 23:37:44 +01:00
],
];
2019-05-03 02:22:27 +02:00
2021-01-03 23:37:44 +01:00
$result = \json_encode($payload);
if (false !== $result) {
2019-05-03 02:22:27 +02:00
return $result;
}
2021-01-03 23:37:44 +01:00
Stripe::getLogger()->error('Serializing telemetry payload failed!');
return '{}';
2019-05-03 02:22:27 +02:00
}
/**
* @static
*
2021-01-03 23:37:44 +01:00
* @param ApiResource|array|bool|mixed $d
2019-05-03 02:22:27 +02:00
*
2021-01-03 23:37:44 +01:00
* @return ApiResource|array|mixed|string
2019-05-03 02:22:27 +02:00
*/
2017-04-18 05:44:08 +02:00
private static function _encodeObjects($d)
{
if ($d instanceof ApiResource) {
return Util\Util::utf8($d->id);
2021-01-03 23:37:44 +01:00
}
if (true === $d) {
2017-04-18 05:44:08 +02:00
return 'true';
2021-01-03 23:37:44 +01:00
}
if (false === $d) {
2017-04-18 05:44:08 +02:00
return 'false';
2021-01-03 23:37:44 +01:00
}
if (\is_array($d)) {
2018-03-06 13:52:56 +01:00
$res = [];
2017-04-18 05:44:08 +02:00
foreach ($d as $k => $v) {
$res[$k] = self::_encodeObjects($v);
}
2021-01-03 23:37:44 +01:00
2017-04-18 05:44:08 +02:00
return $res;
}
2021-01-03 23:37:44 +01:00
return Util\Util::utf8($d);
2017-04-18 05:44:08 +02:00
}
/**
2019-05-03 02:22:27 +02:00
* @param string $method
* @param string $url
2021-01-03 23:37:44 +01:00
* @param null|array $params
* @param null|array $headers
2017-04-18 05:44:08 +02:00
*
2021-01-03 23:37:44 +01:00
* @throws Exception\ApiErrorException
*
* @return array tuple containing (ApiReponse, API key)
2017-04-18 05:44:08 +02:00
*/
public function request($method, $url, $params = null, $headers = null)
{
2018-03-06 13:52:56 +01:00
$params = $params ?: [];
$headers = $headers ?: [];
2017-04-18 05:44:08 +02:00
list($rbody, $rcode, $rheaders, $myApiKey) =
$this->_requestRaw($method, $url, $params, $headers);
$json = $this->_interpretResponse($rbody, $rcode, $rheaders);
$resp = new ApiResponse($rbody, $rcode, $rheaders, $json);
2021-01-03 23:37:44 +01:00
2018-03-06 13:52:56 +01:00
return [$resp, $myApiKey];
2017-04-18 05:44:08 +02:00
}
/**
2021-01-03 23:37:44 +01:00
* @param string $rbody a JSON string
2017-04-18 05:44:08 +02:00
* @param int $rcode
* @param array $rheaders
* @param array $resp
*
2021-01-03 23:37:44 +01:00
* @throws Exception\UnexpectedValueException
* @throws Exception\ApiErrorException
2017-04-18 05:44:08 +02:00
*/
2018-03-06 13:52:56 +01:00
public function handleErrorResponse($rbody, $rcode, $rheaders, $resp)
2017-04-18 05:44:08 +02:00
{
2021-01-03 23:37:44 +01:00
if (!\is_array($resp) || !isset($resp['error'])) {
$msg = "Invalid response object from API: {$rbody} "
. "(HTTP response code was {$rcode})";
throw new Exception\UnexpectedValueException($msg);
2017-04-18 05:44:08 +02:00
}
2018-03-06 13:52:56 +01:00
$errorData = $resp['error'];
$error = null;
2021-01-03 23:37:44 +01:00
if (\is_string($errorData)) {
2018-03-06 13:52:56 +01:00
$error = self::_specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorData);
}
if (!$error) {
$error = self::_specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData);
}
throw $error;
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
* @param string $rbody
* @param int $rcode
* @param array $rheaders
* @param array $resp
* @param array $errorData
*
2021-01-03 23:37:44 +01:00
* @return Exception\ApiErrorException
2019-05-03 02:22:27 +02:00
*/
2018-03-06 13:52:56 +01:00
private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData)
{
$msg = isset($errorData['message']) ? $errorData['message'] : null;
$param = isset($errorData['param']) ? $errorData['param'] : null;
$code = isset($errorData['code']) ? $errorData['code'] : null;
$type = isset($errorData['type']) ? $errorData['type'] : null;
2021-01-03 23:37:44 +01:00
$declineCode = isset($errorData['decline_code']) ? $errorData['decline_code'] : null;
2017-04-18 05:44:08 +02:00
switch ($rcode) {
case 400:
// 'rate_limit' code is deprecated, but left here for backwards compatibility
// for API versions earlier than 2015-09-08
2021-01-03 23:37:44 +01:00
if ('rate_limit' === $code) {
return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
2018-03-06 13:52:56 +01:00
}
2021-01-03 23:37:44 +01:00
if ('idempotency_error' === $type) {
return Exception\IdempotencyException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
2017-04-18 05:44:08 +02:00
}
2020-03-13 03:07:28 +01:00
// no break
2017-04-18 05:44:08 +02:00
case 404:
2021-01-03 23:37:44 +01:00
return Exception\InvalidRequestException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
2017-04-18 05:44:08 +02:00
case 401:
2021-01-03 23:37:44 +01:00
return Exception\AuthenticationException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
2017-04-18 05:44:08 +02:00
case 402:
2021-01-03 23:37:44 +01:00
return Exception\CardException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $declineCode, $param);
2017-04-18 05:44:08 +02:00
case 403:
2021-01-03 23:37:44 +01:00
return Exception\PermissionException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
2017-04-18 05:44:08 +02:00
case 429:
2021-01-03 23:37:44 +01:00
return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
2017-04-18 05:44:08 +02:00
default:
2021-01-03 23:37:44 +01:00
return Exception\UnknownApiErrorException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
2017-04-18 05:44:08 +02:00
}
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
2021-01-03 23:37:44 +01:00
* @param bool|string $rbody
2019-05-03 02:22:27 +02:00
* @param int $rcode
* @param array $rheaders
* @param array $resp
* @param string $errorCode
*
2021-01-03 23:37:44 +01:00
* @return Exception\OAuth\OAuthErrorException
2019-05-03 02:22:27 +02:00
*/
2018-03-06 13:52:56 +01:00
private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorCode)
{
$description = isset($resp['error_description']) ? $resp['error_description'] : $errorCode;
switch ($errorCode) {
case 'invalid_client':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\InvalidClientException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
case 'invalid_grant':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\InvalidGrantException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
case 'invalid_request':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\InvalidRequestException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
case 'invalid_scope':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\InvalidScopeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
case 'unsupported_grant_type':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\UnsupportedGrantTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
case 'unsupported_response_type':
2021-01-03 23:37:44 +01:00
return Exception\OAuth\UnsupportedResponseTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
2018-03-06 13:52:56 +01:00
2021-01-03 23:37:44 +01:00
default:
return Exception\OAuth\UnknownOAuthErrorException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
}
2018-03-06 13:52:56 +01:00
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
* @param null|array $appInfo
*
* @return null|string
*/
2017-04-18 05:44:08 +02:00
private static function _formatAppInfo($appInfo)
{
2021-01-03 23:37:44 +01:00
if (null !== $appInfo) {
2017-04-18 05:44:08 +02:00
$string = $appInfo['name'];
2021-01-03 23:37:44 +01:00
if (null !== $appInfo['version']) {
2017-04-18 05:44:08 +02:00
$string .= '/' . $appInfo['version'];
}
2021-01-03 23:37:44 +01:00
if (null !== $appInfo['url']) {
2017-04-18 05:44:08 +02:00
$string .= ' (' . $appInfo['url'] . ')';
}
2021-01-03 23:37:44 +01:00
2017-04-18 05:44:08 +02:00
return $string;
}
2021-01-03 23:37:44 +01:00
return null;
}
/**
* @static
*
* @param string $disabledFunctionsOutput - String value of the 'disable_function' setting, as output by \ini_get('disable_functions')
* @param string $functionName - Name of the function we are interesting in seeing whether or not it is disabled
* @param mixed $disableFunctionsOutput
*
* @return bool
*/
private static function _isDisabled($disableFunctionsOutput, $functionName)
{
$disabledFunctions = \explode(',', $disableFunctionsOutput);
foreach ($disabledFunctions as $disabledFunction) {
if (\trim($disabledFunction) === $functionName) {
return true;
}
}
return false;
2017-04-18 05:44:08 +02:00
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
* @param string $apiKey
* @param null $clientInfo
*
* @return array
*/
2018-03-06 13:52:56 +01:00
private static function _defaultHeaders($apiKey, $clientInfo = null)
2017-04-18 05:44:08 +02:00
{
$uaString = 'Stripe/v1 PhpBindings/' . Stripe::VERSION;
2021-01-03 23:37:44 +01:00
$langVersion = \PHP_VERSION;
$uname_disabled = static::_isDisabled(\ini_get('disable_functions'), 'php_uname');
$uname = $uname_disabled ? '(disabled)' : \php_uname();
2017-04-18 05:44:08 +02:00
$appInfo = Stripe::getAppInfo();
2018-03-06 13:52:56 +01:00
$ua = [
2017-04-18 05:44:08 +02:00
'bindings_version' => Stripe::VERSION,
'lang' => 'php',
'lang_version' => $langVersion,
'publisher' => 'stripe',
'uname' => $uname,
2018-03-06 13:52:56 +01:00
];
if ($clientInfo) {
2021-01-03 23:37:44 +01:00
$ua = \array_merge($clientInfo, $ua);
2018-03-06 13:52:56 +01:00
}
2021-01-03 23:37:44 +01:00
if (null !== $appInfo) {
2017-04-18 05:44:08 +02:00
$uaString .= ' ' . self::_formatAppInfo($appInfo);
$ua['application'] = $appInfo;
}
2021-01-03 23:37:44 +01:00
return [
'X-Stripe-Client-User-Agent' => \json_encode($ua),
2017-04-18 05:44:08 +02:00
'User-Agent' => $uaString,
'Authorization' => 'Bearer ' . $apiKey,
2018-03-06 13:52:56 +01:00
];
2017-04-18 05:44:08 +02:00
}
2019-05-03 02:22:27 +02:00
/**
* @param string $method
* @param string $url
2021-01-03 23:37:44 +01:00
* @param array $params
* @param array $headers
*
* @throws Exception\AuthenticationException
* @throws Exception\ApiConnectionException
2019-05-03 02:22:27 +02:00
*
* @return array
*/
2017-04-18 05:44:08 +02:00
private function _requestRaw($method, $url, $params, $headers)
{
$myApiKey = $this->_apiKey;
if (!$myApiKey) {
$myApiKey = Stripe::$apiKey;
}
if (!$myApiKey) {
$msg = 'No API key provided. (HINT: set your API key using '
. '"Stripe::setApiKey(<API-KEY>)". You can generate API keys from '
. 'the Stripe web interface. See https://stripe.com/api for '
. 'details, or email support@stripe.com if you have any questions.';
2021-01-03 23:37:44 +01:00
throw new Exception\AuthenticationException($msg);
2017-04-18 05:44:08 +02:00
}
2018-03-06 13:52:56 +01:00
// Clients can supply arbitrary additional keys to be included in the
// X-Stripe-Client-User-Agent header via the optional getUserAgentInfo()
// method
$clientUAInfo = null;
2021-01-03 23:37:44 +01:00
if (\method_exists($this->httpClient(), 'getUserAgentInfo')) {
2018-03-06 13:52:56 +01:00
$clientUAInfo = $this->httpClient()->getUserAgentInfo();
}
2021-01-03 23:37:44 +01:00
if ($params && \is_array($params)) {
$optionKeysInParams = \array_filter(
static::$OPTIONS_KEYS,
function ($key) use ($params) {
return \array_key_exists($key, $params);
}
);
if (\count($optionKeysInParams) > 0) {
$message = \sprintf('Options found in $params: %s. Options should '
. 'be passed in their own array after $params. (HINT: pass an '
. 'empty array to $params if you do not have any.)', \implode(', ', $optionKeysInParams));
\trigger_error($message, \E_USER_WARNING);
}
}
$absUrl = $this->_apiBase . $url;
2017-04-18 05:44:08 +02:00
$params = self::_encodeObjects($params);
2018-03-06 13:52:56 +01:00
$defaultHeaders = $this->_defaultHeaders($myApiKey, $clientUAInfo);
2017-04-18 05:44:08 +02:00
if (Stripe::$apiVersion) {
$defaultHeaders['Stripe-Version'] = Stripe::$apiVersion;
}
if (Stripe::$accountId) {
$defaultHeaders['Stripe-Account'] = Stripe::$accountId;
}
2021-01-03 23:37:44 +01:00
if (Stripe::$enableTelemetry && null !== self::$requestTelemetry) {
$defaultHeaders['X-Stripe-Client-Telemetry'] = self::_telemetryJson(self::$requestTelemetry);
2019-05-03 02:22:27 +02:00
}
2017-04-18 05:44:08 +02:00
$hasFile = false;
foreach ($params as $k => $v) {
2021-01-03 23:37:44 +01:00
if (\is_resource($v)) {
2017-04-18 05:44:08 +02:00
$hasFile = true;
2021-01-03 23:37:44 +01:00
$params[$k] = self::_processResourceParam($v);
} elseif ($v instanceof \CURLFile) {
2017-04-18 05:44:08 +02:00
$hasFile = true;
}
}
if ($hasFile) {
$defaultHeaders['Content-Type'] = 'multipart/form-data';
} else {
$defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
}
2021-01-03 23:37:44 +01:00
$combinedHeaders = \array_merge($defaultHeaders, $headers);
2018-03-06 13:52:56 +01:00
$rawHeaders = [];
2017-04-18 05:44:08 +02:00
foreach ($combinedHeaders as $header => $value) {
$rawHeaders[] = $header . ': ' . $value;
}
2019-05-03 02:22:27 +02:00
$requestStartMs = Util\Util::currentTimeMillis();
2017-04-18 05:44:08 +02:00
list($rbody, $rcode, $rheaders) = $this->httpClient()->request(
$method,
$absUrl,
$rawHeaders,
$params,
$hasFile
);
2019-05-03 02:22:27 +02:00
2021-01-03 23:37:44 +01:00
if (isset($rheaders['request-id'])
&& \is_string($rheaders['request-id'])
&& \strlen($rheaders['request-id']) > 0) {
2019-05-03 02:22:27 +02:00
self::$requestTelemetry = new RequestTelemetry(
$rheaders['request-id'],
Util\Util::currentTimeMillis() - $requestStartMs
);
}
2018-03-06 13:52:56 +01:00
return [$rbody, $rcode, $rheaders, $myApiKey];
2017-04-18 05:44:08 +02:00
}
2019-05-03 02:22:27 +02:00
/**
* @param resource $resource
2021-01-03 23:37:44 +01:00
*
* @throws Exception\InvalidArgumentException
2019-05-03 02:22:27 +02:00
*
* @return \CURLFile|string
*/
2021-01-03 23:37:44 +01:00
private function _processResourceParam($resource)
2017-04-18 05:44:08 +02:00
{
2021-01-03 23:37:44 +01:00
if ('stream' !== \get_resource_type($resource)) {
throw new Exception\InvalidArgumentException(
2017-04-18 05:44:08 +02:00
'Attempted to upload a resource that is not a stream'
);
}
2021-01-03 23:37:44 +01:00
$metaData = \stream_get_meta_data($resource);
if ('plainfile' !== $metaData['wrapper_type']) {
throw new Exception\InvalidArgumentException(
2017-04-18 05:44:08 +02:00
'Only plainfile resource streams are supported'
);
}
2021-01-03 23:37:44 +01:00
// We don't have the filename or mimetype, but the API doesn't care
return new \CURLFile($metaData['uri']);
2017-04-18 05:44:08 +02:00
}
2019-05-03 02:22:27 +02:00
/**
* @param string $rbody
* @param int $rcode
* @param array $rheaders
*
2021-01-03 23:37:44 +01:00
* @throws Exception\UnexpectedValueException
* @throws Exception\ApiErrorException
*
* @return array
2019-05-03 02:22:27 +02:00
*/
2017-04-18 05:44:08 +02:00
private function _interpretResponse($rbody, $rcode, $rheaders)
{
2021-01-03 23:37:44 +01:00
$resp = \json_decode($rbody, true);
$jsonError = \json_last_error();
if (null === $resp && \JSON_ERROR_NONE !== $jsonError) {
$msg = "Invalid response body from API: {$rbody} "
. "(HTTP response code was {$rcode}, json_last_error() was {$jsonError})";
throw new Exception\UnexpectedValueException($msg, $rcode);
2017-04-18 05:44:08 +02:00
}
if ($rcode < 200 || $rcode >= 300) {
2018-03-06 13:52:56 +01:00
$this->handleErrorResponse($rbody, $rcode, $rheaders, $resp);
2017-04-18 05:44:08 +02:00
}
2021-01-03 23:37:44 +01:00
2017-04-18 05:44:08 +02:00
return $resp;
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
* @param HttpClient\ClientInterface $client
*/
2017-04-18 05:44:08 +02:00
public static function setHttpClient($client)
{
self::$_httpClient = $client;
}
2019-05-03 02:22:27 +02:00
/**
* @static
*
* Resets any stateful telemetry data
*/
public static function resetTelemetry()
{
self::$requestTelemetry = null;
}
/**
* @return HttpClient\ClientInterface
*/
2017-04-18 05:44:08 +02:00
private function httpClient()
{
if (!self::$_httpClient) {
self::$_httpClient = HttpClient\CurlClient::instance();
}
2021-01-03 23:37:44 +01:00
2017-04-18 05:44:08 +02:00
return self::$_httpClient;
}
}