stripe 4.21.3 → 5.52.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (226) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +254 -1
  3. data/CODE_OF_CONDUCT.md +77 -0
  4. data/Gemfile +10 -16
  5. data/Makefile +7 -0
  6. data/README.md +115 -47
  7. data/Rakefile +8 -7
  8. data/VERSION +1 -1
  9. data/lib/stripe/api_operations/create.rb +1 -1
  10. data/lib/stripe/api_operations/delete.rb +7 -3
  11. data/lib/stripe/api_operations/list.rb +1 -12
  12. data/lib/stripe/api_operations/nested_resource.rb +29 -26
  13. data/lib/stripe/api_operations/request.rb +82 -6
  14. data/lib/stripe/api_operations/save.rb +7 -4
  15. data/lib/stripe/api_operations/search.rb +19 -0
  16. data/lib/stripe/api_resource.rb +22 -17
  17. data/lib/stripe/api_resource_test_helpers.rb +47 -0
  18. data/lib/stripe/connection_manager.rb +200 -0
  19. data/lib/stripe/error_object.rb +93 -0
  20. data/lib/stripe/errors.rb +24 -3
  21. data/lib/stripe/instrumentation.rb +84 -0
  22. data/lib/stripe/list_object.rb +34 -5
  23. data/lib/stripe/multipart_encoder.rb +131 -0
  24. data/lib/stripe/oauth.rb +8 -6
  25. data/lib/stripe/object_types.rb +20 -5
  26. data/lib/stripe/resources/account.rb +12 -16
  27. data/lib/stripe/resources/account_link.rb +2 -1
  28. data/lib/stripe/resources/alipay_account.rb +1 -1
  29. data/lib/stripe/resources/apple_pay_domain.rb +2 -1
  30. data/lib/stripe/resources/application_fee.rb +2 -12
  31. data/lib/stripe/resources/application_fee_refund.rb +3 -2
  32. data/lib/stripe/resources/balance.rb +2 -1
  33. data/lib/stripe/resources/balance_transaction.rb +2 -5
  34. data/lib/stripe/resources/bank_account.rb +3 -2
  35. data/lib/stripe/resources/billing_portal/configuration.rb +14 -0
  36. data/lib/stripe/resources/billing_portal/session.rb +12 -0
  37. data/lib/stripe/resources/bitcoin_receiver.rb +2 -1
  38. data/lib/stripe/resources/bitcoin_transaction.rb +4 -3
  39. data/lib/stripe/resources/capability.rb +3 -2
  40. data/lib/stripe/resources/card.rb +2 -1
  41. data/lib/stripe/resources/charge.rb +13 -65
  42. data/lib/stripe/resources/checkout/session.rb +17 -1
  43. data/lib/stripe/resources/country_spec.rb +2 -1
  44. data/lib/stripe/resources/coupon.rb +2 -1
  45. data/lib/stripe/resources/credit_note.rb +18 -3
  46. data/lib/stripe/resources/credit_note_line_item.rb +8 -0
  47. data/lib/stripe/resources/customer.rb +35 -59
  48. data/lib/stripe/resources/customer_balance_transaction.rb +4 -3
  49. data/lib/stripe/resources/discount.rb +2 -1
  50. data/lib/stripe/resources/dispute.rb +8 -9
  51. data/lib/stripe/resources/ephemeral_key.rb +2 -1
  52. data/lib/stripe/resources/event.rb +2 -1
  53. data/lib/stripe/resources/exchange_rate.rb +2 -1
  54. data/lib/stripe/resources/file.rb +6 -14
  55. data/lib/stripe/resources/file_link.rb +2 -1
  56. data/lib/stripe/resources/funding_instructions.rb +16 -0
  57. data/lib/stripe/resources/identity/verification_report.rb +12 -0
  58. data/lib/stripe/resources/identity/verification_session.rb +35 -0
  59. data/lib/stripe/resources/invoice.rb +47 -12
  60. data/lib/stripe/resources/invoice_item.rb +2 -1
  61. data/lib/stripe/resources/invoice_line_item.rb +2 -1
  62. data/lib/stripe/resources/issuing/authorization.rb +14 -5
  63. data/lib/stripe/resources/issuing/card.rb +8 -3
  64. data/lib/stripe/resources/issuing/card_details.rb +3 -2
  65. data/lib/stripe/resources/issuing/cardholder.rb +2 -1
  66. data/lib/stripe/resources/issuing/dispute.rb +13 -1
  67. data/lib/stripe/resources/issuing/transaction.rb +2 -1
  68. data/lib/stripe/resources/line_item.rb +8 -0
  69. data/lib/stripe/resources/login_link.rb +2 -1
  70. data/lib/stripe/resources/mandate.rb +8 -0
  71. data/lib/stripe/resources/order.rb +14 -13
  72. data/lib/stripe/resources/order_return.rb +2 -1
  73. data/lib/stripe/resources/payment_intent.rb +59 -7
  74. data/lib/stripe/resources/payment_link.rb +23 -0
  75. data/lib/stripe/resources/payment_method.rb +14 -5
  76. data/lib/stripe/resources/payout.rb +16 -7
  77. data/lib/stripe/resources/person.rb +2 -1
  78. data/lib/stripe/resources/plan.rb +2 -1
  79. data/lib/stripe/resources/price.rb +21 -0
  80. data/lib/stripe/resources/product.rb +11 -1
  81. data/lib/stripe/resources/promotion_code.rb +12 -0
  82. data/lib/stripe/resources/quote.rb +105 -0
  83. data/lib/stripe/resources/radar/early_fraud_warning.rb +2 -1
  84. data/lib/stripe/resources/radar/value_list.rb +2 -1
  85. data/lib/stripe/resources/radar/value_list_item.rb +2 -1
  86. data/lib/stripe/resources/recipient.rb +2 -5
  87. data/lib/stripe/resources/recipient_transfer.rb +1 -1
  88. data/lib/stripe/resources/refund.rb +13 -1
  89. data/lib/stripe/resources/reporting/report_run.rb +2 -1
  90. data/lib/stripe/resources/reporting/report_type.rb +2 -1
  91. data/lib/stripe/resources/reversal.rb +4 -3
  92. data/lib/stripe/resources/review.rb +8 -3
  93. data/lib/stripe/resources/setup_attempt.rb +10 -0
  94. data/lib/stripe/resources/setup_intent.rb +24 -5
  95. data/lib/stripe/resources/shipping_rate.rb +12 -0
  96. data/lib/stripe/resources/sigma/scheduled_query_run.rb +2 -1
  97. data/lib/stripe/resources/sku.rb +2 -1
  98. data/lib/stripe/resources/source.rb +17 -12
  99. data/lib/stripe/resources/source_transaction.rb +2 -1
  100. data/lib/stripe/resources/subscription.rb +16 -6
  101. data/lib/stripe/resources/subscription_item.rb +11 -2
  102. data/lib/stripe/resources/subscription_schedule.rb +14 -13
  103. data/lib/stripe/resources/tax_code.rb +10 -0
  104. data/lib/stripe/resources/tax_id.rb +2 -1
  105. data/lib/stripe/resources/tax_rate.rb +2 -1
  106. data/lib/stripe/resources/terminal/configuration.rb +15 -0
  107. data/lib/stripe/resources/terminal/connection_token.rb +2 -1
  108. data/lib/stripe/resources/terminal/location.rb +2 -1
  109. data/lib/stripe/resources/terminal/reader.rb +62 -1
  110. data/lib/stripe/resources/test_helpers/test_clock.rb +25 -0
  111. data/lib/stripe/resources/three_d_secure.rb +2 -1
  112. data/lib/stripe/resources/token.rb +2 -1
  113. data/lib/stripe/resources/topup.rb +8 -3
  114. data/lib/stripe/resources/transfer.rb +8 -8
  115. data/lib/stripe/resources/usage_record.rb +2 -17
  116. data/lib/stripe/resources/usage_record_summary.rb +2 -1
  117. data/lib/stripe/resources/webhook_endpoint.rb +2 -1
  118. data/lib/stripe/resources.rb +18 -2
  119. data/lib/stripe/search_result_object.rb +86 -0
  120. data/lib/stripe/stripe_client.rb +617 -243
  121. data/lib/stripe/stripe_configuration.rb +194 -0
  122. data/lib/stripe/stripe_object.rb +30 -25
  123. data/lib/stripe/stripe_response.rb +87 -27
  124. data/lib/stripe/util.rb +88 -18
  125. data/lib/stripe/version.rb +1 -1
  126. data/lib/stripe/webhook.rb +39 -8
  127. data/lib/stripe.rb +43 -131
  128. data/stripe.gemspec +17 -13
  129. metadata +36 -220
  130. data/.editorconfig +0 -10
  131. data/.gitattributes +0 -4
  132. data/.github/ISSUE_TEMPLATE.md +0 -5
  133. data/.gitignore +0 -8
  134. data/.rubocop.yml +0 -43
  135. data/.rubocop_todo.yml +0 -38
  136. data/.travis.yml +0 -43
  137. data/.vscode/extensions.json +0 -7
  138. data/.vscode/settings.json +0 -8
  139. data/lib/stripe/resources/issuer_fraud_record.rb +0 -9
  140. data/lib/stripe/resources/subscription_schedule_revision.rb +0 -34
  141. data/test/api_stub_helpers.rb +0 -1
  142. data/test/openapi/README.md +0 -9
  143. data/test/stripe/account_link_test.rb +0 -18
  144. data/test/stripe/account_test.rb +0 -428
  145. data/test/stripe/alipay_account_test.rb +0 -37
  146. data/test/stripe/api_operations_test.rb +0 -80
  147. data/test/stripe/api_resource_test.rb +0 -544
  148. data/test/stripe/apple_pay_domain_test.rb +0 -46
  149. data/test/stripe/application_fee_refund_test.rb +0 -37
  150. data/test/stripe/application_fee_test.rb +0 -58
  151. data/test/stripe/balance_test.rb +0 -13
  152. data/test/stripe/bank_account_test.rb +0 -36
  153. data/test/stripe/capability_test.rb +0 -45
  154. data/test/stripe/charge_test.rb +0 -80
  155. data/test/stripe/checkout/session_test.rb +0 -41
  156. data/test/stripe/country_spec_test.rb +0 -20
  157. data/test/stripe/coupon_test.rb +0 -61
  158. data/test/stripe/credit_note_test.rb +0 -61
  159. data/test/stripe/customer_balance_transaction_test.rb +0 -37
  160. data/test/stripe/customer_card_test.rb +0 -42
  161. data/test/stripe/customer_test.rb +0 -269
  162. data/test/stripe/dispute_test.rb +0 -51
  163. data/test/stripe/ephemeral_key_test.rb +0 -93
  164. data/test/stripe/errors_test.rb +0 -20
  165. data/test/stripe/exchange_rate_test.rb +0 -20
  166. data/test/stripe/file_link_test.rb +0 -41
  167. data/test/stripe/file_test.rb +0 -97
  168. data/test/stripe/file_upload_test.rb +0 -79
  169. data/test/stripe/invoice_item_test.rb +0 -66
  170. data/test/stripe/invoice_line_item_test.rb +0 -8
  171. data/test/stripe/invoice_test.rb +0 -213
  172. data/test/stripe/issuer_fraud_record_test.rb +0 -20
  173. data/test/stripe/issuing/authorization_test.rb +0 -72
  174. data/test/stripe/issuing/card_test.rb +0 -62
  175. data/test/stripe/issuing/cardholder_test.rb +0 -53
  176. data/test/stripe/issuing/dispute_test.rb +0 -45
  177. data/test/stripe/issuing/transaction_test.rb +0 -48
  178. data/test/stripe/list_object_test.rb +0 -156
  179. data/test/stripe/login_link_test.rb +0 -37
  180. data/test/stripe/oauth_test.rb +0 -88
  181. data/test/stripe/order_return_test.rb +0 -21
  182. data/test/stripe/order_test.rb +0 -82
  183. data/test/stripe/payment_intent_test.rb +0 -107
  184. data/test/stripe/payment_method_test.rb +0 -84
  185. data/test/stripe/payout_test.rb +0 -57
  186. data/test/stripe/person_test.rb +0 -46
  187. data/test/stripe/plan_test.rb +0 -98
  188. data/test/stripe/product_test.rb +0 -59
  189. data/test/stripe/radar/early_fraud_warning_test.rb +0 -22
  190. data/test/stripe/radar/value_list_item_test.rb +0 -48
  191. data/test/stripe/radar/value_list_test.rb +0 -61
  192. data/test/stripe/recipient_test.rb +0 -62
  193. data/test/stripe/refund_test.rb +0 -39
  194. data/test/stripe/reporting/report_run_test.rb +0 -33
  195. data/test/stripe/reporting/report_type_test.rb +0 -22
  196. data/test/stripe/reversal_test.rb +0 -43
  197. data/test/stripe/review_test.rb +0 -27
  198. data/test/stripe/setup_intent_test.rb +0 -84
  199. data/test/stripe/sigma/scheduled_query_run_test.rb +0 -22
  200. data/test/stripe/sku_test.rb +0 -60
  201. data/test/stripe/source_test.rb +0 -99
  202. data/test/stripe/source_transaction_test.rb +0 -19
  203. data/test/stripe/stripe_client_test.rb +0 -842
  204. data/test/stripe/stripe_object_test.rb +0 -525
  205. data/test/stripe/stripe_response_test.rb +0 -49
  206. data/test/stripe/subscription_item_test.rb +0 -63
  207. data/test/stripe/subscription_schedule_revision_test.rb +0 -37
  208. data/test/stripe/subscription_schedule_test.rb +0 -116
  209. data/test/stripe/subscription_test.rb +0 -80
  210. data/test/stripe/tax_id_test.rb +0 -31
  211. data/test/stripe/tax_rate_test.rb +0 -43
  212. data/test/stripe/terminal/connection_token_test.rb +0 -16
  213. data/test/stripe/terminal/location_test.rb +0 -68
  214. data/test/stripe/terminal/reader_test.rb +0 -62
  215. data/test/stripe/three_d_secure_test.rb +0 -23
  216. data/test/stripe/topup_test.rb +0 -62
  217. data/test/stripe/transfer_test.rb +0 -88
  218. data/test/stripe/usage_record_summary_test.rb +0 -19
  219. data/test/stripe/usage_record_test.rb +0 -28
  220. data/test/stripe/util_test.rb +0 -402
  221. data/test/stripe/webhook_endpoint_test.rb +0 -59
  222. data/test/stripe/webhook_test.rb +0 -96
  223. data/test/stripe_mock.rb +0 -77
  224. data/test/stripe_test.rb +0 -63
  225. data/test/test_data.rb +0 -61
  226. data/test/test_helper.rb +0 -71
