stripe 2.0.3 → 5.55.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (214) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +1036 -0
  3. data/CODE_OF_CONDUCT.md +77 -0
  4. data/Gemfile +24 -23
  5. data/History.txt +1 -593
  6. data/Makefile +7 -0
  7. data/README.md +252 -53
  8. data/Rakefile +18 -24
  9. data/VERSION +1 -1
  10. data/bin/stripe-console +5 -3
  11. data/lib/stripe/api_operations/create.rb +4 -2
  12. data/lib/stripe/api_operations/delete.rb +31 -3
  13. data/lib/stripe/api_operations/list.rb +4 -13
  14. data/lib/stripe/api_operations/nested_resource.rb +73 -0
  15. data/lib/stripe/api_operations/request.rb +92 -10
  16. data/lib/stripe/api_operations/save.rb +25 -13
  17. data/lib/stripe/api_operations/search.rb +19 -0
  18. data/lib/stripe/api_resource.rb +55 -11
  19. data/lib/stripe/api_resource_test_helpers.rb +47 -0
  20. data/lib/stripe/connection_manager.rb +200 -0
  21. data/lib/stripe/error_object.rb +93 -0
  22. data/lib/stripe/errors.rb +98 -13
  23. data/lib/stripe/instrumentation.rb +84 -0
  24. data/lib/stripe/list_object.rb +55 -21
  25. data/lib/stripe/multipart_encoder.rb +131 -0
  26. data/lib/stripe/oauth.rb +65 -0
  27. data/lib/stripe/object_types.rb +119 -0
  28. data/lib/stripe/{account.rb → resources/account.rb} +75 -38
  29. data/lib/stripe/resources/account_link.rb +10 -0
  30. data/lib/stripe/resources/alipay_account.rb +34 -0
  31. data/lib/stripe/{apple_pay_domain.rb → resources/apple_pay_domain.rb} +6 -1
  32. data/lib/stripe/resources/application_fee.rb +14 -0
  33. data/lib/stripe/resources/application_fee_refund.rb +31 -0
  34. data/lib/stripe/resources/balance.rb +8 -0
  35. data/lib/stripe/resources/balance_transaction.rb +10 -0
  36. data/lib/stripe/resources/bank_account.rb +43 -0
  37. data/lib/stripe/resources/billing_portal/configuration.rb +14 -0
  38. data/lib/stripe/resources/billing_portal/session.rb +12 -0
  39. data/lib/stripe/{bitcoin_receiver.rb → resources/bitcoin_receiver.rb} +8 -4
  40. data/lib/stripe/resources/bitcoin_transaction.rb +16 -0
  41. data/lib/stripe/resources/capability.rb +34 -0
  42. data/lib/stripe/resources/card.rb +38 -0
  43. data/lib/stripe/resources/cash_balance.rb +22 -0
  44. data/lib/stripe/resources/charge.rb +32 -0
  45. data/lib/stripe/resources/checkout/session.rb +27 -0
  46. data/lib/stripe/resources/country_spec.rb +10 -0
  47. data/lib/stripe/{coupon.rb → resources/coupon.rb} +6 -1
  48. data/lib/stripe/resources/credit_note.rb +33 -0
  49. data/lib/stripe/resources/credit_note_line_item.rb +8 -0
  50. data/lib/stripe/resources/customer.rb +74 -0
  51. data/lib/stripe/resources/customer_balance_transaction.rb +31 -0
  52. data/lib/stripe/resources/discount.rb +8 -0
  53. data/lib/stripe/resources/dispute.rb +22 -0
  54. data/lib/stripe/resources/ephemeral_key.rb +20 -0
  55. data/lib/stripe/resources/event.rb +10 -0
  56. data/lib/stripe/resources/exchange_rate.rb +10 -0
  57. data/lib/stripe/resources/file.rb +36 -0
  58. data/lib/stripe/resources/file_link.rb +12 -0
  59. data/lib/stripe/resources/financial_connections/account.rb +31 -0
  60. data/lib/stripe/resources/financial_connections/account_owner.rb +10 -0
  61. data/lib/stripe/resources/financial_connections/account_ownership.rb +10 -0
  62. data/lib/stripe/resources/financial_connections/session.rb +12 -0
  63. data/lib/stripe/resources/funding_instructions.rb +16 -0
  64. data/lib/stripe/resources/identity/verification_report.rb +12 -0
  65. data/lib/stripe/resources/identity/verification_session.rb +35 -0
  66. data/lib/stripe/resources/invoice.rb +83 -0
  67. data/lib/stripe/{invoice_item.rb → resources/invoice_item.rb} +6 -1
  68. data/lib/stripe/resources/invoice_line_item.rb +8 -0
  69. data/lib/stripe/resources/issuing/authorization.rb +34 -0
  70. data/lib/stripe/resources/issuing/card.rb +25 -0
  71. data/lib/stripe/resources/issuing/card_details.rb +10 -0
  72. data/lib/stripe/resources/issuing/cardholder.rb +14 -0
  73. data/lib/stripe/resources/issuing/dispute.rb +25 -0
  74. data/lib/stripe/resources/issuing/transaction.rb +13 -0
  75. data/lib/stripe/resources/line_item.rb +8 -0
  76. data/lib/stripe/resources/login_link.rb +15 -0
  77. data/lib/stripe/resources/mandate.rb +8 -0
  78. data/lib/stripe/resources/order.rb +33 -0
  79. data/lib/stripe/resources/order_return.rb +10 -0
  80. data/lib/stripe/resources/payment_intent.rb +82 -0
  81. data/lib/stripe/resources/payment_link.rb +23 -0
  82. data/lib/stripe/resources/payment_method.rb +33 -0
  83. data/lib/stripe/resources/payout.rb +33 -0
  84. data/lib/stripe/resources/person.rb +32 -0
  85. data/lib/stripe/{plan.rb → resources/plan.rb} +5 -0
  86. data/lib/stripe/resources/price.rb +21 -0
  87. data/lib/stripe/resources/product.rb +22 -0
  88. data/lib/stripe/resources/promotion_code.rb +12 -0
  89. data/lib/stripe/resources/quote.rb +105 -0
  90. data/lib/stripe/resources/radar/early_fraud_warning.rb +12 -0
  91. data/lib/stripe/resources/radar/value_list.rb +15 -0
  92. data/lib/stripe/resources/radar/value_list_item.rb +14 -0
  93. data/lib/stripe/resources/recipient.rb +14 -0
  94. data/lib/stripe/resources/recipient_transfer.rb +7 -0
  95. data/lib/stripe/resources/refund.rb +42 -0
  96. data/lib/stripe/resources/reporting/report_run.rb +13 -0
  97. data/lib/stripe/resources/reporting/report_type.rb +13 -0
  98. data/lib/stripe/resources/reversal.rb +30 -0
  99. data/lib/stripe/resources/review.rb +21 -0
  100. data/lib/stripe/resources/setup_attempt.rb +10 -0
  101. data/lib/stripe/resources/setup_intent.rb +43 -0
  102. data/lib/stripe/resources/shipping_rate.rb +12 -0
  103. data/lib/stripe/resources/sigma/scheduled_query_run.rb +16 -0
  104. data/lib/stripe/{sku.rb → resources/sku.rb} +7 -2
  105. data/lib/stripe/resources/source.rb +47 -0
  106. data/lib/stripe/resources/source_transaction.rb +8 -0
  107. data/lib/stripe/resources/subscription.rb +35 -0
  108. data/lib/stripe/resources/subscription_item.rb +26 -0
  109. data/lib/stripe/resources/subscription_schedule.rb +33 -0
  110. data/lib/stripe/resources/tax_code.rb +10 -0
  111. data/lib/stripe/resources/tax_id.rb +27 -0
  112. data/lib/stripe/{product.rb → resources/tax_rate.rb} +7 -3
  113. data/lib/stripe/resources/terminal/configuration.rb +15 -0
  114. data/lib/stripe/resources/terminal/connection_token.rb +12 -0
  115. data/lib/stripe/resources/terminal/location.rb +15 -0
  116. data/lib/stripe/resources/terminal/reader.rb +75 -0
  117. data/lib/stripe/resources/test_helpers/test_clock.rb +25 -0
  118. data/lib/stripe/{three_d_secure.rb → resources/three_d_secure.rb} +5 -0
  119. data/lib/stripe/resources/token.rb +10 -0
  120. data/lib/stripe/resources/topup.rb +23 -0
  121. data/lib/stripe/resources/transfer.rb +27 -0
  122. data/lib/stripe/resources/usage_record.rb +8 -0
  123. data/lib/stripe/resources/usage_record_summary.rb +8 -0
  124. data/lib/stripe/{recipient.rb → resources/webhook_endpoint.rb} +6 -5
  125. data/lib/stripe/resources.rb +100 -0
  126. data/lib/stripe/search_result_object.rb +86 -0
  127. data/lib/stripe/singleton_api_resource.rb +10 -4
  128. data/lib/stripe/stripe_client.rb +886 -223
  129. data/lib/stripe/stripe_configuration.rb +194 -0
  130. data/lib/stripe/stripe_object.rb +301 -132
  131. data/lib/stripe/stripe_response.rb +89 -27
  132. data/lib/stripe/util.rb +272 -122
  133. data/lib/stripe/version.rb +3 -1
  134. data/lib/stripe/webhook.rb +121 -0
  135. data/lib/stripe.rb +94 -116
  136. data/stripe.gemspec +35 -16
  137. metadata +127 -156
  138. data/.gitattributes +0 -4
  139. data/.github/ISSUE_TEMPLATE.md +0 -5
  140. data/.gitignore +0 -5
  141. data/.travis.yml +0 -15
  142. data/lib/stripe/alipay_account.rb +0 -20
  143. data/lib/stripe/application_fee.rb +0 -20
  144. data/lib/stripe/application_fee_refund.rb +0 -18
  145. data/lib/stripe/balance.rb +0 -4
  146. data/lib/stripe/balance_transaction.rb +0 -9
  147. data/lib/stripe/bank_account.rb +0 -28
  148. data/lib/stripe/bitcoin_transaction.rb +0 -9
  149. data/lib/stripe/card.rb +0 -25
  150. data/lib/stripe/charge.rb +0 -80
  151. data/lib/stripe/country_spec.rb +0 -9
  152. data/lib/stripe/customer.rb +0 -77
  153. data/lib/stripe/dispute.rb +0 -15
  154. data/lib/stripe/event.rb +0 -5
  155. data/lib/stripe/file_upload.rb +0 -31
  156. data/lib/stripe/invoice.rb +0 -27
  157. data/lib/stripe/order.rb +0 -27
  158. data/lib/stripe/order_return.rb +0 -9
  159. data/lib/stripe/refund.rb +0 -7
  160. data/lib/stripe/reversal.rb +0 -18
  161. data/lib/stripe/source.rb +0 -11
  162. data/lib/stripe/subscription.rb +0 -31
  163. data/lib/stripe/subscription_item.rb +0 -12
  164. data/lib/stripe/token.rb +0 -5
  165. data/lib/stripe/transfer.rb +0 -16
  166. data/openapi/fixtures.json +0 -1383
  167. data/openapi/fixtures.yaml +0 -1130
  168. data/openapi/spec.json +0 -19749
  169. data/openapi/spec.yaml +0 -15359
  170. data/test/api_fixtures.rb +0 -29
  171. data/test/api_stub_helpers.rb +0 -125
  172. data/test/stripe/account_test.rb +0 -204
  173. data/test/stripe/alipay_account_test.rb +0 -19
  174. data/test/stripe/api_operations_test.rb +0 -31
  175. data/test/stripe/api_resource_test.rb +0 -496
  176. data/test/stripe/apple_pay_domain_test.rb +0 -33
  177. data/test/stripe/application_fee_refund_test.rb +0 -38
  178. data/test/stripe/application_fee_test.rb +0 -14
  179. data/test/stripe/balance_test.rb +0 -11
  180. data/test/stripe/bank_account_test.rb +0 -41
  181. data/test/stripe/bitcoin_receiver_test.rb +0 -70
  182. data/test/stripe/bitcoin_transaction_test.rb +0 -21
  183. data/test/stripe/charge_test.rb +0 -59
  184. data/test/stripe/country_spec_test.rb +0 -20
  185. data/test/stripe/coupon_test.rb +0 -44
  186. data/test/stripe/customer_card_test.rb +0 -42
  187. data/test/stripe/customer_test.rb +0 -116
  188. data/test/stripe/dispute_test.rb +0 -42
  189. data/test/stripe/errors_test.rb +0 -18
  190. data/test/stripe/file_upload_test.rb +0 -66
  191. data/test/stripe/invoice_item_test.rb +0 -55
  192. data/test/stripe/invoice_test.rb +0 -66
  193. data/test/stripe/list_object_test.rb +0 -170
  194. data/test/stripe/order_return_test.rb +0 -21
  195. data/test/stripe/order_test.rb +0 -59
  196. data/test/stripe/plan_test.rb +0 -52
  197. data/test/stripe/product_test.rb +0 -47
  198. data/test/stripe/recipient_card_test.rb +0 -40
  199. data/test/stripe/recipient_test.rb +0 -50
  200. data/test/stripe/refund_test.rb +0 -39
  201. data/test/stripe/reversal_test.rb +0 -43
  202. data/test/stripe/sku_test.rb +0 -50
  203. data/test/stripe/source_test.rb +0 -43
  204. data/test/stripe/stripe_client_test.rb +0 -440
  205. data/test/stripe/stripe_object_test.rb +0 -361
  206. data/test/stripe/stripe_response_test.rb +0 -46
  207. data/test/stripe/subscription_item_test.rb +0 -54
  208. data/test/stripe/subscription_test.rb +0 -60
  209. data/test/stripe/three_d_secure_test.rb +0 -23
  210. data/test/stripe/transfer_test.rb +0 -50
  211. data/test/stripe/util_test.rb +0 -149
  212. data/test/stripe_test.rb +0 -41
  213. data/test/test_data.rb +0 -59
  214. data/test/test_helper.rb +0 -41
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,30 @@ 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 || {}
28
+ @idempotent_replayed = @http_headers["idempotent-replayed"] == "true"
26
29
  @json_body = json_body
