stripe 3.2.0 → 5.16.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (230) hide show
  1. checksums.yaml +5 -5
  2. data/.editorconfig +10 -0
  3. data/.gitignore +3 -0
  4. data/.rubocop.yml +80 -0
  5. data/.rubocop_todo.yml +33 -0
  6. data/.travis.yml +9 -7
  7. data/.vscode/extensions.json +7 -0
  8. data/.vscode/settings.json +8 -0
  9. data/CHANGELOG.md +876 -0
  10. data/CODE_OF_CONDUCT.md +77 -0
  11. data/Gemfile +21 -21
  12. data/History.txt +1 -678
  13. data/README.md +195 -53
  14. data/Rakefile +18 -12
  15. data/VERSION +1 -1
  16. data/bin/stripe-console +5 -3
  17. data/lib/stripe/api_operations/create.rb +3 -1
  18. data/lib/stripe/api_operations/delete.rb +26 -2
  19. data/lib/stripe/api_operations/list.rb +3 -12
  20. data/lib/stripe/api_operations/nested_resource.rb +72 -0
  21. data/lib/stripe/api_operations/request.rb +33 -15
  22. data/lib/stripe/api_operations/save.rb +18 -9
  23. data/lib/stripe/api_resource.rb +60 -10
  24. data/lib/stripe/connection_manager.rb +159 -0
  25. data/lib/stripe/error_object.rb +94 -0
  26. data/lib/stripe/errors.rb +39 -19
  27. data/lib/stripe/instrumentation.rb +82 -0
  28. data/lib/stripe/list_object.rb +54 -22
  29. data/lib/stripe/multipart_encoder.rb +131 -0
  30. data/lib/stripe/oauth.rb +22 -14
  31. data/lib/stripe/object_types.rb +96 -0
  32. data/lib/stripe/{account.rb → resources/account.rb} +72 -34
  33. data/lib/stripe/resources/account_link.rb +9 -0
  34. data/lib/stripe/resources/alipay_account.rb +34 -0
  35. data/lib/stripe/{apple_pay_domain.rb → resources/apple_pay_domain.rb} +4 -2
  36. data/lib/stripe/resources/application_fee.rb +13 -0
  37. data/lib/stripe/resources/application_fee_refund.rb +30 -0
  38. data/lib/stripe/{balance.rb → resources/balance.rb} +3 -1
  39. data/lib/stripe/{balance_transaction.rb → resources/balance_transaction.rb} +3 -5
  40. data/lib/stripe/resources/bank_account.rb +42 -0
  41. data/lib/stripe/{bitcoin_receiver.rb → resources/bitcoin_receiver.rb} +6 -5
  42. data/lib/stripe/resources/bitcoin_transaction.rb +15 -0
  43. data/lib/stripe/resources/capability.rb +33 -0
  44. data/lib/stripe/resources/card.rb +37 -0
  45. data/lib/stripe/resources/charge.rb +22 -0
  46. data/lib/stripe/resources/checkout/session.rb +12 -0
  47. data/lib/stripe/{country_spec.rb → resources/country_spec.rb} +3 -5
  48. data/lib/stripe/{coupon.rb → resources/coupon.rb} +4 -2
  49. data/lib/stripe/resources/credit_note.rb +32 -0
  50. data/lib/stripe/resources/credit_note_line_item.rb +7 -0
  51. data/lib/stripe/resources/customer.rb +35 -0
  52. data/lib/stripe/resources/customer_balance_transaction.rb +30 -0
  53. data/lib/stripe/resources/discount.rb +7 -0
  54. data/lib/stripe/resources/dispute.rb +21 -0
  55. data/lib/stripe/resources/ephemeral_key.rb +19 -0
  56. data/lib/stripe/{event.rb → resources/event.rb} +3 -1
  57. data/lib/stripe/resources/exchange_rate.rb +9 -0
  58. data/lib/stripe/resources/file.rb +34 -0
  59. data/lib/stripe/resources/file_link.rb +11 -0
  60. data/lib/stripe/resources/invoice.rb +73 -0
  61. data/lib/stripe/{invoice_item.rb → resources/invoice_item.rb} +4 -2
  62. data/lib/stripe/{invoice_line_item.rb → resources/invoice_line_item.rb} +3 -1
  63. data/lib/stripe/resources/issuing/authorization.rb +33 -0
  64. data/lib/stripe/resources/issuing/card.rb +24 -0
  65. data/lib/stripe/resources/issuing/card_details.rb +9 -0
  66. data/lib/stripe/resources/issuing/cardholder.rb +13 -0
  67. data/lib/stripe/resources/issuing/dispute.rb +13 -0
  68. data/lib/stripe/resources/issuing/transaction.rb +12 -0
  69. data/lib/stripe/resources/login_link.rb +14 -0
  70. data/lib/stripe/resources/mandate.rb +7 -0
  71. data/lib/stripe/resources/order.rb +32 -0
  72. data/lib/stripe/{order_return.rb → resources/order_return.rb} +3 -5
  73. data/lib/stripe/resources/payment_intent.rb +42 -0
  74. data/lib/stripe/resources/payment_method.rb +32 -0
  75. data/lib/stripe/resources/payout.rb +22 -0
  76. data/lib/stripe/resources/person.rb +31 -0
  77. data/lib/stripe/{plan.rb → resources/plan.rb} +3 -1
  78. data/lib/stripe/{product.rb → resources/product.rb} +5 -3
  79. data/lib/stripe/resources/radar/early_fraud_warning.rb +11 -0
  80. data/lib/stripe/resources/radar/value_list.rb +14 -0
  81. data/lib/stripe/resources/radar/value_list_item.rb +13 -0
  82. data/lib/stripe/{recipient.rb → resources/recipient.rb} +5 -6
  83. data/lib/stripe/resources/recipient_transfer.rb +7 -0
  84. data/lib/stripe/{refund.rb → resources/refund.rb} +3 -1
  85. data/lib/stripe/resources/reporting/report_run.rb +12 -0
  86. data/lib/stripe/resources/reporting/report_type.rb +12 -0
  87. data/lib/stripe/resources/reversal.rb +29 -0
  88. data/lib/stripe/resources/review.rb +20 -0
  89. data/lib/stripe/resources/setup_intent.rb +32 -0
  90. data/lib/stripe/resources/sigma/scheduled_query_run.rb +15 -0
  91. data/lib/stripe/{sku.rb → resources/sku.rb} +5 -3
  92. data/lib/stripe/resources/source.rb +46 -0
  93. data/lib/stripe/resources/source_transaction.rb +7 -0
  94. data/lib/stripe/resources/subscription.rb +25 -0
  95. data/lib/stripe/resources/subscription_item.rb +25 -0
  96. data/lib/stripe/resources/subscription_schedule.rb +32 -0
  97. data/lib/stripe/resources/tax_id.rb +26 -0
  98. data/lib/stripe/resources/tax_rate.rb +11 -0
  99. data/lib/stripe/resources/terminal/connection_token.rb +11 -0
  100. data/lib/stripe/resources/terminal/location.rb +14 -0
  101. data/lib/stripe/resources/terminal/reader.rb +14 -0
  102. data/lib/stripe/{three_d_secure.rb → resources/three_d_secure.rb} +3 -1
  103. data/lib/stripe/{token.rb → resources/token.rb} +3 -1
  104. data/lib/stripe/resources/topup.rb +22 -0
  105. data/lib/stripe/resources/transfer.rb +26 -0
  106. data/lib/stripe/resources/usage_record.rb +7 -0
  107. data/lib/stripe/resources/usage_record_summary.rb +7 -0
  108. data/lib/stripe/resources/webhook_endpoint.rb +12 -0
  109. data/lib/stripe/resources.rb +79 -0
  110. data/lib/stripe/singleton_api_resource.rb +10 -4
  111. data/lib/stripe/stripe_client.rb +658 -337
  112. data/lib/stripe/stripe_object.rb +248 -126
  113. data/lib/stripe/stripe_response.rb +55 -21
  114. data/lib/stripe/util.rb +145 -187
  115. data/lib/stripe/version.rb +3 -1
  116. data/lib/stripe/webhook.rb +27 -16
  117. data/lib/stripe.rb +139 -90
  118. data/stripe.gemspec +26 -14
  119. data/test/openapi/README.md +9 -0
  120. data/test/stripe/account_link_test.rb +18 -0
  121. data/test/stripe/account_test.rb +311 -101
  122. data/test/stripe/alipay_account_test.rb +21 -1
  123. data/test/stripe/api_operations_test.rb +57 -8
  124. data/test/stripe/api_resource_test.rb +359 -271
  125. data/test/stripe/apple_pay_domain_test.rb +26 -11
  126. data/test/stripe/application_fee_refund_test.rb +10 -8
  127. data/test/stripe/application_fee_test.rb +49 -3
  128. data/test/stripe/balance_test.rb +4 -2
  129. data/test/stripe/balance_transaction_test.rb +20 -0
  130. data/test/stripe/bank_account_test.rb +11 -11
  131. data/test/stripe/capability_test.rb +45 -0
  132. data/test/stripe/charge_test.rb +25 -18
  133. data/test/stripe/checkout/session_test.rb +41 -0
  134. data/test/stripe/connection_manager_test.rb +163 -0
  135. data/test/stripe/country_spec_test.rb +6 -4
  136. data/test/stripe/coupon_test.rb +29 -10
  137. data/test/stripe/credit_note_test.rb +90 -0
  138. data/test/stripe/customer_balance_transaction_test.rb +37 -0
  139. data/test/stripe/customer_card_test.rb +13 -17
  140. data/test/stripe/customer_test.rb +161 -49
  141. data/test/stripe/dispute_test.rb +19 -8
  142. data/test/stripe/ephemeral_key_test.rb +23 -14
  143. data/test/stripe/errors_test.rb +32 -9
  144. data/test/stripe/exchange_rate_test.rb +20 -0
  145. data/test/stripe/file_link_test.rb +41 -0
  146. data/test/stripe/file_test.rb +87 -0
  147. data/test/stripe/instrumentation_test.rb +74 -0
  148. data/test/stripe/invoice_item_test.rb +31 -18
  149. data/test/stripe/invoice_line_item_test.rb +3 -1
  150. data/test/stripe/invoice_test.rb +158 -39
  151. data/test/stripe/issuing/authorization_test.rb +72 -0
  152. data/test/stripe/issuing/card_test.rb +62 -0
  153. data/test/stripe/issuing/cardholder_test.rb +53 -0
  154. data/test/stripe/issuing/dispute_test.rb +45 -0
  155. data/test/stripe/issuing/transaction_test.rb +48 -0
  156. data/test/stripe/list_object_test.rb +120 -88
  157. data/test/stripe/login_link_test.rb +16 -14
  158. data/test/stripe/mandate_test.rb +14 -0
  159. data/test/stripe/multipart_encoder_test.rb +130 -0
  160. data/test/stripe/oauth_test.rb +69 -50
  161. data/test/stripe/order_return_test.rb +7 -5
  162. data/test/stripe/order_test.rb +39 -14
  163. data/test/stripe/payment_intent_test.rb +107 -0
  164. data/test/stripe/payment_method_test.rb +84 -0
  165. data/test/stripe/payout_test.rb +18 -9
  166. data/test/stripe/person_test.rb +46 -0
  167. data/test/stripe/plan_test.rb +67 -19
  168. data/test/stripe/product_test.rb +28 -14
  169. data/test/stripe/radar/early_fraud_warning_test.rb +22 -0
  170. data/test/stripe/radar/value_list_item_test.rb +48 -0
  171. data/test/stripe/radar/value_list_test.rb +61 -0
  172. data/test/stripe/recipient_test.rb +27 -13
  173. data/test/stripe/refund_test.rb +11 -9
  174. data/test/stripe/reporting/report_run_test.rb +33 -0
  175. data/test/stripe/reporting/report_type_test.rb +22 -0
  176. data/test/stripe/reversal_test.rb +12 -10
  177. data/test/stripe/review_test.rb +27 -0
  178. data/test/stripe/setup_intent_test.rb +84 -0
  179. data/test/stripe/sigma/scheduled_query_run_test.rb +22 -0
  180. data/test/stripe/sku_test.rb +24 -12
  181. data/test/stripe/source_test.rb +70 -19
  182. data/test/stripe/stripe_client_test.rb +867 -326
  183. data/test/stripe/stripe_object_test.rb +284 -182
  184. data/test/stripe/stripe_response_test.rb +73 -24
  185. data/test/stripe/subscription_item_test.rb +47 -15
  186. data/test/stripe/subscription_schedule_test.rb +82 -0
  187. data/test/stripe/subscription_test.rb +41 -19
  188. data/test/stripe/tax_id_test.rb +31 -0
  189. data/test/stripe/tax_rate_test.rb +43 -0
  190. data/test/stripe/terminal/connection_token_test.rb +16 -0
  191. data/test/stripe/terminal/location_test.rb +68 -0
  192. data/test/stripe/terminal/reader_test.rb +62 -0
  193. data/test/stripe/three_d_secure_test.rb +4 -2
  194. data/test/stripe/topup_test.rb +62 -0
  195. data/test/stripe/transfer_test.rb +55 -8
  196. data/test/stripe/usage_record_summary_test.rb +29 -0
  197. data/test/stripe/util_test.rb +173 -84
  198. data/test/stripe/webhook_endpoint_test.rb +59 -0
  199. data/test/stripe/webhook_test.rb +21 -17
  200. data/test/stripe_mock.rb +78 -0
  201. data/test/stripe_test.rb +6 -15
  202. data/test/test_data.rb +28 -26
  203. data/test/test_helper.rb +48 -29
  204. metadata +183 -70
  205. data/lib/stripe/alipay_account.rb +0 -22
  206. data/lib/stripe/application_fee.rb +0 -22
  207. data/lib/stripe/application_fee_refund.rb +0 -20
  208. data/lib/stripe/bank_account.rb +0 -30
  209. data/lib/stripe/bitcoin_transaction.rb +0 -11
  210. data/lib/stripe/card.rb +0 -27
  211. data/lib/stripe/charge.rb +0 -82
  212. data/lib/stripe/customer.rb +0 -79
  213. data/lib/stripe/dispute.rb +0 -17
  214. data/lib/stripe/ephemeral_key.rb +0 -18
  215. data/lib/stripe/file_upload.rb +0 -33
  216. data/lib/stripe/invoice.rb +0 -29
  217. data/lib/stripe/login_link.rb +0 -9
  218. data/lib/stripe/order.rb +0 -29
  219. data/lib/stripe/payout.rb +0 -18
  220. data/lib/stripe/recipient_transfer.rb +0 -6
  221. data/lib/stripe/reversal.rb +0 -20
  222. data/lib/stripe/source.rb +0 -23
  223. data/lib/stripe/subscription.rb +0 -33
  224. data/lib/stripe/subscription_item.rb +0 -14
  225. data/lib/stripe/transfer.rb +0 -18
  226. data/test/api_stub_helpers.rb +0 -0
  227. data/test/stripe/bitcoin_receiver_test.rb +0 -67
  228. data/test/stripe/bitcoin_transaction_test.rb +0 -19
  229. data/test/stripe/file_upload_test.rb +0 -66
  230. data/test/stripe/recipient_card_test.rb +0 -44
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  module APIOperations
3
5
  module Save
