Request.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace Stripe\ApiOperations;
  3. /**
  4. * Trait for resources that need to make API requests.
  5. *
  6. * This trait should only be applied to classes that derive from StripeObject.
  7. */
  8. trait Request
  9. {
  10. /**
  11. * @param null|array|mixed $params The list of parameters to validate
  12. *
  13. * @throws \Stripe\Exception\InvalidArgumentException if $params exists and is not an array
  14. */
  15. protected static function _validateParams($params = null)
  16. {
  17. if ($params && !\is_array($params)) {
  18. $message = 'You must pass an array as the first argument to Stripe API '
  19. . 'method calls. (HINT: an example call to create a charge '
  20. . "would be: \"Stripe\\Charge::create(['amount' => 100, "
  21. . "'currency' => 'usd', 'source' => 'tok_1234'])\")";
  22. throw new \Stripe\Exception\InvalidArgumentException($message);
  23. }
  24. }
  25. /**
  26. * @param string $method HTTP method ('get', 'post', etc.)
  27. * @param string $url URL for the request
  28. * @param array $params list of parameters for the request
  29. * @param null|array|string $options
  30. *
  31. * @throws \Stripe\Exception\ApiErrorException if the request fails
  32. *
  33. * @return array tuple containing (the JSON response, $options)
  34. */
  35. protected function _request($method, $url, $params = [], $options = null)
  36. {
  37. $opts = $this->_opts->merge($options);
  38. list($resp, $options) = static::_staticRequest($method, $url, $params, $opts);
  39. $this->setLastResponse($resp);
  40. return [$resp->json, $options];
  41. }
  42. /**
  43. * @param string $method HTTP method ('get', 'post', etc.)
  44. * @param string $url URL for the request
  45. * @param array $params list of parameters for the request
  46. * @param null|array|string $options
  47. *
  48. * @throws \Stripe\Exception\ApiErrorException if the request fails
  49. *
  50. * @return array tuple containing (the JSON response, $options)
  51. */
  52. protected static function _staticRequest($method, $url, $params, $options)
  53. {
  54. $opts = \Stripe\Util\RequestOptions::parse($options);
  55. $baseUrl = isset($opts->apiBase) ? $opts->apiBase : static::baseUrl();
  56. $requestor = new \Stripe\ApiRequestor($opts->apiKey, $baseUrl);
  57. list($response, $opts->apiKey) = $requestor->request($method, $url, $params, $opts->headers);
  58. $opts->discardNonPersistentHeaders();
  59. return [$response, $opts];
  60. }
  61. }