27
- @request_id = @http_headers[:request_id]
30
+ @code = code
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
28
46
  end
29
47
 
30
48
  def to_s
@@ -55,26 +73,32 @@ module Stripe
55
73
  # CardError is raised when a user enters a card that can't be charged for
56
74
  # some reason.
57
75
  class CardError < StripeError
58
- attr_reader :param, :code
76
+ attr_reader :param
59
77
 
60
- def initialize(message, param, code, http_status: nil, http_body: nil, json_body: nil,
61
- http_headers: nil)
78
+ def initialize(message, param, code: nil, http_status: nil, http_body: nil,
79
+ json_body: nil, http_headers: nil)
62
80
  super(message, http_status: http_status, http_body: http_body,
63
- json_body: json_body, http_headers: http_headers)
81
+ json_body: json_body, http_headers: http_headers,
82
+ code: code)
64
83
  @param = param
65
- @code = code
66
84
  end
67
85
  end
68
86
 
87
+ # IdempotencyError is raised in cases where an idempotency key was used
88
+ # improperly.
89
+ class IdempotencyError < StripeError
90
+ end
91
+
69
92
  # InvalidRequestError is raised when a request is initiated with invalid
70
93
  # parameters.
71
94
  class InvalidRequestError < StripeError
72
95
  attr_accessor :param