@@ -14,9 +16,9 @@ module Stripe
14
16
  # object values) to be added to the request. E.g. to allow for an
15
17
  # idempotency_key to be passed in the request headers, or for the
16
18
  # api_key to be overwritten. See {APIOperations::Request.request}.
17
- def update(id, params={}, opts={})
18
- params.each do |k, v|
19
- if self.protected_fields.include?(k)
19
+ def update(id, params = {}, opts = {})
20
+ params.each_key do |k|
21
+ if protected_fields.include?(k)
20
22
  raise ArgumentError, "Cannot update protected field: #{k}"
21
23
  end
22
24
  end
@@ -42,7 +44,7 @@ module Stripe
42
44
  # object values) to be added to the request. E.g. to allow for an
43
45
  # idempotency_key to be passed in the request headers, or for the
44
46
  # api_key to be overwritten. See {APIOperations::Request.request}.
45
- def save(params={}, opts={})
47
+ def save(params = {}, opts = {})
46
48
  # We started unintentionally (sort of) allowing attributes sent to
47
49
  # +save+ to override values used during the update. So as not to break
48
50
  # the API, this makes that official here.
@@ -51,7 +53,7 @@ module Stripe
51
53
  # Now remove any parameters that look like object attributes.
52
54
  params = params.reject { |k, _| respond_to?(k) }
