ApiRequestor.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. <?php
  2. namespace Stripe;
  3. /**
  4. * Class ApiRequestor.
  5. */
  6. class ApiRequestor
  7. {
  8. /**
  9. * @var null|string
  10. */
  11. private $_apiKey;
  12. /**
  13. * @var string
  14. */
  15. private $_apiBase;
  16. /**
  17. * @var null|array
  18. */
  19. private $_appInfo;
  20. /**
  21. * @var HttpClient\ClientInterface
  22. */
  23. private static $_httpClient;
  24. /**
  25. * @var HttpClient\StreamingClientInterface
  26. */
  27. private static $_streamingHttpClient;
  28. /**
  29. * @var RequestTelemetry
  30. */
  31. private static $requestTelemetry;
  32. private static $OPTIONS_KEYS = ['api_key', 'idempotency_key', 'stripe_account', 'stripe_version', 'api_base'];
  33. /**
  34. * ApiRequestor constructor.
  35. *
  36. * @param null|string $apiKey
  37. * @param null|string $apiBase
  38. * @param null|array $appInfo
  39. */
  40. public function __construct($apiKey = null, $apiBase = null, $appInfo = null)
  41. {
  42. $this->_apiKey = $apiKey;
  43. if (!$apiBase) {
  44. $apiBase = Stripe::$apiBase;
  45. }
  46. $this->_apiBase = $apiBase;
  47. $this->_appInfo = $appInfo;
  48. }
  49. /**
  50. * Creates a telemetry json blob for use in 'X-Stripe-Client-Telemetry' headers.
  51. *
  52. * @static
  53. *
  54. * @param RequestTelemetry $requestTelemetry
  55. *
  56. * @return string
  57. */
  58. private static function _telemetryJson($requestTelemetry)
  59. {
  60. $payload = [
  61. 'last_request_metrics' => [
  62. 'request_id' => $requestTelemetry->requestId,
  63. 'request_duration_ms' => $requestTelemetry->requestDuration,
  64. ],
  65. ];
  66. if (\count($requestTelemetry->usage) > 0) {
  67. $payload['last_request_metrics']['usage'] = $requestTelemetry->usage;
  68. }
  69. $result = \json_encode($payload);
  70. if (false !== $result) {
  71. return $result;
  72. }
  73. Stripe::getLogger()->error('Serializing telemetry payload failed!');
  74. return '{}';
  75. }
  76. /**
  77. * @static
  78. *
  79. * @param ApiResource|array|bool|mixed $d
  80. *
  81. * @return ApiResource|array|mixed|string
  82. */
  83. private static function _encodeObjects($d)
  84. {
  85. if ($d instanceof ApiResource) {
  86. return Util\Util::utf8($d->id);
  87. }
  88. if (true === $d) {
  89. return 'true';
  90. }
  91. if (false === $d) {
  92. return 'false';
  93. }
  94. if (\is_array($d)) {
  95. $res = [];
  96. foreach ($d as $k => $v) {
  97. $res[$k] = self::_encodeObjects($v);
  98. }
  99. return $res;
  100. }
  101. return Util\Util::utf8($d);
  102. }
  103. /**
  104. * @param 'delete'|'get'|'post' $method
  105. * @param string $url
  106. * @param null|array $params
  107. * @param null|array $headers
  108. * @param string[] $usage
  109. *
  110. * @throws Exception\ApiErrorException
  111. *
  112. * @return array tuple containing (ApiReponse, API key)
  113. */
  114. public function request($method, $url, $params = null, $headers = null, $usage = [])
  115. {
  116. $params = $params ?: [];
  117. $headers = $headers ?: [];
  118. list($rbody, $rcode, $rheaders, $myApiKey) =
  119. $this->_requestRaw($method, $url, $params, $headers, $usage);
  120. $json = $this->_interpretResponse($rbody, $rcode, $rheaders);
  121. $resp = new ApiResponse($rbody, $rcode, $rheaders, $json);
  122. return [$resp, $myApiKey];
  123. }
  124. /**
  125. * @param 'delete'|'get'|'post' $method
  126. * @param string $url
  127. * @param callable $readBodyChunkCallable
  128. * @param null|array $params
  129. * @param null|array $headers
  130. * @param string[] $usage
  131. *
  132. * @throws Exception\ApiErrorException
  133. */
  134. public function requestStream($method, $url, $readBodyChunkCallable, $params = null, $headers = null, $usage = [])
  135. {
  136. $params = $params ?: [];
  137. $headers = $headers ?: [];
  138. list($rbody, $rcode, $rheaders, $myApiKey) =
  139. $this->_requestRawStreaming($method, $url, $params, $headers, $usage, $readBodyChunkCallable);
  140. if ($rcode >= 300) {
  141. $this->_interpretResponse($rbody, $rcode, $rheaders);
  142. }
  143. }
  144. /**
  145. * @param string $rbody a JSON string
  146. * @param int $rcode
  147. * @param array $rheaders
  148. * @param array $resp
  149. *
  150. * @throws Exception\UnexpectedValueException
  151. * @throws Exception\ApiErrorException
  152. */
  153. public function handleErrorResponse($rbody, $rcode, $rheaders, $resp)
  154. {
  155. if (!\is_array($resp) || !isset($resp['error'])) {
  156. $msg = "Invalid response object from API: {$rbody} "
  157. . "(HTTP response code was {$rcode})";
  158. throw new Exception\UnexpectedValueException($msg);
  159. }
  160. $errorData = $resp['error'];
  161. $error = null;
  162. if (\is_string($errorData)) {
  163. $error = self::_specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorData);
  164. }
  165. if (!$error) {
  166. $error = self::_specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData);
  167. }
  168. throw $error;
  169. }
  170. /**
  171. * @static
  172. *
  173. * @param string $rbody
  174. * @param int $rcode
  175. * @param array $rheaders
  176. * @param array $resp
  177. * @param array $errorData
  178. *
  179. * @return Exception\ApiErrorException
  180. */
  181. private static function _specificAPIError($rbody, $rcode, $rheaders, $resp, $errorData)
  182. {
  183. $msg = isset($errorData['message']) ? $errorData['message'] : null;
  184. $param = isset($errorData['param']) ? $errorData['param'] : null;
  185. $code = isset($errorData['code']) ? $errorData['code'] : null;
  186. $type = isset($errorData['type']) ? $errorData['type'] : null;
  187. $declineCode = isset($errorData['decline_code']) ? $errorData['decline_code'] : null;
  188. switch ($rcode) {
  189. case 400:
  190. // 'rate_limit' code is deprecated, but left here for backwards compatibility
  191. // for API versions earlier than 2015-09-08
  192. if ('rate_limit' === $code) {
  193. return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
  194. }
  195. if ('idempotency_error' === $type) {
  196. return Exception\IdempotencyException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
  197. }
  198. // no break
  199. case 404:
  200. return Exception\InvalidRequestException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
  201. case 401:
  202. return Exception\AuthenticationException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
  203. case 402:
  204. return Exception\CardException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $declineCode, $param);
  205. case 403:
  206. return Exception\PermissionException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
  207. case 429:
  208. return Exception\RateLimitException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code, $param);
  209. default:
  210. return Exception\UnknownApiErrorException::factory($msg, $rcode, $rbody, $resp, $rheaders, $code);
  211. }
  212. }
  213. /**
  214. * @static
  215. *
  216. * @param bool|string $rbody
  217. * @param int $rcode
  218. * @param array $rheaders
  219. * @param array $resp
  220. * @param string $errorCode
  221. *
  222. * @return Exception\OAuth\OAuthErrorException
  223. */
  224. private static function _specificOAuthError($rbody, $rcode, $rheaders, $resp, $errorCode)
  225. {
  226. $description = isset($resp['error_description']) ? $resp['error_description'] : $errorCode;
  227. switch ($errorCode) {
  228. case 'invalid_client':
  229. return Exception\OAuth\InvalidClientException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  230. case 'invalid_grant':
  231. return Exception\OAuth\InvalidGrantException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  232. case 'invalid_request':
  233. return Exception\OAuth\InvalidRequestException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  234. case 'invalid_scope':
  235. return Exception\OAuth\InvalidScopeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  236. case 'unsupported_grant_type':
  237. return Exception\OAuth\UnsupportedGrantTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  238. case 'unsupported_response_type':
  239. return Exception\OAuth\UnsupportedResponseTypeException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  240. default:
  241. return Exception\OAuth\UnknownOAuthErrorException::factory($description, $rcode, $rbody, $resp, $rheaders, $errorCode);
  242. }
  243. }
  244. /**
  245. * @static
  246. *
  247. * @param null|array $appInfo
  248. *
  249. * @return null|string
  250. */
  251. private static function _formatAppInfo($appInfo)
  252. {
  253. if (null !== $appInfo) {
  254. $string = $appInfo['name'];
  255. if (\array_key_exists('version', $appInfo) && null !== $appInfo['version']) {
  256. $string .= '/' . $appInfo['version'];
  257. }
  258. if (\array_key_exists('url', $appInfo) && null !== $appInfo['url']) {
  259. $string .= ' (' . $appInfo['url'] . ')';
  260. }
  261. return $string;
  262. }
  263. return null;
  264. }
  265. /**
  266. * @static
  267. *
  268. * @param string $disableFunctionsOutput - String value of the 'disable_function' setting, as output by \ini_get('disable_functions')
  269. * @param string $functionName - Name of the function we are interesting in seeing whether or not it is disabled
  270. *
  271. * @return bool
  272. */
  273. private static function _isDisabled($disableFunctionsOutput, $functionName)
  274. {
  275. $disabledFunctions = \explode(',', $disableFunctionsOutput);
  276. foreach ($disabledFunctions as $disabledFunction) {
  277. if (\trim($disabledFunction) === $functionName) {
  278. return true;
  279. }
  280. }
  281. return false;
  282. }
  283. /**
  284. * @static
  285. *
  286. * @param string $apiKey the Stripe API key, to be used in regular API requests
  287. * @param null $clientInfo client user agent information
  288. * @param null $appInfo information to identify a plugin that integrates Stripe using this library
  289. *
  290. * @return array
  291. */
  292. private static function _defaultHeaders($apiKey, $clientInfo = null, $appInfo = null)
  293. {
  294. $uaString = 'Stripe/v1 PhpBindings/' . Stripe::VERSION;
  295. $langVersion = \PHP_VERSION;
  296. $uname_disabled = self::_isDisabled(\ini_get('disable_functions'), 'php_uname');
  297. $uname = $uname_disabled ? '(disabled)' : \php_uname();
  298. // Fallback to global configuration to maintain backwards compatibility.
  299. $appInfo = $appInfo ?: Stripe::getAppInfo();
  300. $ua = [
  301. 'bindings_version' => Stripe::VERSION,
  302. 'lang' => 'php',
  303. 'lang_version' => $langVersion,
  304. 'publisher' => 'stripe',
  305. 'uname' => $uname,
  306. ];
  307. if ($clientInfo) {
  308. $ua = \array_merge($clientInfo, $ua);
  309. }
  310. if (null !== $appInfo) {
  311. $uaString .= ' ' . self::_formatAppInfo($appInfo);
  312. $ua['application'] = $appInfo;
  313. }
  314. return [
  315. 'X-Stripe-Client-User-Agent' => \json_encode($ua),
  316. 'User-Agent' => $uaString,
  317. 'Authorization' => 'Bearer ' . $apiKey,
  318. 'Stripe-Version' => Stripe::getApiVersion(),
  319. ];
  320. }
  321. private function _prepareRequest($method, $url, $params, $headers)
  322. {
  323. $myApiKey = $this->_apiKey;
  324. if (!$myApiKey) {
  325. $myApiKey = Stripe::$apiKey;
  326. }
  327. if (!$myApiKey) {
  328. $msg = 'No API key provided. (HINT: set your API key using '
  329. . '"Stripe::setApiKey(<API-KEY>)". You can generate API keys from '
  330. . 'the Stripe web interface. See https://stripe.com/api for '
  331. . 'details, or email support@stripe.com if you have any questions.';
  332. throw new Exception\AuthenticationException($msg);
  333. }
  334. // Clients can supply arbitrary additional keys to be included in the
  335. // X-Stripe-Client-User-Agent header via the optional getUserAgentInfo()
  336. // method
  337. $clientUAInfo = null;
  338. if (\method_exists($this->httpClient(), 'getUserAgentInfo')) {
  339. $clientUAInfo = $this->httpClient()->getUserAgentInfo();
  340. }
  341. if ($params && \is_array($params)) {
  342. $optionKeysInParams = \array_filter(
  343. self::$OPTIONS_KEYS,
  344. function ($key) use ($params) {
  345. return \array_key_exists($key, $params);
  346. }
  347. );
  348. if (\count($optionKeysInParams) > 0) {
  349. $message = \sprintf('Options found in $params: %s. Options should '
  350. . 'be passed in their own array after $params. (HINT: pass an '
  351. . 'empty array to $params if you do not have any.)', \implode(', ', $optionKeysInParams));
  352. \trigger_error($message, \E_USER_WARNING);
  353. }
  354. }
  355. $absUrl = $this->_apiBase . $url;
  356. $params = self::_encodeObjects($params);
  357. $defaultHeaders = $this->_defaultHeaders($myApiKey, $clientUAInfo, $this->_appInfo);
  358. if (Stripe::$accountId) {
  359. $defaultHeaders['Stripe-Account'] = Stripe::$accountId;
  360. }
  361. if (Stripe::$enableTelemetry && null !== self::$requestTelemetry) {
  362. $defaultHeaders['X-Stripe-Client-Telemetry'] = self::_telemetryJson(self::$requestTelemetry);
  363. }
  364. $hasFile = false;
  365. foreach ($params as $k => $v) {
  366. if (\is_resource($v)) {
  367. $hasFile = true;
  368. $params[$k] = self::_processResourceParam($v);
  369. } elseif ($v instanceof \CURLFile) {
  370. $hasFile = true;
  371. }
  372. }
  373. if ($hasFile) {
  374. $defaultHeaders['Content-Type'] = 'multipart/form-data';
  375. } else {
  376. $defaultHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
  377. }
  378. $combinedHeaders = \array_merge($defaultHeaders, $headers);
  379. $rawHeaders = [];
  380. foreach ($combinedHeaders as $header => $value) {
  381. $rawHeaders[] = $header . ': ' . $value;
  382. }
  383. return [$absUrl, $rawHeaders, $params, $hasFile, $myApiKey];
  384. }
  385. /**
  386. * @param 'delete'|'get'|'post' $method
  387. * @param string $url
  388. * @param array $params
  389. * @param array $headers
  390. * @param string[] $usage
  391. *
  392. * @throws Exception\AuthenticationException
  393. * @throws Exception\ApiConnectionException
  394. *
  395. * @return array
  396. */
  397. private function _requestRaw($method, $url, $params, $headers, $usage)
  398. {
  399. list($absUrl, $rawHeaders, $params, $hasFile, $myApiKey) = $this->_prepareRequest($method, $url, $params, $headers);
  400. $requestStartMs = Util\Util::currentTimeMillis();
  401. list($rbody, $rcode, $rheaders) = $this->httpClient()->request(
  402. $method,
  403. $absUrl,
  404. $rawHeaders,
  405. $params,
  406. $hasFile
  407. );
  408. if (
  409. isset($rheaders['request-id'])
  410. && \is_string($rheaders['request-id'])
  411. && '' !== $rheaders['request-id']
  412. ) {
  413. self::$requestTelemetry = new RequestTelemetry(
  414. $rheaders['request-id'],
  415. Util\Util::currentTimeMillis() - $requestStartMs,
  416. $usage
  417. );
  418. }
  419. return [$rbody, $rcode, $rheaders, $myApiKey];
  420. }
  421. /**
  422. * @param 'delete'|'get'|'post' $method
  423. * @param string $url
  424. * @param array $params
  425. * @param array $headers
  426. * @param string[] $usage
  427. * @param callable $readBodyChunkCallable
  428. *
  429. * @throws Exception\AuthenticationException
  430. * @throws Exception\ApiConnectionException
  431. *
  432. * @return array
  433. */
  434. private function _requestRawStreaming($method, $url, $params, $headers, $usage, $readBodyChunkCallable)
  435. {
  436. list($absUrl, $rawHeaders, $params, $hasFile, $myApiKey) = $this->_prepareRequest($method, $url, $params, $headers);
  437. $requestStartMs = Util\Util::currentTimeMillis();
  438. list($rbody, $rcode, $rheaders) = $this->streamingHttpClient()->requestStream(
  439. $method,
  440. $absUrl,
  441. $rawHeaders,
  442. $params,
  443. $hasFile,
  444. $readBodyChunkCallable
  445. );
  446. if (
  447. isset($rheaders['request-id'])
  448. && \is_string($rheaders['request-id'])
  449. && '' !== $rheaders['request-id']
  450. ) {
  451. self::$requestTelemetry = new RequestTelemetry(
  452. $rheaders['request-id'],
  453. Util\Util::currentTimeMillis() - $requestStartMs
  454. );
  455. }
  456. return [$rbody, $rcode, $rheaders, $myApiKey];
  457. }
  458. /**
  459. * @param resource $resource
  460. *
  461. * @throws Exception\InvalidArgumentException
  462. *
  463. * @return \CURLFile|string
  464. */
  465. private function _processResourceParam($resource)
  466. {
  467. if ('stream' !== \get_resource_type($resource)) {
  468. throw new Exception\InvalidArgumentException(
  469. 'Attempted to upload a resource that is not a stream'
  470. );
  471. }
  472. $metaData = \stream_get_meta_data($resource);
  473. if ('plainfile' !== $metaData['wrapper_type']) {
  474. throw new Exception\InvalidArgumentException(
  475. 'Only plainfile resource streams are supported'
  476. );
  477. }
  478. // We don't have the filename or mimetype, but the API doesn't care
  479. return new \CURLFile($metaData['uri']);
  480. }
  481. /**
  482. * @param string $rbody
  483. * @param int $rcode
  484. * @param array $rheaders
  485. *
  486. * @throws Exception\UnexpectedValueException
  487. * @throws Exception\ApiErrorException
  488. *
  489. * @return array
  490. */
  491. private function _interpretResponse($rbody, $rcode, $rheaders)
  492. {
  493. $resp = \json_decode($rbody, true);
  494. $jsonError = \json_last_error();
  495. if (null === $resp && \JSON_ERROR_NONE !== $jsonError) {
  496. $msg = "Invalid response body from API: {$rbody} "
  497. . "(HTTP response code was {$rcode}, json_last_error() was {$jsonError})";
  498. throw new Exception\UnexpectedValueException($msg, $rcode);
  499. }
  500. if ($rcode < 200 || $rcode >= 300) {
  501. $this->handleErrorResponse($rbody, $rcode, $rheaders, $resp);
  502. }
  503. return $resp;
  504. }
  505. /**
  506. * @static
  507. *
  508. * @param HttpClient\ClientInterface $client
  509. */
  510. public static function setHttpClient($client)
  511. {
  512. self::$_httpClient = $client;
  513. }
  514. /**
  515. * @static
  516. *
  517. * @param HttpClient\StreamingClientInterface $client
  518. */
  519. public static function setStreamingHttpClient($client)
  520. {
  521. self::$_streamingHttpClient = $client;
  522. }
  523. /**
  524. * @static
  525. *
  526. * Resets any stateful telemetry data
  527. */
  528. public static function resetTelemetry()
  529. {
  530. self::$requestTelemetry = null;
  531. }
  532. /**
  533. * @return HttpClient\ClientInterface
  534. */
  535. private function httpClient()
  536. {
  537. if (!self::$_httpClient) {
  538. self::$_httpClient = HttpClient\CurlClient::instance();
  539. }
  540. return self::$_httpClient;
  541. }
  542. /**
  543. * @return HttpClient\StreamingClientInterface
  544. */
  545. private function streamingHttpClient()
  546. {
  547. if (!self::$_streamingHttpClient) {
  548. self::$_streamingHttpClient = HttpClient\CurlClient::instance();
  549. }
  550. return self::$_streamingHttpClient;
  551. }
  552. }