73
96
 
74
- def initialize(message, param, http_status: nil, http_body: nil, json_body: nil,
75
- http_headers: nil)
97
+ def initialize(message, param, http_status: nil, http_body: nil,
98
+ json_body: nil, http_headers: nil, code: nil)
76
99
  super(message, http_status: http_status, http_body: http_body,
77
- json_body: json_body, http_headers: http_headers)
100
+ json_body: json_body, http_headers: http_headers,
101
+ code: code)
78
102
  @param = param
79
103
  end
80
104
  end
@@ -89,4 +113,65 @@ module Stripe
89
113
  # back off on request rate.
90
114
  class RateLimitError < StripeError
91
115
  end
116
+
117
+ # SignatureVerificationError is raised when the signature verification for a
118
+ # webhook fails
119
+ class SignatureVerificationError < StripeError
120
+ attr_accessor :sig_header
121
+
122
+ def initialize(message, sig_header, http_body: nil)
123
+ super(message, http_body: http_body)
124
+ @sig_header = sig_header
125
+ end
126
+ end
127
+
128
+ module OAuth
129
+ # OAuthError is raised when the OAuth API returns an error.
130
+ class OAuthError < StripeError
131
+ def initialize(code, description, http_status: nil, http_body: nil,
132
+ json_body: nil, http_headers: nil)
133
+ super(description, http_status: http_status, http_body: http_body,
134
+ json_body: json_body, http_headers: http_headers,
135
+ code: code)
136
+ end
137
+
138
+ def construct_error_object
139
+ return nil if @json_body.nil?
140
+
141
+ OAuthErrorObject.construct_from(@json_body)
142
+ end
143
+ end
144
+
145
+ # InvalidClientError is raised when the client doesn't belong to you, or
146
+ # the API key mode (live or test) doesn't match the client mode. Or the
147
+ # stripe_user_id doesn't exist or isn't connected to your application.
148
+ class InvalidClientError < OAuthError
149
+ end
150
+
151
+ # InvalidGrantError is raised when a specified code doesn't exist, is
152
+ # expired, has been used, or doesn't belong to you; a refresh token doesn't
153
+ # exist, or doesn't belong to you; or if an API key's mode (live or test)
154
+ # doesn't match the mode of a code or refresh token.
155
+ class InvalidGrantError < OAuthError
156
+ end
157
+
158
+ # InvalidRequestError is raised when a code, refresh token, or grant type
159
+ # parameter is not provided, but was required.
160
+ class InvalidRequestError < OAuthError
161
+ end
162
+
163
+ # InvalidScopeError is raised when an invalid scope parameter is provided.
164
+ class InvalidScopeError < OAuthError
165
+ end
166
+
167
+ # UnsupportedGrantTypeError is raised when an unuspported grant type
168
+ # parameter is specified.
169
+ class UnsupportedGrantTypeError < OAuthError
170
+ end
171
+
172
+ # UnsupportedResponseTypeError is raised when an unsupported response type
173
+ # parameter is specified.
174
+ class UnsupportedResponseTypeError < OAuthError
175
+ end
176
+ end
92
177
  end