53
55
 
54
- values = self.serialize_params(self).merge(params)
56
+ values = serialize_params(self).merge(params)
55
57
 
56
58
  # note that id gets removed here our call to #url above has already
57
59
  # generated a uri for this object with an identifier baked in
@@ -62,19 +64,26 @@ module Stripe
62
64
  end
63
65
 
64
66
  def self.included(base)
67
+ # Set `metadata` as additive so that when it's set directly we remember
68
+ # to clear keys that may have been previously set by sending empty
69
+ # values for them.
70
+ #
71
+ # It's possible that not every object with `Save` has `metadata`, but
72
+ # it's a close enough heuristic, and having this option set when there
73
+ # is no `metadata` field is not harmful.
74
+ base.additive_object_param(:metadata)
75
+
65
76
  base.extend(ClassMethods)
66
77
  end
67
78
 
68
- private
69
-
70
- def save_url
79
+ private def save_url
71
80
  # This switch essentially allows us "upsert"-like functionality. If the
72
81
  # API resource doesn't have an ID set (suggesting that it's new) and
73
82
  # its class responds to .create (which comes from
74
83
  # Stripe::APIOperations::Create), then use the URL to create a new
75
84
  # resource. Otherwise, generate a URL based on the object's identifier
76
85
  # for a normal update.