@@ -63,22 +63,7 @@ module Stripe
63
63
  # adds a `capture` class method to the resource class that, when called,
64
64
  # will send a POST request to `/v1/<object_name>/capture`.
65
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
66
+ Util.custom_method self, self, name, http_verb, http_path
82
67
  end
83
68
 
84
69
  def resource_url
@@ -93,7 +78,8 @@ module Stripe
93
78
  end
94
79
 
95
80
  def refresh
96
- resp, opts = request(:get, resource_url, @retrieve_params)
81
+ resp, opts = execute_resource_request(:get, resource_url,
82
+ @retrieve_params)
97
83
  initialize_from(resp.data, opts)
98
84
  end
99
85
 
@@ -103,5 +89,24 @@ module Stripe
103
89
  instance.refresh
104
90
  instance
105
91
  end
92
+
93
+ def request_stripe_object(method:, path:, params:, opts: {})
94
+ resp, opts = execute_resource_request(method, path, params, opts)
95
+
96
+ # If we're getting back this thing, update; otherwise, instantiate.
97
+ if Util.object_name_matches_class?(resp.data[:object], self.class)
98
+ initialize_from(resp.data, opts)
99
+ else
100
+ Util.convert_to_stripe_object(resp.data, opts)
101
+ end
102
+ end
103
+
104
+ protected def request_stream(method:, path:, params:, opts: {},
105
+ &read_body_chunk_block)
106
+ resp, = execute_resource_request_stream(
107
+ method, path, params, opts, &read_body_chunk_block
108
+ )
109
+ resp
110
+ end
106
111
  end