@@ -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
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  class ListObject < StripeObject
3
5
  include Enumerable
@@ -5,6 +7,8 @@ module Stripe
5
7
  include Stripe::APIOperations::Request
6
8
  include Stripe::APIOperations::Create
7
9
 
10
+ OBJECT_NAME = "list"
11
+
8
12
  # This accessor allows a `ListObject` to inherit various filters that were
9
13
  # given to a predecessor. This allows for things like consistent limits,
10
14
  # expansions, and predicates as a user pages through resources.
@@ -13,8 +17,8 @@ module Stripe
13
17
  # An empty list object. This is returned from +next+ when we know that
14
18
  # there isn't a next page in order to replicate the behavior of the API
15
19
  # when it attempts to return a page beyond the last.
16
- def self.empty_list(opts={})
17
- ListObject.construct_from({ :data => [] }, opts)
20
+ def self.empty_list(opts = {})
21
+ ListObject.construct_from({ data: [] }, opts)
18
22
  end
19
23
 
20
24
  def initialize(*args)
@@ -22,12 +26,16 @@ module Stripe
22
26
  self.filters = {}
23
27
  end
24
28
 
25
- def [](k)
26
- case k
29
+ def [](key)
30
+ case key
27
31
  when String, Symbol
28
32
  super
29
33
  else