77
- if self[:id] == nil && self.class.respond_to?(:create)
86
+ if self[:id].nil? && self.class.respond_to?(:create)
78
87
  self.class.resource_url
79
88
  else
80
89
  resource_url
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  class APIResource < StripeObject
3
5
  include Stripe::APIOperations::Request
@@ -10,14 +12,18 @@ module Stripe
10
12
  attr_accessor :save_with_parent
11
13
 
12
14
  def self.class_name
13
- self.name.split('::')[-1]
15
+ name.split("::")[-1]
14
16
  end
15
17
 
16
18
  def self.resource_url
17
19
  if self == APIResource
18
- raise NotImplementedError.new('APIResource is an abstract class. You should perform actions on its subclasses (Charge, Customer, etc.)')
20
+ raise NotImplementedError,
21
+ "APIResource is an abstract class. You should perform actions " \
22
+ "on its subclasses (Charge, Customer, etc.)"
19
23
  end
20
- "/v1/#{CGI.escape(class_name.downcase)}s"
24
+ # Namespaces are separated in object names with periods (.) and in URLs
25
+ # with forward slashes (/), so replace the former with the latter.
26
+ "/v1/#{self::OBJECT_NAME.downcase.tr('.', '/')}s"
21
27
  end
22
28
 
23
29
  # A metaprogramming call that specifies that a field of a resource can be
