ApiRequestor.php 16 KB

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