30
- raise ArgumentError.new("You tried to access the #{k.inspect} index, but ListObject types only support String keys. (HINT: List calls return an object with a 'data' (which is the data array). You likely want to call #data[#{k.inspect}])")
34
+ raise ArgumentError,
35
+ "You tried to access the #{key.inspect} index, but ListObject " \
36
+ "types only support String keys. (HINT: List calls return an " \
37
+ "object with a 'data' (which is the data array). You likely " \
38
+ "want to call #data[#{key.inspect}])"
31
39
  end
32
40
  end
33
41
 
@@ -37,12 +45,22 @@ module Stripe
37
45
  # Note that this method makes no effort to fetch a new page when it gets to
38
46
  # the end of the current page's resources. See also +auto_paging_each+.
39
47
  def each(&blk)
40
- self.data.each(&blk)
48
+ data.each(&blk)
41
49
  end
42
50
 
43
51
  # Iterates through each resource in all pages, making additional fetches to
44
52
  # the API as necessary.
45
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
+ #
46
64
  # Note that this method will make as many API calls as necessary to fetch
47
65
  # all resources. For more granular control, please see +each+ and
48
66
  # +next_page+.
@@ -51,20 +69,31 @@ module Stripe
51
69
 
52
70
  page = self
53
71
  loop do