@@ -38,17 +44,50 @@ module Stripe
38
44
  # Note that the value may be subresource, but could also be a scalar
39
45
  # (like a tokenized card's ID for example), so we check the type before
40
46
  # setting #save_with_parent here.
41
- if value.is_a?(APIResource)
42
- value.save_with_parent = true
43
- end
47
+ value.save_with_parent = true if value.is_a?(APIResource)
44
48
 
45
49
  value
46
50
  end
47
51
  end
48
52
 
53
+ # Adds a custom method to a resource class. This is used to add support for
54
+ # non-CRUDL API requests, e.g. capturing charges. custom_method takes the
55
+ # following parameters:
56
+ # - name: the name of the custom method to create (as a symbol)
57
+ # - http_verb: the HTTP verb for the API request (:get, :post, or :delete)
58
+ # - http_path: the path to append to the resource's URL. If not provided,
59
+ # the name is used as the path
60
+ #
61
+ # For example, this call:
62
+ # custom_method :capture, http_verb: post
63
+ # adds a `capture` class method to the resource class that, when called,
64
+ # will send a POST request to `/v1/<object_name>/capture`.
65
+ def self.custom_method(name, http_verb:, http_path: nil)
66
+ unless %i[get post delete].include?(http_verb)
67
+ raise ArgumentError,
68
+ "Invalid http_verb value: #{http_verb.inspect}. Should be one " \
69
+ "of :get, :post or :delete."
70
+ end
71
+ http_path ||= name.to_s
72
+ define_singleton_method(name) do |id, params = {}, opts = {}|
73
+ unless id.is_a?(String)
74
+ raise ArgumentError,
75
+ "id should be a string representing the ID of an API resource"
76
+ end
77
+
78
+ url = "#{resource_url}/#{CGI.escape(id)}/#{CGI.escape(http_path)}"
79
+ resp, opts = request(http_verb, url, params, opts)
80
+ Util.convert_to_stripe_object(resp.data, opts)
81
+ end
82
+ end
83
+
49
84
  def resource_url
50
- unless id = self['id']
51
- raise InvalidRequestError.new("Could not determine which URL to request: #{self.class} instance has invalid ID: #{id.inspect}", 'id')
85
+ unless (id = self["id"])
86
+ raise InvalidRequestError.new(
87
+ "Could not determine which URL to request: #{self.class} instance " \
88
+ "has invalid ID: #{id.inspect}",
89
+ "id"
90
+ )
52
91
  end
53
92
  "#{self.class.resource_url}/#{CGI.escape(id)}"
54
93
  end
@@ -58,11 +97,22 @@ module Stripe
58
97
  initialize_from(resp.data, opts)
59
98
  end
60
99
 
61
- def self.retrieve(id, opts={})
100
+ def self.retrieve(id, opts = {})
62
101
  opts = Util.normalize_opts(opts)
63
- instance = self.new(id, opts)
102
+ instance = new(id, opts)
64
103
  instance.refresh
65
104
  instance
66
105
  end
106
+
107
+ protected def request_stripe_object(method:, path:, params:, opts: {})
108
+ resp, opts = request(method, path, params, opts)
109
+
110
+ # If we're getting back this thing, update; otherwise, instantiate.
111
+ if Util.object_name_matches_class?(resp.data[:object], self.class)
112
+ initialize_from(resp.data, opts)
113
+ else
114
+ Util.convert_to_stripe_object(resp.data, opts)
115
+ end
116
+ end
67
117
  end
68
118
  end