107
112
  end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ # The base class for nested TestHelpers classes in resource objects.
5
+ # The APIResourceTestHelpers handles URL generation and custom method
6
+ # support for test-helper methods.
7
+ #
8
+ # class MyAPIResource < APIResource
9
+ # class TestHelpers < APIResourceTestHelpers
10
+ class APIResourceTestHelpers
11
+ def initialize(resource)
12
+ @resource = resource
13
+ end
14
+
15
+ # Adds a custom method to a test helper. This is used to add support for
16
+ # non-CRUDL API requests, e.g. capturing charges. custom_method takes the
17
+ # following parameters:
18
+ # - name: the name of the custom method to create (as a symbol)
19
+ # - http_verb: the HTTP verb for the API request (:get, :post, or :delete)
20
+ # - http_path: the path to append to the resource's URL. If not provided,
21
+ # the name is used as the path
22
+ #
23
+ # For example, this call:
24
+ # custom_method :capture, http_verb: post
25
+ # adds a `capture` class method to the resource class that, when called,
26
+ # will send a POST request to `/v1/<object_name>/capture`.
27
+ def self.custom_method(name, http_verb:, http_path: nil)
28
+ Util.custom_method self::RESOURCE_CLASS, self, name, http_verb, http_path
29
+ end
30
+
31
+ def self.resource_url
32
+ "/v1/test_helpers/"\
33
+ "#{self::RESOURCE_CLASS::OBJECT_NAME.downcase.tr('.', '/')}s"
34
+ end
35
+
36
+ def resource_url
37
+ unless (id = @resource["id"])
38
+ raise InvalidRequestError.new(
39
+ "Could not determine which URL to request: #{self.class} instance " \
40
+ "has invalid ID: #{id.inspect}",
41
+ "id"
42
+ )
43
+ end
44
+ "#{self.class.resource_url}/#{CGI.escape(id)}"
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,200 @@
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
+ attr_reader :config
19
+
20
+ def initialize(config = Stripe.config)
21
+ @config = config
22
+ @active_connections = {}
23
+ @last_used = Util.monotonic_time
24
+
25
+ # A connection manager may be accessed across threads as one thread makes
26
+ # requests on it while another is trying to clear it (either because it's
27
+ # trying to garbage collect the manager or trying to clear it because a
28
+ # configuration setting has changed). That's probably thread-safe already
29
+ # because of Ruby's GIL, but just in case the library's running on JRuby
30
+ # or the like, use a mutex to synchronize access in this connection
31
+ # manager.
32
+ @mutex = Mutex.new
33
+ end
34
+
35
+ # Finishes any active connections by closing their TCP connection and
36
+ # clears them from internal tracking.
37
+ def clear
38
+ @mutex.synchronize do
39
+ @active_connections.each do |_, connection|
40
+ connection.finish
41
+ end
42
+ @active_connections = {}
43
+ end
44
+ end
45
+
46
+ # Gets a connection for a given URI. This is for internal use only as it's
47
+ # subject to change (we've moved between HTTP client schemes in the past
48
+ # and may do it again).
49
+ #
50
+ # `uri` is expected to be a string.
51
+ def connection_for(uri)
52
+ @mutex.synchronize do
53
+ u = URI.parse(uri)
54
+ connection = @active_connections[[u.host, u.port]]
55
+
56
+ if connection.nil?
57
+ connection = create_connection(u)
58
+ connection.start
59
+
60
+ @active_connections[[u.host, u.port]] = connection
61
+ end
62
+
63
+ connection
64
+ end
65
+ end
66
+
67
+ # Executes an HTTP request to the given URI with the given method. Also
68
+ # allows a request body, headers, and query string to be specified.
69
+ def execute_request(method, uri, body: nil, headers: nil, query: nil,
70
+ &block)
71
+ # Perform some basic argument validation because it's easy to get
72
+ # confused between strings and hashes for things like body and query
73
+ # parameters.
74
+ raise ArgumentError, "method should be a symbol" \
75
+ unless method.is_a?(Symbol)
76
+ raise ArgumentError, "uri should be a string" \
77
+ unless uri.is_a?(String)
78
+ raise ArgumentError, "body should be a string" \
79
+ if body && !body.is_a?(String)
80
+ raise ArgumentError, "headers should be a hash" \
81
+ if headers && !headers.is_a?(Hash)
82
+ raise ArgumentError, "query should be a string" \
83
+ if query && !query.is_a?(String)
84
+
85
+ @last_used = Util.monotonic_time
86
+
87
+ connection = connection_for(uri)
88
+
89
+ u = URI.parse(uri)
90
+ path = if query
91
+ u.path + "?" + query
92
+ else
93
+ u.path
94
+ end
95
+
96
+ method_name = method.to_s.upcase
97
+ has_response_body = method_name != "HEAD"
98
+ request = Net::HTTPGenericRequest.new(
99
+ method_name,
100
+ (body ? true : false),
101
+ has_response_body,
102
+ path,
103
+ headers
104
+ )
105
+
106
+ Util.log_debug("ConnectionManager starting request",
107
+ method_name: method_name,
108
+ path: path,
109
+ process_id: Process.pid,
110
+ thread_object_id: Thread.current.object_id,
111
+ connection_manager_object_id: object_id,
112
+ connection_object_id: connection.object_id,
113
+ log_timestamp: Util.monotonic_time)
114
+
115
+ resp = @mutex.synchronize do
116
+ # The block parameter is special here. If a block is provided, the block
117
+ # is invoked with the Net::HTTPResponse. However, the body will not have
118
+ # been read yet in the block, and can be streamed by calling
119
+ # HTTPResponse#read_body.
120
+ connection.request(request, body, &block)
121
+ end
122
+
123
+ Util.log_debug("ConnectionManager request complete",
124
+ method_name: method_name,
125
+ path: path,
126
+ process_id: Process.pid,
127
+ thread_object_id: Thread.current.object_id,
128
+ connection_manager_object_id: object_id,
129
+ connection_object_id: connection.object_id,
130
+ response_object_id: resp.object_id,
131
+ log_timestamp: Util.monotonic_time)
132
+
133
+ resp
134
+ end
135
+
136
+ #
137
+ # private
138
+ #
139
+
140
+ # `uri` should be a parsed `URI` object.
141
+ private def create_connection(uri)
142
+ # These all come back as `nil` if no proxy is configured.
143
+ proxy_host, proxy_port, proxy_user, proxy_pass = proxy_parts
144
+
145
+ connection = Net::HTTP.new(uri.host, uri.port,
146
+ proxy_host, proxy_port,
147
+ proxy_user, proxy_pass)
148
+
149
+ # Time in seconds within which Net::HTTP will try to reuse an already
150
+ # open connection when issuing a new operation. Outside this window, Ruby
151
+ # will transparently close and re-open the connection without trying to
152
+ # reuse it.
153
+ #
154
+ # Ruby's default of 2 seconds is almost certainly too short. Here I've
155
+ # reused Go's default for `DefaultTransport`.
156
+ connection.keep_alive_timeout = 30
157
+
158
+ connection.open_timeout = config.open_timeout
159
+ connection.read_timeout = config.read_timeout
160
+ if connection.respond_to?(:write_timeout=)
161
+ connection.write_timeout = config.write_timeout
162
+ end
163
+
164
+ connection.use_ssl = uri.scheme == "https"
165
+
166
+ if config.verify_ssl_certs
167
+ connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
168
+ connection.cert_store = config.ca_store
169
+ else
170
+ connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
171
+ warn_ssl_verify_none
172
+ end
173
+
174
+ connection
175
+ end
176
+
177
+ # `Net::HTTP` somewhat awkwardly requires each component of a proxy URI
178
+ # (host, port, etc.) rather than the URI itself. This method simply parses
179
+ # out those pieces to make passing them into a new connection a little less
180
+ # ugly.
181
+ private def proxy_parts
182
+ if config.proxy.nil?
183
+ [nil, nil, nil, nil]
184
+ else
185
+ u = URI.parse(config.proxy)
186
+ [u.host, u.port, u.user, u.password]
187
+ end
188
+ end
189
+
190
+ private def warn_ssl_verify_none
191
+ return if @verify_ssl_warned
192
+
193
+ @verify_ssl_warned = true
194
+ warn("WARNING: Running without SSL cert verification. " \
195
+ "You should never do this in production. " \
196
+ "Execute `Stripe.verify_ssl_certs = true` to enable " \
197
+ "verification.")
198
+ end
199
+ end
200
+ end
@@ -0,0 +1,93 @@
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_error`, `card_error`,
73
+ # `idempotency_error`, or `invalid_request_error`.
74
+ def type
75
+ @values[:type]
76
+ end
77
+ end
78
+
79
+ # Represents on OAuth error returned by the OAuth API.
80
+ #
81
+ # @see https://stripe.com/docs/connect/oauth-reference#post-token-errors
82
+ class OAuthErrorObject < StripeObject
83
+ # A unique error code per error type.
84
+ def error
85
+ @values[:error]
86
+ end
87
+
88
+ # A human readable description of the error.
89
+ def error_description
90
+ @values[:error_description]
91
+ end
92
+ end
93
+ end
data/lib/stripe/errors.rb CHANGED
@@ -11,6 +11,7 @@ module Stripe
11
11
  attr_accessor :response
12
12
 
13
13
  attr_reader :code
14
+ attr_reader :error
14
15
  attr_reader :http_body
15
16
  attr_reader :http_headers
16
17
  attr_reader :http_status
@@ -24,9 +25,24 @@ module Stripe
24
25
  @http_status = http_status
25
26
  @http_body = http_body
26
27
  @http_headers = http_headers || {}
28
+ @idempotent_replayed = @http_headers["idempotent-replayed"] == "true"
27
29
  @json_body = json_body
28
30
  @code = code
29
- @request_id = @http_headers[:request_id]
31
+ @request_id = @http_headers["request-id"]
32
+ @error = construct_error_object
33
+ end
34
+
35
+ def construct_error_object
36
+ return nil if @json_body.nil? || !@json_body.key?(:error)
37
+
38
+ ErrorObject.construct_from(@json_body[:error])
39
+ end
40
+
41
+ # Whether the error was the result of an idempotent replay, meaning that it
42
+ # originally occurred on a previous request and is being replayed back
43
+ # because the user sent the same idempotency key for this one.
44
+ def idempotent_replayed?
45
+ @idempotent_replayed
30
46
  end
31
47
 
32
48
  def to_s
@@ -59,8 +75,7 @@ module Stripe
59
75
  class CardError < StripeError
60
76
  attr_reader :param
61
77
 
62
- # TODO: make code a keyword arg in next major release
63
- def initialize(message, param, code, http_status: nil, http_body: nil,
78
+ def initialize(message, param, code: nil, http_status: nil, http_body: nil,
64
79
  json_body: nil, http_headers: nil)
65
80
  super(message, http_status: http_status, http_body: http_body,
66
81
  json_body: json_body, http_headers: http_headers,
@@ -119,6 +134,12 @@ module Stripe
119
134
  json_body: json_body, http_headers: http_headers,
120
135
  code: code)
121
136
  end
137
+
138
+ def construct_error_object
139
+ return nil if @json_body.nil?
140
+
141
+ OAuthErrorObject.construct_from(@json_body)
142
+ end
122
143
  end
123
144
 
124
145
  # InvalidClientError is raised when the client doesn't belong to you, or
@@ -0,0 +1,84 @@
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
+ attr_reader :request_id
36
+
37
+ # Arbitrary user-provided data in the form of a Ruby hash that's passed
38
+ # from subscribers on `request_begin` to subscribers on `request_end`.
39
+ # `request_begin` subscribers can set keys which will then be available
40
+ # in `request_end`.
41
+ attr_reader :user_data
42
+
43
+ def initialize(duration:, http_status:, method:, num_retries:, path:,
44
+ request_id:, user_data: nil)
45
+ @duration = duration
46
+ @http_status = http_status
47
+ @method = method
48
+ @num_retries = num_retries
49
+ @path = path
50
+ @request_id = request_id
51
+ @user_data = user_data
52
+ freeze
53
+ end
54
+ end
55
+
56
+ # This class was renamed for consistency. This alias is here for backwards
57
+ # compatibility.
58
+ RequestEvent = RequestEndEvent
59
+
60
+ # Returns true if there are a non-zero number of subscribers on the given
61
+ # topic, and false otherwise.
62
+ def self.any_subscribers?(topic)
63
+ !subscribers[topic].empty?
64
+ end
65
+
66
+ def self.subscribe(topic, name = rand, &block)
67
+ subscribers[topic][name] = block
68
+ name
69
+ end
70
+
71
+ def self.unsubscribe(topic, name)
72
+ subscribers[topic].delete(name)
73
+ end
74
+
75
+ def self.notify(topic, event)
76
+ subscribers[topic].each_value { |subscriber| subscriber.call(event) }
77
+ end
78
+
79
+ def self.subscribers
80
+ @subscribers ||= Hash.new { |hash, key| hash[key] = {} }
81
+ end
82
+ private_class_method :subscribers
83
+ end
84
+ end
@@ -7,7 +7,7 @@ module Stripe
7
7
  include Stripe::APIOperations::Request
8
8
  include Stripe::APIOperations::Create
9
9
 
10
- OBJECT_NAME = "list".freeze
10
+ OBJECT_NAME = "list"
11
11
 
12
12
  # This accessor allows a `ListObject` to inherit various filters that were
13
13
  # given to a predecessor. This allows for things like consistent limits,
@@ -51,6 +51,16 @@ module Stripe
51
51
  # Iterates through each resource in all pages, making additional fetches to
52
52
  # the API as necessary.
53
53
  #
54
+ # The default iteration direction is forwards according to Stripe's API
55
+ # "natural" ordering direction -- newer objects first, and moving towards
56
+ # older objects.
57
+ #
58
+ # However, if the initial list object was fetched using an `ending_before`
59
+ # cursor (and only `ending_before`, `starting_after` cannot also be
60
+ # included), the method assumes that the user is trying to iterate
61
+ # backwards compared to natural ordering and returns results that way --
62
+ # older objects first, and moving towards newer objects.
63
+ #
54
64
  # Note that this method will make as many API calls as necessary to fetch
55
65
  # all resources. For more granular control, please see +each+ and
56
66
  # +next_page+.
@@ -59,8 +69,18 @@ module Stripe
59
69
 
60
70
  page = self
61
71
  loop do
62
- page.each(&blk)
63
- page = page.next_page
72
+ # Backward iterating activates if we have an `ending_before` constraint
73
+ # and _just_ an `ending_before` constraint. If `starting_after` was
74
+ # also used, we iterate forwards normally.
75
+ if filters.include?(:ending_before) &&
76
+ !filters.include?(:starting_after)
77
+ page.reverse_each(&blk)
78
+ page = page.previous_page
79
+ else
80
+ page.each(&blk)
81
+ page = page.next_page
82
+ end
83
+
64
84
  break if page.empty?
65
85
  end
66
86
  end
@@ -72,8 +92,8 @@ module Stripe
72
92
 
73
93
  def retrieve(id, opts = {})
74
94
  id, retrieve_params = Util.normalize_id(id)
75
- resp, opts = request(:get, "#{resource_url}/#{CGI.escape(id)}",
76
- retrieve_params, opts)
95
+ url = "#{resource_url}/#{CGI.escape(id)}"
96
+ resp, opts = execute_resource_request(:get, url, retrieve_params, opts)
77
97
  Util.convert_to_stripe_object(resp.data, opts)
78
98
  end
79
99
 
@@ -83,6 +103,7 @@ module Stripe
83
103
  # was given, the default limit will be fetched again.
84
104
  def next_page(params = {}, opts = {})
85
105
  return self.class.empty_list(opts) unless has_more
106
+
86
107
  last_id = data.last.id
87
108
 
88
109
  params = filters.merge(starting_after: last_id).merge(params)
@@ -95,6 +116,8 @@ module Stripe
95
116
  # This method will try to respect the limit of the current page. If none
96
117
  # was given, the default limit will be fetched again.
97
118
  def previous_page(params = {}, opts = {})
119
+ return self.class.empty_list(opts) unless has_more
120
+
98
121
  first_id = data.first.id
99
122
 
100
123
  params = filters.merge(ending_before: first_id).merge(params)
@@ -106,5 +129,11 @@ module Stripe
106
129
  url ||
107
130
  raise(ArgumentError, "List object does not contain a 'url' field.")
108
131
  end
132
+
133
+ # Iterates through each resource in the page represented by the current
134
+ # `ListObject` in reverse.
135
+ def reverse_each(&blk)
136
+ data.reverse_each(&blk)
137
+ end
109
138
  end
110
139
  end