54
- page.each(&blk)
55
- 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
+
56
84
  break if page.empty?
57
85
  end
58
86
  end
59
87
 
60
88
  # Returns true if the page object contains no elements.
61
89
  def empty?
62
- self.data.empty?
90
+ data.empty?
63
91
  end
64
92
 
65
- def retrieve(id, opts={})
93
+ def retrieve(id, opts = {})
66
94
  id, retrieve_params = Util.normalize_id(id)
67
- resp, opts = request(:get,"#{resource_url}/#{CGI.escape(id)}", retrieve_params, opts)
95
+ url = "#{resource_url}/#{CGI.escape(id)}"
96
+ resp, opts = execute_resource_request(:get, url, retrieve_params, opts)
68
97
  Util.convert_to_stripe_object(resp.data, opts)
69
98
  end
70
99
 
@@ -72,13 +101,12 @@ module Stripe
72
101
  #
73
102
  # This method will try to respect the limit of the current page. If none
74
103
  # was given, the default limit will be fetched again.
75
- def next_page(params={}, opts={})
76
- return self.class.empty_list(opts) if !has_more
104
+ def next_page(params = {}, opts = {})
105
+ return self.class.empty_list(opts) unless has_more
106
+
77
107
  last_id = data.last.id
78
108
 
79
- params = filters.merge({
80
- :starting_after => last_id,
81
- }).merge(params)
109
+ params = filters.merge(starting_after: last_id).merge(params)
82
110
 
83
111
  list(params, opts)
84
112
  end
@@ -87,19 +115,25 @@ module Stripe
87
115
  #
88
116
  # This method will try to respect the limit of the current page. If none
89
117
  # was given, the default limit will be fetched again.