@@ -0,0 +1,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ # Manages connections across multiple hosts which is useful because the
5
+ # library may connect to multiple hosts during a typical session (main API,
6
+ # Connect, Uploads). Ruby doesn't provide an easy way to make this happen
7
+ # easily, so this class is designed to track what we're connected to and
8
+ # manage the lifecycle of those connections.
9
+ #
10
+ # Note that this class in itself is *not* thread safe. We expect it to be
11
+ # instantiated once per thread.
12
+ class ConnectionManager
13
+ # Timestamp (in seconds procured from the system's monotonic clock)
14
+ # indicating when the connection manager last made a request. This is used
15
+ # by `StripeClient` to determine whether a connection manager should be
16
+ # garbage collected or not.
17
+ attr_reader :last_used
18
+
19
+ def initialize
20
+ @active_connections = {}
21
+ @last_used = Util.monotonic_time
22
+
23
+ # A connection manager may be accessed across threads as one thread makes
24
+ # requests on it while another is trying to clear it (either because it's
25
+ # trying to garbage collect the manager or trying to clear it because a
26
+ # configuration setting has changed). That's probably thread-safe already
27
+ # because of Ruby's GIL, but just in case the library's running on JRuby
28
+ # or the like, use a mutex to synchronize access in this connection
29
+ # manager.
30
+ @mutex = Mutex.new
31
+ end
32
+
33
+ # Finishes any active connections by closing their TCP connection and
34
+ # clears them from internal tracking.
35
+ def clear
36
+ @mutex.synchronize do
37
+ @active_connections.each do |_, connection|
38
+ connection.finish
39
+ end
40
+ @active_connections = {}
41
+ end
42
+ end
43
+
44
+ # Gets a connection for a given URI. This is for internal use only as it's
45
+ # subject to change (we've moved between HTTP client schemes in the past
46
+ # and may do it again).
47
+ #
48
+ # `uri` is expected to be a string.
49
+ def connection_for(uri)
50
+ @mutex.synchronize do
51
+ u = URI.parse(uri)
52
+ connection = @active_connections[[u.host, u.port]]
53
+
54
+ if connection.nil?
55
+ connection = create_connection(u)
56
+ connection.start
57
+
58
+ @active_connections[[u.host, u.port]] = connection
59
+ end
60
+
61
+ connection
62
+ end
63
+ end
64
+
65
+ # Executes an HTTP request to the given URI with the given method. Also
66
+ # allows a request body, headers, and query string to be specified.
67
+ def execute_request(method, uri, body: nil, headers: nil, query: nil)
68
+ # Perform some basic argument validation because it's easy to get
69
+ # confused between strings and hashes for things like body and query
70
+ # parameters.
71
+ raise ArgumentError, "method should be a symbol" \
72
+ unless method.is_a?(Symbol)
73
+ raise ArgumentError, "uri should be a string" \
74
+ unless uri.is_a?(String)
75
+ raise ArgumentError, "body should be a string" \
76
+ if body && !body.is_a?(String)
77
+ raise ArgumentError, "headers should be a hash" \
78
+ if headers && !headers.is_a?(Hash)
79
+ raise ArgumentError, "query should be a string" \
80
+ if query && !query.is_a?(String)
81
+
82
+ @last_used = Util.monotonic_time
83
+
84
+ connection = connection_for(uri)
85
+
86
+ u = URI.parse(uri)
87
+ path = if query
88
+ u.path + "?" + query
89
+ else
90
+ u.path
91
+ end
92
+
93
+ @mutex.synchronize do
94
+ connection.send_request(method.to_s.upcase, path, body, headers)
95
+ end
96
+ end
97
+
98
+ #
99
+ # private
100
+ #
101
+
102
+ # `uri` should be a parsed `URI` object.
103
+ private def create_connection(uri)
104
+ # These all come back as `nil` if no proxy is configured.
105
+ proxy_host, proxy_port, proxy_user, proxy_pass = proxy_parts
106
+
107
+ connection = Net::HTTP.new(uri.host, uri.port,
108
+ proxy_host, proxy_port,
109
+ proxy_user, proxy_pass)
110
+
111
+ # Time in seconds within which Net::HTTP will try to reuse an already
112
+ # open connection when issuing a new operation. Outside this window, Ruby
113
+ # will transparently close and re-open the connection without trying to
114
+ # reuse it.
115
+ #
116
+ # Ruby's default of 2 seconds is almost certainly too short. Here I've
117
+ # reused Go's default for `DefaultTransport`.
118
+ connection.keep_alive_timeout = 30
119
+
120
+ connection.open_timeout = Stripe.open_timeout
121
+ connection.read_timeout = Stripe.read_timeout
122
+
123
+ connection.use_ssl = uri.scheme == "https"
124
+
125
+ if Stripe.verify_ssl_certs
126
+ connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
127
+ connection.cert_store = Stripe.ca_store
128
+ else
129
+ connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
130
+ warn_ssl_verify_none
131
+ end
132
+
133
+ connection
134
+ end
135
+
136
+ # `Net::HTTP` somewhat awkwardly requires each component of a proxy URI
137
+ # (host, port, etc.) rather than the URI itself. This method simply parses
138
+ # out those pieces to make passing them into a new connection a little less
139
+ # ugly.
140
+ private def proxy_parts
141
+ if Stripe.proxy.nil?
142
+ [nil, nil, nil, nil]
143
+ else
144
+ u = URI.parse(Stripe.proxy)
145
+ [u.host, u.port, u.user, u.password]
146
+ end
147
+ end
148
+
149
+ private def warn_ssl_verify_none
150
+ return if @verify_ssl_warned
151
+
152
+ @verify_ssl_warned = true
153
+ warn("WARNING: Running without SSL cert verification. " \
154
+ "You should never do this in production. " \
155
+ "Execute `Stripe.verify_ssl_certs = true` to enable " \
156
+ "verification.")
157
+ end
158
+ end
159
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ # Represents an error object as returned by the API.
5
+ #
6
+ # @see https://stripe.com/docs/api/errors
7
+ class ErrorObject < StripeObject
8
+ # Unlike other objects, we explicitly declare getter methods here. This
9
+ # is because the API doesn't return `null` values for fields on this
10
+ # object, rather the fields are omitted entirely. Not declaring the getter
11
+ # methods would cause users to run into `NoMethodError` exceptions and
12
+ # get in the way of generic error handling.
13
+
14
+ # For card errors, the ID of the failed charge.
15
+ def charge
16
+ @values[:charge]
17
+ end
18
+
19
+ # For some errors that could be handled programmatically, a short string
20
+ # indicating the error code reported.
21
+ def code
22
+ @values[:code]
23
+ end
24
+
25
+ # For card errors resulting from a card issuer decline, a short string
26
+ # indicating the card issuer's reason for the decline if they provide one.
27
+ def decline_code
28
+ @values[:decline_code]
29
+ end
30
+
31
+ # A URL to more information about the error code reported.
32
+ def doc_url
33
+ @values[:doc_url]
34
+ end
35
+
36
+ # A human-readable message providing more details about the error. For card
37
+ # errors, these messages can be shown to your users.
38
+ def message
39
+ @values[:message]
40
+ end
41
+
42
+ # If the error is parameter-specific, the parameter related to the error.
43
+ # For example, you can use this to display a message near the correct form
44
+ # field.
45
+ def param
46
+ @values[:param]
47
+ end
48
+
49
+ # The PaymentIntent object for errors returned on a request involving a
50
+ # PaymentIntent.
51
+ def payment_intent
52
+ @values[:payment_intent]
53
+ end
54
+
55
+ # The PaymentMethod object for errors returned on a request involving a
56
+ # PaymentMethod.
57
+ def payment_method
58
+ @values[:payment_method]
59
+ end
60
+
61
+ # The SetupIntent object for errors returned on a request involving a
62
+ # SetupIntent.
63
+ def setup_intent
64
+ @values[:setup_intent]
65
+ end
66
+
67
+ # The source object for errors returned on a request involving a source.
68
+ def source
69
+ @values[:source]
70
+ end
71
+
72
+ # The type of error returned. One of `api_connection_error`, `api_error`,
73
+ # `authentication_error`, `card_error`, `idempotency_error`,
74
+ # `invalid_request_error`, or `rate_limit_error`.
75
+ def type
76
+ @values[:type]
77
+ end
78
+ end
79
+
80
+ # Represents on OAuth error returned by the OAuth API.
81
+ #
82
+ # @see https://stripe.com/docs/connect/oauth-reference#post-token-errors
83
+ class OAuthErrorObject < StripeObject
84
+ # A unique error code per error type.
85
+ def error
86
+ @values[:error]
87
+ end
88
+
89
+ # A human readable description of the error.
90
+ def error_description
91
+ @values[:error_description]
92
+ end
93
+ end
94
+ end
data/lib/stripe/errors.rb CHANGED
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  # StripeError is the base error from which all other more specific Stripe
3
5
  # errors derive.
@@ -8,8 +10,8 @@ module Stripe
8
10
  # about the response that conveyed the error.
9
11
  attr_accessor :response
10
12
 
11
- # These fields are now available as part of #response and that usage should
12
- # be preferred.
13
+ attr_reader :code
14
+ attr_reader :error
13
15
  attr_reader :http_body
14
16
  attr_reader :http_headers
15
17
  attr_reader :http_status
@@ -17,14 +19,22 @@ module Stripe
17
19
  attr_reader :request_id
18
20
 
19
21
  # Initializes a StripeError.
20
- def initialize(message=nil, http_status: nil, http_body: nil, json_body: nil,
21
- http_headers: nil)
22
+ def initialize(message = nil, http_status: nil, http_body: nil,
23
+ json_body: nil, http_headers: nil, code: nil)
22
24
  @message = message
23
25
  @http_status = http_status
24
26
  @http_body = http_body
25
27
  @http_headers = http_headers || {}
26
28
  @json_body = json_body
27
- @request_id = @http_headers[:request_id]
29
+ @code = code
30
+ @request_id = @http_headers["request-id"]
31
+ @error = construct_error_object
32
+ end
33
+
34
+ def construct_error_object
35
+ return nil if @json_body.nil? || !@json_body.key?(:error)
36
+
37
+ ErrorObject.construct_from(@json_body[:error])
28
38
  end
29
39
 
30
40
  def to_s
@@ -55,26 +65,32 @@ module Stripe
55
65
  # CardError is raised when a user enters a card that can't be charged for
56
66
  # some reason.
57
67
  class CardError < StripeError
58
- attr_reader :param, :code
68
+ attr_reader :param
59
69
 