90
- def previous_page(params={}, opts={})
118
+ def previous_page(params = {}, opts = {})
119
+ return self.class.empty_list(opts) unless has_more
120
+
91
121
  first_id = data.first.id
92
122
 
93
- params = filters.merge({
94
- :ending_before => first_id,
95
- }).merge(params)
123
+ params = filters.merge(ending_before: first_id).merge(params)
96
124
 
97
125
  list(params, opts)
98
126
  end
99
127
 
100
128
  def resource_url
101
- self.url ||
129
+ url ||
102
130
  raise(ArgumentError, "List object does not contain a 'url' field.")
103
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
104
138
  end
105
139
  end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "tempfile"
5
+
6
+ module Stripe
7
+ # Encodes parameters into a `multipart/form-data` payload as described by RFC
8
+ # 2388:
9
+ #
10
+ # https://tools.ietf.org/html/rfc2388
11
+ #
12
+ # This is most useful for transferring file-like objects.
13
+ #
14
+ # Parameters should be added with `#encode`. When ready, use `#body` to get
15
+ # the encoded result and `#content_type` to get the value that should be
16
+ # placed in the `Content-Type` header of a subsequent request (which includes
17
+ # a boundary value).
18
+ class MultipartEncoder
19
+ MULTIPART_FORM_DATA = "multipart/form-data"
20
+
21
+ # A shortcut for encoding a single set of parameters and finalizing a
22
+ # result.
23
+ #
24
+ # Returns an encoded body and the value that should be set in the content
25
+ # type header of a subsequent request.
26
+ def self.encode(params)
27
+ encoder = MultipartEncoder.new
28
+ encoder.encode(params)
29
+ encoder.close
30
+ [encoder.body, encoder.content_type]
31
+ end
32
+
33
+ # Gets the object's randomly generated boundary string.
34
+ attr_reader :boundary
35
+
36
+ # Initializes a new multipart encoder.
37
+ def initialize
38
+ # Kind of weird, but required by Rubocop because the unary plus operator
39
+ # is considered faster than `Stripe.new`.
40
+ @body = +""
41
+
42
+ # Chose the same number of random bytes that Go uses in its standard
43
+ # library implementation. Easily enough entropy to ensure that it won't
44
+ # be present in a file we're sending.
45
+ @boundary = SecureRandom.hex(30)
46
+
47
+ @closed = false
48
+ @first_field = true
49
+ end
50
+
51
+ # Gets the encoded body. `#close` must be called first.
52
+ def body
53
+ raise "object must be closed before getting body" unless @closed
54
+
55
+ @body
56
+ end
57
+
58
+ # Finalizes the object by writing the final boundary.
59
+ def close
60
+ raise "object already closed" if @closed
61
+
62
+ @body << "\r\n"
63
+ @body << "--#{@boundary}--"
64
+
65
+ @closed = true
66
+
67
+ nil
68
+ end
69
+
70
+ # Gets the value including boundary that should be put into a multipart
71
+ # request's `Content-Type`.
72
+ def content_type
73
+ "#{MULTIPART_FORM_DATA}; boundary=#{@boundary}"
74
+ end
75
+
76
+ # Encodes a set of parameters to the body.
77
+ #
78
+ # Note that parameters are expected to be a hash, but a "flat" hash such
79
+ # that complex substructures like hashes and arrays have already been
80
+ # appropriately Stripe-encoded. Pass a complex structure through
81
+ # `Util.flatten_params` first before handing it off to this method.
82
+ def encode(params)
83
+ raise "no more parameters can be written to closed object" if @closed
84
+
85
+ params.each do |name, val|
86
+ if val.is_a?(::File) || val.is_a?(::Tempfile)
87
+ write_field(name, val.read, filename: ::File.basename(val.path))
88
+ elsif val.respond_to?(:read)
89
+ write_field(name, val.read, filename: "blob")
90
+ else
91
+ write_field(name, val, filename: nil)
92
+ end
93
+ end
94
+
95
+ nil
96
+ end
97
+
98
+ #
99
+ # private
100
+ #
101
+
102
+ # Escapes double quotes so that the given value can be used in a
103
+ # double-quoted string and replaces any linebreak characters with spaces.
104
+ private def escape(str)
105
+ str.gsub('"', "%22").tr("\n", " ").tr("\r", " ")
106
+ end
107
+
108
+ private def write_field(name, data, filename:)
109
+ if !@first_field
110
+ @body << "\r\n"
111
+ else
112
+ @first_field = false
113
+ end
114
+
115
+ @body << "--#{@boundary}\r\n"
116
+
117
+ if filename
118
+ @body << %(Content-Disposition: form-data) +
119
+ %(; name="#{escape(name.to_s)}") +
120
+ %(; filename="#{escape(filename)}"\r\n)
121
+ @body << %(Content-Type: application/octet-stream\r\n)
122
+ else
123
+ @body << %(Content-Disposition: form-data) +
124
+ %(; name="#{escape(name.to_s)}"\r\n)
125
+ end
126
+
127
+ @body << "\r\n"
128
+ @body << data.to_s
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ module OAuth
5
+ module OAuthOperations
6
+ extend APIOperations::Request::ClassMethods
7
+
8
+ def self.execute_resource_request(method, url, params, opts)
9
+ opts = Util.normalize_opts(opts)
10
+ opts[:client] ||= opts[:client] || StripeClient.active_client
11
+ opts[:api_base] ||= opts[:client].config.connect_base
12
+
13
+ super(method, url, params, opts)
14
+ end
15
+ end
16
+
17
+ def self.get_client_id(params = {})
18
+ client_id = params[:client_id] || Stripe.client_id
19
+ unless client_id
20
+ raise AuthenticationError, "No client_id provided. " \
21
+ 'Set your client_id using "Stripe.client_id = <CLIENT-ID>". ' \
22
+ "You can find your client_ids in your Stripe dashboard at " \
23
+ "https://dashboard.stripe.com/account/applications/settings, " \
24
+ "after registering your account as a platform. See " \
25
+ "https://stripe.com/docs/connect/standalone-accounts for details, " \
26
+ "or email support@stripe.com if you have any questions."
27
+ end
28
+ client_id
29
+ end
30
+
31
+ def self.authorize_url(params = {}, opts = {})
32
+ client = opts[:client] || StripeClient.active_client
33
+ base = opts[:connect_base] || client.config.connect_base
34
+
35
+ path = "/oauth/authorize"
36
+ path = "/express" + path if opts[:express]
37
+
38
+ params[:client_id] = get_client_id(params)
39
+ params[:response_type] ||= "code"
40
+ query = Util.encode_parameters(params)
41
+
42
+ "#{base}#{path}?#{query}"
43
+ end
44
+
45
+ def self.token(params = {}, opts = {})
46
+ opts = Util.normalize_opts(opts)
47
+ opts[:api_key] = params[:client_secret] if params[:client_secret]
48
+ resp, opts = OAuthOperations.execute_resource_request(
49
+ :post, "/oauth/token", params, opts
50
+ )
51
+ # This is just going to return a generic StripeObject, but that's okay
52
+ Util.convert_to_stripe_object(resp.data, opts)
53
+ end
54
+
55
+ def self.deauthorize(params = {}, opts = {})
56
+ opts = Util.normalize_opts(opts)
57
+ params[:client_id] = get_client_id(params)
58
+ resp, opts = OAuthOperations.execute_resource_request(
59
+ :post, "/oauth/deauthorize", params, opts
60
+ )
61
+ # This is just going to return a generic StripeObject, but that's okay
62
+ Util.convert_to_stripe_object(resp.data, opts)
63
+ end
64
+ end
65
+ end