60
- def initialize(message, param, code, http_status: nil, http_body: nil, json_body: nil,
61
- http_headers: nil)
70
+ def initialize(message, param, code: nil, http_status: nil, http_body: nil,
71
+ json_body: nil, http_headers: nil)
62
72
  super(message, http_status: http_status, http_body: http_body,
63
- json_body: json_body, http_headers: http_headers)
73
+ json_body: json_body, http_headers: http_headers,
74
+ code: code)
64
75
  @param = param
65
- @code = code
66
76
  end
67
77
  end
68
78
 
79
+ # IdempotencyError is raised in cases where an idempotency key was used
80
+ # improperly.
81
+ class IdempotencyError < StripeError
82
+ end
83
+
69
84
  # InvalidRequestError is raised when a request is initiated with invalid
70
85
  # parameters.
71
86
  class InvalidRequestError < StripeError
72
87
  attr_accessor :param
73
88
 
74
- def initialize(message, param, http_status: nil, http_body: nil, json_body: nil,
75
- http_headers: nil)
89
+ def initialize(message, param, http_status: nil, http_body: nil,
90
+ json_body: nil, http_headers: nil, code: nil)
76
91
  super(message, http_status: http_status, http_body: http_body,
77
- json_body: json_body, http_headers: http_headers)
92
+ json_body: json_body, http_headers: http_headers,
93
+ code: code)
78
94
  @param = param
79
95
  end
80
96
  end
@@ -104,13 +120,17 @@ module Stripe
104
120
  module OAuth
105
121
  # OAuthError is raised when the OAuth API returns an error.
106
122
  class OAuthError < StripeError
107
- attr_accessor :code
108
-
109
- def initialize(code, description, http_status: nil, http_body: nil, json_body: nil,
110
- http_headers: nil)
123
+ def initialize(code, description, http_status: nil, http_body: nil,
124
+ json_body: nil, http_headers: nil)
111
125
  super(description, http_status: http_status, http_body: http_body,
112
- json_body: json_body, http_headers: http_headers)
113
- @code = code
126
+ json_body: json_body, http_headers: http_headers,
127
+ code: code)
128
+ end
129
+
130
+ def construct_error_object
131
+ return nil if @json_body.nil?
132
+
133
+ OAuthErrorObject.construct_from(@json_body)
114
134
  end
115
135
  end
116
136
 
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ class Instrumentation
5
+ # Event emitted on `request_begin` callback.
6
+ class RequestBeginEvent
7
+ attr_reader :method
8
+ attr_reader :path
9
+
10
+ # Arbitrary user-provided data in the form of a Ruby hash that's passed
11
+ # from subscribers on `request_begin` to subscribers on `request_end`.
12
+ # `request_begin` subscribers can set keys which will then be available
13
+ # in `request_end`.
14
+ #
15
+ # Note that all subscribers of `request_begin` share the same object, so
16
+ # they must be careful to set unique keys so as to not conflict with data
17
+ # set by other subscribers.
18
+ attr_reader :user_data
19
+
20
+ def initialize(method:, path:, user_data:)
21
+ @method = method
22
+ @path = path
23
+ @user_data = user_data
24
+ freeze
25
+ end
26
+ end
27
+
28
+ # Event emitted on `request_end` callback.
29
+ class RequestEndEvent
30
+ attr_reader :duration
31
+ attr_reader :http_status
32
+ attr_reader :method
33
+ attr_reader :num_retries
34
+ attr_reader :path
35
+
36
+ # Arbitrary user-provided data in the form of a Ruby hash that's passed
37
+ # from subscribers on `request_begin` to subscribers on `request_end`.
38
+ # `request_begin` subscribers can set keys which will then be available
39
+ # in `request_end`.
40
+ attr_reader :user_data
41
+
42
+ def initialize(duration:, http_status:, method:, num_retries:, path:,
43
+ user_data: nil)
44
+ @duration = duration
45
+ @http_status = http_status
46
+ @method = method
47
+ @num_retries = num_retries
48
+ @path = path
49
+ @user_data = user_data
50
+ freeze
51
+ end
52
+ end
53
+
54
+ # This class was renamed for consistency. This alias is here for backwards
55
+ # compatibility.
56
+ RequestEvent = RequestEndEvent
57
+
58
+ # Returns true if there are a non-zero number of subscribers on the given
59
+ # topic, and false otherwise.
60
+ def self.any_subscribers?(topic)
61
+ !subscribers[topic].empty?
62
+ end
63
+
64
+ def self.subscribe(topic, name = rand, &block)
65
+ subscribers[topic][name] = block
66
+ name
67
+ end
68
+
69
+ def self.unsubscribe(topic, name)
70
+ subscribers[topic].delete(name)
71
+ end
72
+
73
+ def self.notify(topic, event)
74
+ subscribers[topic].each_value { |subscriber| subscriber.call(event) }
75
+ end
76
+
77
+ def self.subscribers
78
+ @subscribers ||= Hash.new { |hash, key| hash[key] = {} }
79
+ end
80
+ private_class_method :subscribers
81
+ end
82
+ end