stripe 1.27.2 → 5.33.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (192) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +942 -0
  3. data/CODE_OF_CONDUCT.md +77 -0
  4. data/Gemfile +29 -4
  5. data/History.txt +1 -361
  6. data/README.md +349 -0
  7. data/Rakefile +33 -3
  8. data/VERSION +1 -1
  9. data/bin/stripe-console +14 -5
  10. data/lib/data/ca-certificates.crt +4016 -5138
  11. data/lib/stripe.rb +102 -320
  12. data/lib/stripe/api_operations/create.rb +5 -9
  13. data/lib/stripe/api_operations/delete.rb +32 -4
  14. data/lib/stripe/api_operations/list.rb +11 -9
  15. data/lib/stripe/api_operations/nested_resource.rb +73 -0
  16. data/lib/stripe/api_operations/request.rb +66 -11
  17. data/lib/stripe/api_operations/save.rb +97 -0
  18. data/lib/stripe/api_resource.rb +96 -12
  19. data/lib/stripe/connection_manager.rb +164 -0
  20. data/lib/stripe/error_object.rb +94 -0
  21. data/lib/stripe/errors.rb +177 -0
  22. data/lib/stripe/instrumentation.rb +82 -0
  23. data/lib/stripe/list_object.rb +118 -13
  24. data/lib/stripe/multipart_encoder.rb +131 -0
  25. data/lib/stripe/oauth.rb +65 -0
  26. data/lib/stripe/object_types.rb +104 -0
  27. data/lib/stripe/resources.rb +87 -0
  28. data/lib/stripe/resources/account.rb +170 -0
  29. data/lib/stripe/resources/account_link.rb +10 -0
  30. data/lib/stripe/resources/alipay_account.rb +34 -0
  31. data/lib/stripe/resources/apple_pay_domain.rb +17 -0
  32. data/lib/stripe/resources/application_fee.rb +14 -0
  33. data/lib/stripe/resources/application_fee_refund.rb +30 -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/resources/bitcoin_receiver.rb +24 -0
  40. data/lib/stripe/resources/bitcoin_transaction.rb +15 -0
  41. data/lib/stripe/resources/capability.rb +33 -0
  42. data/lib/stripe/resources/card.rb +38 -0
  43. data/lib/stripe/resources/charge.rb +23 -0
  44. data/lib/stripe/resources/checkout/session.rb +16 -0
  45. data/lib/stripe/resources/country_spec.rb +10 -0
  46. data/lib/stripe/resources/coupon.rb +13 -0
  47. data/lib/stripe/resources/credit_note.rb +33 -0
  48. data/lib/stripe/resources/credit_note_line_item.rb +7 -0
  49. data/lib/stripe/resources/customer.rb +41 -0
  50. data/lib/stripe/resources/customer_balance_transaction.rb +30 -0
  51. data/lib/stripe/resources/discount.rb +7 -0
  52. data/lib/stripe/resources/dispute.rb +22 -0
  53. data/lib/stripe/resources/ephemeral_key.rb +20 -0
  54. data/lib/stripe/resources/event.rb +10 -0
  55. data/lib/stripe/resources/exchange_rate.rb +10 -0
  56. data/lib/stripe/resources/file.rb +36 -0
  57. data/lib/stripe/resources/file_link.rb +12 -0
  58. data/lib/stripe/resources/identity/verification_report.rb +12 -0
  59. data/lib/stripe/resources/identity/verification_session.rb +35 -0
  60. data/lib/stripe/resources/invoice.rb +74 -0
  61. data/lib/stripe/resources/invoice_item.rb +13 -0
  62. data/lib/stripe/resources/invoice_line_item.rb +7 -0
  63. data/lib/stripe/resources/issuing/authorization.rb +34 -0
  64. data/lib/stripe/resources/issuing/card.rb +25 -0
  65. data/lib/stripe/resources/issuing/card_details.rb +9 -0
  66. data/lib/stripe/resources/issuing/cardholder.rb +14 -0
  67. data/lib/stripe/resources/issuing/dispute.rb +25 -0
  68. data/lib/stripe/resources/issuing/transaction.rb +13 -0
  69. data/lib/stripe/resources/line_item.rb +7 -0
  70. data/lib/stripe/resources/login_link.rb +14 -0
  71. data/lib/stripe/resources/mandate.rb +8 -0
  72. data/lib/stripe/resources/order.rb +33 -0
  73. data/lib/stripe/resources/order_return.rb +10 -0
  74. data/lib/stripe/resources/payment_intent.rb +43 -0
  75. data/lib/stripe/resources/payment_method.rb +33 -0
  76. data/lib/stripe/resources/payout.rb +33 -0
  77. data/lib/stripe/resources/person.rb +31 -0
  78. data/lib/stripe/resources/plan.rb +13 -0
  79. data/lib/stripe/resources/price.rb +12 -0
  80. data/lib/stripe/resources/product.rb +13 -0
  81. data/lib/stripe/resources/promotion_code.rb +12 -0
  82. data/lib/stripe/resources/radar/early_fraud_warning.rb +12 -0
  83. data/lib/stripe/resources/radar/value_list.rb +15 -0
  84. data/lib/stripe/resources/radar/value_list_item.rb +14 -0
  85. data/lib/stripe/resources/recipient.rb +14 -0
  86. data/lib/stripe/resources/recipient_transfer.rb +7 -0
  87. data/lib/stripe/resources/refund.rb +12 -0
  88. data/lib/stripe/resources/reporting/report_run.rb +13 -0
  89. data/lib/stripe/resources/reporting/report_type.rb +13 -0
  90. data/lib/stripe/resources/reversal.rb +29 -0
  91. data/lib/stripe/resources/review.rb +21 -0
  92. data/lib/stripe/resources/setup_attempt.rb +10 -0
  93. data/lib/stripe/resources/setup_intent.rb +33 -0
  94. data/lib/stripe/resources/sigma/scheduled_query_run.rb +16 -0
  95. data/lib/stripe/resources/sku.rb +13 -0
  96. data/lib/stripe/resources/source.rb +47 -0
  97. data/lib/stripe/resources/source_transaction.rb +7 -0
  98. data/lib/stripe/resources/subscription.rb +26 -0
  99. data/lib/stripe/resources/subscription_item.rb +26 -0
  100. data/lib/stripe/resources/subscription_schedule.rb +33 -0
  101. data/lib/stripe/resources/tax_id.rb +26 -0
  102. data/lib/stripe/resources/tax_rate.rb +12 -0
  103. data/lib/stripe/resources/terminal/connection_token.rb +12 -0
  104. data/lib/stripe/resources/terminal/location.rb +15 -0
  105. data/lib/stripe/resources/terminal/reader.rb +15 -0
  106. data/lib/stripe/resources/three_d_secure.rb +14 -0
  107. data/lib/stripe/resources/token.rb +10 -0
  108. data/lib/stripe/resources/topup.rb +23 -0
  109. data/lib/stripe/resources/transfer.rb +27 -0
  110. data/lib/stripe/resources/usage_record.rb +7 -0
  111. data/lib/stripe/resources/usage_record_summary.rb +7 -0
  112. data/lib/stripe/resources/webhook_endpoint.rb +13 -0
  113. data/lib/stripe/singleton_api_resource.rb +13 -7
  114. data/lib/stripe/stripe_client.rb +989 -0
  115. data/lib/stripe/stripe_configuration.rb +194 -0
  116. data/lib/stripe/stripe_object.rb +481 -148
  117. data/lib/stripe/stripe_response.rb +82 -0
  118. data/lib/stripe/util.rb +265 -70
  119. data/lib/stripe/version.rb +3 -1
  120. data/lib/stripe/webhook.rb +121 -0
  121. data/stripe.gemspec +35 -21
  122. metadata +118 -198
  123. data/.gitignore +0 -4
  124. data/.travis.yml +0 -22
  125. data/README.rdoc +0 -43
  126. data/gemfiles/default-with-activesupport.gemfile +0 -10
  127. data/gemfiles/json.gemfile +0 -12
  128. data/gemfiles/yajl.gemfile +0 -12
  129. data/lib/stripe/account.rb +0 -39
  130. data/lib/stripe/api_operations/update.rb +0 -19
  131. data/lib/stripe/application_fee.rb +0 -20
  132. data/lib/stripe/application_fee_refund.rb +0 -14
  133. data/lib/stripe/balance.rb +0 -4
  134. data/lib/stripe/balance_transaction.rb +0 -9
  135. data/lib/stripe/bank_account.rb +0 -19
  136. data/lib/stripe/bitcoin_receiver.rb +0 -20
  137. data/lib/stripe/bitcoin_transaction.rb +0 -9
  138. data/lib/stripe/card.rb +0 -21
  139. data/lib/stripe/charge.rb +0 -62
  140. data/lib/stripe/coupon.rb +0 -8
  141. data/lib/stripe/customer.rb +0 -75
  142. data/lib/stripe/dispute.rb +0 -16
  143. data/lib/stripe/errors/api_connection_error.rb +0 -4
  144. data/lib/stripe/errors/api_error.rb +0 -4
  145. data/lib/stripe/errors/authentication_error.rb +0 -4
  146. data/lib/stripe/errors/card_error.rb +0 -12
  147. data/lib/stripe/errors/invalid_request_error.rb +0 -11
  148. data/lib/stripe/errors/rate_limit_error.rb +0 -4
  149. data/lib/stripe/errors/stripe_error.rb +0 -26
  150. data/lib/stripe/event.rb +0 -5
  151. data/lib/stripe/file_upload.rb +0 -22
  152. data/lib/stripe/invoice.rb +0 -27
  153. data/lib/stripe/invoice_item.rb +0 -8
  154. data/lib/stripe/order.rb +0 -19
  155. data/lib/stripe/plan.rb +0 -8
  156. data/lib/stripe/product.rb +0 -16
  157. data/lib/stripe/recipient.rb +0 -12
  158. data/lib/stripe/refund.rb +0 -7
  159. data/lib/stripe/reversal.rb +0 -14
  160. data/lib/stripe/sku.rb +0 -8
  161. data/lib/stripe/subscription.rb +0 -25
  162. data/lib/stripe/token.rb +0 -5
  163. data/lib/stripe/transfer.rb +0 -17
  164. data/test/stripe/account_test.rb +0 -118
  165. data/test/stripe/api_resource_test.rb +0 -632
  166. data/test/stripe/application_fee_refund_test.rb +0 -47
  167. data/test/stripe/application_fee_test.rb +0 -22
  168. data/test/stripe/balance_test.rb +0 -11
  169. data/test/stripe/bitcoin_receiver_test.rb +0 -61
  170. data/test/stripe/bitcoin_transaction_test.rb +0 -29
  171. data/test/stripe/charge_refund_test.rb +0 -55
  172. data/test/stripe/charge_test.rb +0 -118
  173. data/test/stripe/coupon_test.rb +0 -20
  174. data/test/stripe/customer_card_test.rb +0 -63
  175. data/test/stripe/customer_test.rb +0 -88
  176. data/test/stripe/dispute_test.rb +0 -45
  177. data/test/stripe/file_upload_test.rb +0 -28
  178. data/test/stripe/invoice_test.rb +0 -40
  179. data/test/stripe/list_object_test.rb +0 -16
  180. data/test/stripe/metadata_test.rb +0 -129
  181. data/test/stripe/order_test.rb +0 -52
  182. data/test/stripe/product_test.rb +0 -41
  183. data/test/stripe/recipient_card_test.rb +0 -57
  184. data/test/stripe/refund_test.rb +0 -55
  185. data/test/stripe/reversal_test.rb +0 -47
  186. data/test/stripe/sku_test.rb +0 -24
  187. data/test/stripe/stripe_object_test.rb +0 -28
  188. data/test/stripe/subscription_test.rb +0 -72
  189. data/test/stripe/transfer_test.rb +0 -25
  190. data/test/stripe/util_test.rb +0 -34
  191. data/test/test_data.rb +0 -666
  192. data/test/test_helper.rb +0 -41
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ # Configurable options:
5
+ #
6
+ # =ca_bundle_path=
7
+ # The location of a file containing a bundle of CA certificates. By default
8
+ # the library will use an included bundle that can successfully validate
9
+ # Stripe certificates.
10
+ #
11
+ # =log_level=
12
+ # When set prompts the library to log some extra information to $stdout and
13
+ # $stderr about what it's doing. For example, it'll produce information about
14
+ # requests, responses, and errors that are received. Valid log levels are
15
+ # `debug` and `info`, with `debug` being a little more verbose in places.
16
+ #
17
+ # Use of this configuration is only useful when `.logger` is _not_ set. When
18
+ # it is, the decision what levels to print is entirely deferred to the logger.
19
+ #
20
+ # =logger=
21
+ # The logger should support the same interface as the `Logger` class that's
22
+ # part of Ruby's standard library (hint, anything in `Rails.logger` will
23
+ # likely be suitable).
24
+ #
25
+ # If `.logger` is set, the value of `.log_level` is ignored. The decision on
26
+ # what levels to print is entirely deferred to the logger.
27
+ class StripeConfiguration
28
+ attr_accessor :api_key
29
+ attr_accessor :api_version
30
+ attr_accessor :client_id
31
+ attr_accessor :enable_telemetry
32
+ attr_accessor :logger
33
+ attr_accessor :stripe_account
34
+
35
+ attr_reader :api_base
36
+ attr_reader :uploads_base
37
+ attr_reader :connect_base
38
+ attr_reader :ca_bundle_path
39
+ attr_reader :log_level
40
+ attr_reader :initial_network_retry_delay
41
+ attr_reader :max_network_retries
42
+ attr_reader :max_network_retry_delay
43
+ attr_reader :open_timeout
44
+ attr_reader :read_timeout
45
+ attr_reader :write_timeout
46
+ attr_reader :proxy
47
+ attr_reader :verify_ssl_certs
48
+
49
+ def self.setup
50
+ new.tap do |instance|
51
+ yield(instance) if block_given?
52
+ end
53
+ end
54
+
55
+ # Create a new config based off an existing one. This is useful when the
56
+ # caller wants to override the global configuration
57
+ def reverse_duplicate_merge(hash)
58
+ dup.tap do |instance|
59
+ hash.each do |option, value|
60
+ instance.public_send("#{option}=", value)
61
+ end
62
+ end
63
+ end
64
+
65
+ def initialize
66
+ @ca_bundle_path = Stripe::DEFAULT_CA_BUNDLE_PATH
67
+ @enable_telemetry = true
68
+ @verify_ssl_certs = true
69
+
70
+ @max_network_retries = 0
71
+ @initial_network_retry_delay = 0.5
72
+ @max_network_retry_delay = 2
73
+
74
+ @open_timeout = 30
75
+ @read_timeout = 80
76
+ @write_timeout = 30
77
+
78
+ @api_base = "https://api.stripe.com"
79
+ @connect_base = "https://connect.stripe.com"
80
+ @uploads_base = "https://files.stripe.com"
81
+ end
82
+
83
+ def log_level=(val)
84
+ # Backwards compatibility for values that we briefly allowed
85
+ if val == "debug"
86
+ val = Stripe::LEVEL_DEBUG
87
+ elsif val == "info"
88
+ val = Stripe::LEVEL_INFO
89
+ end
90
+
91
+ levels = [Stripe::LEVEL_INFO, Stripe::LEVEL_DEBUG, Stripe::LEVEL_ERROR]
92
+
93
+ if !val.nil? && !levels.include?(val)
94
+ raise ArgumentError,
95
+ "log_level should only be set to `nil`, `debug` or `info`"
96
+ end
97
+ @log_level = val
98
+ end
99
+
100
+ def max_network_retries=(val)
101
+ @max_network_retries = val.to_i
102
+ end
103
+
104
+ def max_network_retry_delay=(val)
105
+ @max_network_retry_delay = val.to_i
106
+ end
107
+
108
+ def initial_network_retry_delay=(val)
109
+ @initial_network_retry_delay = val.to_i
110
+ end
111
+
112
+ def open_timeout=(open_timeout)
113
+ @open_timeout = open_timeout
114
+ StripeClient.clear_all_connection_managers(config: self)
115
+ end
116
+
117
+ def read_timeout=(read_timeout)
118
+ @read_timeout = read_timeout
119
+ StripeClient.clear_all_connection_managers(config: self)
120
+ end
121
+
122
+ def write_timeout=(write_timeout)
123
+ unless Net::HTTP.instance_methods.include?(:write_timeout=)
124
+ raise NotImplementedError
125
+ end
126
+
127
+ @write_timeout = write_timeout
128
+ StripeClient.clear_all_connection_managers(config: self)
129
+ end
130
+
131
+ def proxy=(proxy)
132
+ @proxy = proxy
133
+ StripeClient.clear_all_connection_managers(config: self)
134
+ end
135
+
136
+ def verify_ssl_certs=(verify_ssl_certs)
137
+ @verify_ssl_certs = verify_ssl_certs
138
+ StripeClient.clear_all_connection_managers(config: self)
139
+ end
140
+
141
+ def uploads_base=(uploads_base)
142
+ @uploads_base = uploads_base
143
+ StripeClient.clear_all_connection_managers(config: self)
144
+ end
145
+
146
+ def connect_base=(connect_base)
147
+ @connect_base = connect_base
148
+ StripeClient.clear_all_connection_managers(config: self)
149
+ end
150
+
151
+ def api_base=(api_base)
152
+ @api_base = api_base
153
+ StripeClient.clear_all_connection_managers(config: self)
154
+ end
155
+
156
+ def ca_bundle_path=(path)
157
+ @ca_bundle_path = path
158
+
159
+ # empty this field so a new store is initialized
160
+ @ca_store = nil
161
+
162
+ StripeClient.clear_all_connection_managers(config: self)
163
+ end
164
+
165
+ # A certificate store initialized from the the bundle in #ca_bundle_path and
166
+ # which is used to validate TLS on every request.
167
+ #
168
+ # This was added to the give the gem "pseudo thread safety" in that it seems
169
+ # when initiating many parallel requests marshaling the certificate store is
170
+ # the most likely point of failure (see issue #382). Any program attempting
171
+ # to leverage this pseudo safety should make a call to this method (i.e.
172
+ # `Stripe.ca_store`) in their initialization code because it marshals lazily
173
+ # and is itself not thread safe.
174
+ def ca_store
175
+ @ca_store ||= begin
176
+ store = OpenSSL::X509::Store.new
177
+ store.add_file(ca_bundle_path)
178
+ store
179
+ end
180
+ end
181
+
182
+ def enable_telemetry?
183
+ enable_telemetry
184
+ end
185
+
186
+ # Generates a deterministic key to identify configuration objects with
187
+ # identical configuration values.
188
+ def key
189
+ instance_variables
190
+ .collect { |variable| instance_variable_get(variable) }
191
+ .join
192
+ end
193
+ end
194
+ end
@@ -1,17 +1,79 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  class StripeObject
3
5
  include Enumerable
4
6
 
5
- @@permanent_attributes = Set.new([:id])
7
+ @@permanent_attributes = Set.new([:id]) # rubocop:disable Style/ClassVars
6
8
 
7
9
  # The default :id method is deprecated and isn't useful to us
8
- if method_defined?(:id)
9
- undef :id
10
+ undef :id if method_defined?(:id)
11
+
12
+ # Sets the given parameter name to one which is known to be an additive
13
+ # object.
14
+ #
15
+ # Additive objects are subobjects in the API that don't have the same
16
+ # semantics as most subobjects, which are fully replaced when they're set.
17
+ # This is best illustrated by example. The `source` parameter sent when
18
+ # updating a subscription is *not* additive; if we set it:
19
+ #
20
+ # source[object]=card&source[number]=123
21
+ #
22
+ # We expect the old `source` object to have been overwritten completely. If
23
+ # the previous source had an `address_state` key associated with it and we
24
+ # didn't send one this time, that value of `address_state` is gone.
25
+ #
26
+ # By contrast, additive objects are those that will have new data added to
27
+ # them while keeping any existing data in place. The only known case of its
28
+ # use is for `metadata`, but it could in theory be more general. As an
29
+ # example, say we have a `metadata` object that looks like this on the
30
+ # server side:
31
+ #
32
+ # metadata = { old: "old_value" }
33
+ #
34
+ # If we update the object with `metadata[new]=new_value`, the server side
35
+ # object now has *both* fields:
36
+ #
37
+ # metadata = { old: "old_value", new: "new_value" }
38
+ #
39
+ # This is okay in itself because usually users will want to treat it as
40
+ # additive:
41
+ #
42
+ # obj.metadata[:new] = "new_value"
43
+ # obj.save
44
+ #
45
+ # However, in other cases, they may want to replace the entire existing
46
+ # contents:
47
+ #
48
+ # obj.metadata = { new: "new_value" }
49
+ # obj.save
50
+ #
51
+ # This is where things get a little bit tricky because in order to clear
52
+ # any old keys that may have existed, we actually have to send an explicit
53
+ # empty string to the server. So the operation above would have to send
54
+ # this form to get the intended behavior:
55
+ #
56
+ # metadata[old]=&metadata[new]=new_value
57
+ #
58
+ # This method allows us to track which parameters are considered additive,
59
+ # and lets us behave correctly where appropriate when serializing
60
+ # parameters to be sent.
61
+ def self.additive_object_param(name)
62
+ @additive_params ||= Set.new
63
+ @additive_params << name
64
+ end
65
+
66
+ # Returns whether the given name is an additive object parameter. See
67
+ # `.additive_object_param` for details.
68
+ def self.additive_object_param?(name)
69
+ @additive_params ||= Set.new
70
+ @additive_params.include?(name)
10
71
  end
11
72
 
12
- def initialize(id=nil, opts={})
73
+ def initialize(id = nil, opts = {})
13
74
  id, @retrieve_params = Util.normalize_id(id)
14
- @opts = opts
75
+ @opts = Util.normalize_opts(opts)
76
+ @original_values = {}
15
77
  @values = {}
16
78
  # This really belongs in APIResource, but not putting it there allows us
17
79
  # to have a unified inspect method
@@ -20,52 +82,84 @@ module Stripe
20
82
  @values[:id] = id if id
21
83
  end
22
84
 
23
- def self.construct_from(values, opts={})
24
- self.new(values[:id]).refresh_from(values, opts)
85
+ def self.construct_from(values, opts = {})
86
+ values = Stripe::Util.symbolize_names(values)
87
+
88
+ # work around protected #initialize_from for now
89
+ new(values[:id]).send(:initialize_from, values, opts)
25
90
  end
26
91
 
27
- def to_s(*args)
28
- JSON.pretty_generate(@values)
92
+ # Determines the equality of two Stripe objects. Stripe objects are
93
+ # considered to be equal if they have the same set of values and each one
94
+ # of those values is the same.
95
+ def ==(other)
96
+ other.is_a?(StripeObject) &&
97
+ @values == other.instance_variable_get(:@values)
29
98
  end
30
99
 
31
- def inspect
32
- id_string = (self.respond_to?(:id) && !self.id.nil?) ? " id=#{self.id}" : ""
33
- "#<#{self.class}:0x#{self.object_id.to_s(16)}#{id_string}> JSON: " + JSON.pretty_generate(@values)
100
+ # Hash equality. As with `#==`, we consider two equivalent Stripe objects
101
+ # equal.
102
+ def eql?(other)
103
+ # Defer to the implementation on `#==`.
104
+ self == other
34
105
  end
35
106
 
36
- def refresh_from(values, opts, partial=false)
37
- @opts = opts
38
- @original_values = Marshal.load(Marshal.dump(values)) # deep copy
39
- removed = partial ? Set.new : Set.new(@values.keys - values.keys)
40
- added = Set.new(values.keys - @values.keys)
41
- # Wipe old state before setting new. This is useful for e.g. updating a
42
- # customer, where there is no persistent card parameter. Mark those values
43
- # which don't persist as transient
107
+ # As with equality in `#==` and `#eql?`, we hash two Stripe objects to the
108
+ # same value if they're equivalent objects.
109
+ def hash
110
+ @values.hash
111
+ end
44
112
 
45
- instance_eval do
46
- remove_accessors(removed)
47
- add_accessors(added)
48
- end
49
- removed.each do |k|
50
- @values.delete(k)
51
- @transient_values.add(k)
52
- @unsaved_values.delete(k)
53
- end
113
+ # Indicates whether or not the resource has been deleted on the server.
114
+ # Note that some, but not all, resources can indicate whether they have
115
+ # been deleted.
116
+ def deleted?
117
+ @values.fetch(:deleted, false)
118
+ end
119
+
120
+ def to_s(*_args)
121
+ JSON.pretty_generate(to_hash)
122
+ end
123
+
124
+ def inspect
125
+ id_string = respond_to?(:id) && !id.nil? ? " id=#{id}" : ""
126
+ "#<#{self.class}:0x#{object_id.to_s(16)}#{id_string}> JSON: " +
127
+ JSON.pretty_generate(@values)
128
+ end
129
+
130
+ # Mass assigns attributes on the model.
131
+ #
132
+ # This is a version of +update_attributes+ that takes some extra options
133
+ # for internal use.
134
+ #
135
+ # ==== Attributes
136
+ #
137
+ # * +values+ - Hash of values to use to update the current attributes of
138
+ # the object. If you are on ruby 2.7 or higher make sure to wrap in curly
139
+ # braces to be ruby 3 compatible.
140
+ # * +opts+ - Options for +StripeObject+ like an API key that will be reused
141
+ # on subsequent API calls.
142
+ #
143
+ # ==== Options
144
+ #
145
+ # * +:dirty+ - Whether values should be initiated as "dirty" (unsaved) and
146
+ # which applies only to new StripeObjects being initiated under this
147
+ # StripeObject. Defaults to true.
148
+ def update_attributes(values, opts = {}, dirty: true)
54
149
  values.each do |k, v|
55
- @values[k] = Util.convert_to_stripe_object(v, @opts)
56
- @transient_values.delete(k)
57
- @unsaved_values.delete(k)
150
+ add_accessors([k], values) unless metaclass.method_defined?(k.to_sym)
151
+ @values[k] = Util.convert_to_stripe_object(v, opts)
152
+ dirty_value!(@values[k]) if dirty
153
+ @unsaved_values.add(k)
58
154
  end
59
-
60
- return self
61
155
  end
62
156
 
63
- def [](k)
64
- @values[k.to_sym]
157
+ def [](key)
158
+ @values[key.to_sym]
65
159
  end
66
160
 
67
- def []=(k, v)
68
- send(:"#{k}=", v)
161
+ def []=(key, value)
162
+ send(:"#{key}=", value)
69
163
  end
70
164
 
71
165
  def keys
@@ -76,18 +170,29 @@ module Stripe
76
170
  @values.values
77
171
  end
78
172
 
79
- def to_json(*a)
173
+ def to_json(*_opts)
174
+ # TODO: pass opts to JSON.generate?
80
175
  JSON.generate(@values)
81
176
  end
82
177
 
83
- def as_json(*a)
84
- @values.as_json(*a)
178
+ def as_json(*opts)
179
+ @values.as_json(*opts)
85
180
  end
86
181
 
87
182
  def to_hash
88
- @values.inject({}) do |acc, (key, value)|
89
- acc[key] = value.respond_to?(:to_hash) ? value.to_hash : value
90
- acc
183
+ maybe_to_hash = lambda do |value|
184
+ return nil if value.nil?
185
+
186
+ value.respond_to?(:to_hash) ? value.to_hash : value
187
+ end
188
+
189
+ @values.each_with_object({}) do |(key, value), acc|
190
+ acc[key] = case value
191
+ when Array
192
+ value.map(&maybe_to_hash)
193
+ else
194
+ maybe_to_hash.call(value)
195
+ end
91
196
  end
92
197
  end
93
198
 
@@ -95,161 +200,389 @@ module Stripe
95
200
  @values.each(&blk)
96
201
  end
97
202
 
98
- def _dump(level)
99
- Marshal.dump([@values, @opts])
203
+ # Sets all keys within the StripeObject as unsaved so that they will be
204
+ # included with an update when #serialize_params is called. This method is
205
+ # also recursive, so any StripeObjects contained as values or which are
206
+ # values in a tenant array are also marked as dirty.
207
+ def dirty!
208
+ @unsaved_values = Set.new(@values.keys)
209
+ @values.each_value do |v|
210
+ dirty_value!(v)
211
+ end
100
212
  end
101
213
 
102
- def self._load(args)
103
- values, opts = Marshal.load(args)
104
- construct_from(values, opts)
214
+ # Implements custom encoding for Ruby's Marshal. The data produced by this
215
+ # method should be comprehendable by #marshal_load.
216
+ #
217
+ # This allows us to remove certain features that cannot or should not be
218
+ # serialized.
219
+ def marshal_dump
220
+ # The StripeClient instance in @opts is not serializable and is not
221
+ # really a property of the StripeObject, so we exclude it when
222
+ # dumping
223
+ opts = @opts.clone
224
+ opts.delete(:client)
225
+ [@values, opts]
105
226
  end
106
227
 
107
- if RUBY_VERSION < '1.9.2'
108
- def respond_to?(symbol)
109
- @values.has_key?(symbol) || super
110
- end
228
+ # Implements custom decoding for Ruby's Marshal. Consumes data that's
229
+ # produced by #marshal_dump.
230
+ def marshal_load(data)
231
+ values, opts = data
232
+ initialize(values[:id])
233
+ initialize_from(values, opts)
111
234
  end
112
235
 
113
- def serialize_nested_object(key)
114
- new_value = @values[key]
115
- if new_value.is_a?(APIResource)
116
- return {}
236
+ def serialize_params(options = {})
237
+ update_hash = {}
238
+
239
+ @values.each do |k, v|
240
+ # There are a few reasons that we may want to add in a parameter for
241
+ # update:
242
+ #
243
+ # 1. The `force` option has been set.
244
+ # 2. We know that it was modified.
245
+ # 3. Its value is a StripeObject. A StripeObject may contain modified
246
+ # values within in that its parent StripeObject doesn't know about.
247
+ #
248
+ unsaved = @unsaved_values.include?(k)
249
+ next unless options[:force] || unsaved || v.is_a?(StripeObject)
250
+
251
+ update_hash[k.to_sym] = serialize_params_value(
252
+ @values[k], @original_values[k], unsaved, options[:force], key: k
253
+ )
117
254
  end
118
255
 
119
- if @unsaved_values.include?(key)
120
- # the object has been reassigned
121
- # e.g. as object.key = {foo => bar}
122
- update = new_value
123
- new_keys = update.keys.map(&:to_sym)
124
-
125
- # remove keys at the server, but not known locally
126
- if @original_values[key]
127
- keys_to_unset = @original_values[key].keys - new_keys
128
- keys_to_unset.each {|key| update[key] = ''}
129
- end
256
+ # a `nil` that makes it out of `#serialize_params_value` signals an empty
257
+ # value that we shouldn't appear in the serialized form of the object
258
+ update_hash.reject! { |_, v| v.nil? }
130
259
 
131
- update
132
- else
133
- # can be serialized normally
134
- self.class.serialize_params(new_value)
135
- end
260
+ update_hash
136
261
  end
137
262
 
138
- def self.serialize_params(obj, original_value=nil)
139
- case obj
140
- when nil
141
- ''
142
- when StripeObject
143
- unsaved_keys = obj.instance_variable_get(:@unsaved_values)
144
- obj_values = obj.instance_variable_get(:@values)
145
- update_hash = {}
146
-
147
- unsaved_keys.each do |k|
148
- update_hash[k] = serialize_params(obj_values[k])
149
- end
150
-
151
- obj_values.each do |k, v|
152
- if v.is_a?(StripeObject) || v.is_a?(Hash)
153
- update_hash[k] = obj.serialize_nested_object(k)
154
- elsif v.is_a?(Array)
155
- original_value = obj.instance_variable_get(:@original_values)[k]
156
- if original_value && original_value.length > v.length
157
- # url params provide no mechanism for deleting an item in an array,
158
- # just overwriting the whole array or adding new items. So let's not
159
- # allow deleting without a full overwrite until we have a solution.
160
- raise ArgumentError.new(
161
- "You cannot delete an item from an array, you must instead set a new array"
162
- )
163
- end
164
- update_hash[k] = serialize_params(v, original_value)
165
- end
166
- end
167
-
168
- update_hash
169
- when Array
170
- update_hash = {}
171
- obj.each_with_index do |value, index|
172
- update = serialize_params(value)
173
- if update != {} && (!original_value || update != original_value[index])
174
- update_hash[index] = update
175
- end
176
- end
177
-
178
- if update_hash == {}
179
- nil
180
- else
181
- update_hash
182
- end
183
- else
184
- obj
185
- end
263
+ # A protected field is one that doesn't get an accessor assigned to it
264
+ # (i.e. `obj.public = ...`) and one which is not allowed to be updated via
265
+ # the class level `Model.update(id, { ... })`.
266
+ def self.protected_fields
267
+ []
186
268
  end
187
269
 
188
- protected
189
-
190
- def metaclass
270
+ # When designing APIs, we now make a conscious effort server-side to avoid
271
+ # naming fields after important built-ins in various languages (e.g. class,
272
+ # method, etc.).
273
+ #
274
+ # However, a long time ago we made the mistake (either consciously or by
275
+ # accident) of initializing our `metadata` fields as instances of
276
+ # `StripeObject`, and metadata can have a wide range of different keys
277
+ # defined in it. This is somewhat a convenient in that it allows users to
278
+ # access data like `obj.metadata.my_field`, but is almost certainly not
279
+ # worth the cost.
280
+ #
281
+ # Naming metadata fields bad things like `class` causes `initialize_from`
282
+ # to produce strange results, so we ban known offenders here.
283
+ #
284
+ # In a future major version we should consider leaving `metadata` as a hash
285
+ # and forcing people to access it with `obj.metadata[:my_field]` because
286
+ # the potential for trouble is just too high. For now, reserve names.
287
+ RESERVED_FIELD_NAMES = [
288
+ :class,
289
+ ].freeze
290
+
291
+ protected def metaclass
191
292
  class << self; self; end
192
293
  end
193
294
 
194
- def remove_accessors(keys)
295
+ protected def remove_accessors(keys)
296
+ # not available in the #instance_eval below
297
+ protected_fields = self.class.protected_fields
298
+
195
299
  metaclass.instance_eval do
196
300
  keys.each do |k|
301
+ next if RESERVED_FIELD_NAMES.include?(k)
302
+ next if protected_fields.include?(k)
197
303
  next if @@permanent_attributes.include?(k)
198
- k_eq = :"#{k}="
199
- remove_method(k) if method_defined?(k)
200
- remove_method(k_eq) if method_defined?(k_eq)
304
+
305
+ # Remove methods for the accessor's reader and writer.
306
+ [k, :"#{k}=", :"#{k}?"].each do |method_name|
307
+ next unless method_defined?(method_name)
308
+
309
+ begin
310
+ remove_method(method_name)
311
+ rescue NameError
312
+ # In some cases there can be a method that's detected with
313
+ # `method_defined?`, but which cannot be removed with
314
+ # `remove_method`, even though it's on the same class. The only
315
+ # case so far that we've noticed this is when a class is
316
+ # reopened for monkey patching:
317
+ #
318
+ # https://github.com/stripe/stripe-ruby/issues/749
319
+ #
320
+ # Here we swallow that error and issue a warning so at least
321
+ # the program doesn't crash.
322
+ warn("WARNING: Unable to remove method `#{method_name}`; " \
323
+ "if custom, please consider renaming to a name that doesn't " \
324
+ "collide with an API property name.")
325
+ end
326
+ end
201
327
  end
202
328
  end
203
329
  end
204
330
 
205
- def add_accessors(keys)
331
+ protected def add_accessors(keys, values)
332
+ # not available in the #instance_eval below
333
+ protected_fields = self.class.protected_fields
334
+
206
335
  metaclass.instance_eval do
207
336
  keys.each do |k|
337
+ next if RESERVED_FIELD_NAMES.include?(k)
338
+ next if protected_fields.include?(k)
208
339
  next if @@permanent_attributes.include?(k)
209
- k_eq = :"#{k}="
210
- define_method(k) { @values[k] }
211
- define_method(k_eq) do |v|
340
+
341
+ if k == :method
342
+ # Object#method is a built-in Ruby method that accepts a symbol
343
+ # and returns the corresponding Method object. Because the API may
344
+ # also use `method` as a field name, we check the arity of *args
345
+ # to decide whether to act as a getter or call the parent method.
346
+ define_method(k) { |*args| args.empty? ? @values[k] : super(*args) }
347
+ else
348
+ define_method(k) { @values[k] }
349
+ end
350
+
351
+ define_method(:"#{k}=") do |v|
212
352
  if v == ""
213
- raise ArgumentError.new(
214
- "You cannot set #{k} to an empty string." \
215
- "We interpret empty strings as nil in requests." \
216
- "You may set #{self}.#{k} = nil to delete the property.")
353
+ raise ArgumentError, "You cannot set #{k} to an empty string. " \
354
+ "We interpret empty strings as nil in requests. " \
355
+ "You may set (object).#{k} = nil to delete the property."
217
356
  end
218
- @values[k] = v
357
+ @values[k] = Util.convert_to_stripe_object(v, @opts)
358
+ dirty_value!(@values[k])
219
359
  @unsaved_values.add(k)
220
360
  end
361
+
362
+ if [FalseClass, TrueClass].include?(values[k].class)
363
+ define_method(:"#{k}?") { @values[k] }
364
+ end
221
365
  end
222
366
  end
223
367
  end
224
368
 
225
- def method_missing(name, *args)
369
+ # Disabling the cop because it's confused by the fact that the methods are
370
+ # protected, but we do define `#respond_to_missing?` just below. Hopefully
371
+ # this is fixed in more recent Rubocop versions.
372
+ # rubocop:disable Style/MissingRespondToMissing
373
+ protected def method_missing(name, *args)
226
374
  # TODO: only allow setting in updateable classes.
227
- if name.to_s.end_with?('=')
375
+ if name.to_s.end_with?("=")
228
376
  attr = name.to_s[0...-1].to_sym
229
- add_accessors([attr])
377
+
378
+ # Pull out the assigned value. This is only used in the case of a
379
+ # boolean value to add a question mark accessor (i.e. `foo?`) for
380
+ # convenience.
381
+ val = args.first
382
+
383
+ # the second argument is only required when adding boolean accessors
384
+ add_accessors([attr], attr => val)
385
+
230
386
  begin
231
387
  mth = method(name)
232
388
  rescue NameError
233
- raise NoMethodError.new("Cannot set #{attr} on this object. HINT: you can't set: #{@@permanent_attributes.to_a.join(', ')}")
389
+ raise NoMethodError,
390
+ "Cannot set #{attr} on this object. HINT: you can't set: " \
391
+ "#{@@permanent_attributes.to_a.join(', ')}"
234
392
  end
235
393
  return mth.call(args[0])
236
- else
237
- return @values[name] if @values.has_key?(name)
394
+ elsif @values.key?(name)
395
+ return @values[name]
238
396
  end
239
397
 
240
398
  begin
241
399
  super
242
400
  rescue NoMethodError => e
243
- if @transient_values.include?(name)
244
- raise NoMethodError.new(e.message + ". HINT: The '#{name}' attribute was set in the past, however. It was then wiped when refreshing the object with the result returned by Stripe's API, probably as a result of a save(). The attributes currently available on this object are: #{@values.keys.join(', ')}")
401
+ # If we notice the accessed name of our set of transient values we can
402
+ # give the user a slightly more helpful error message. If not, just
403
+ # raise right away.
404
+ raise unless @transient_values.include?(name)
405
+
406
+ raise NoMethodError,
407
+ e.message + ". HINT: The '#{name}' attribute was set in the " \
408
+ "past, however. It was then wiped when refreshing the object " \
409
+ "with the result returned by Stripe's API, probably as a " \
410
+ "result of a save(). The attributes currently available on " \
411
+ "this object are: #{@values.keys.join(', ')}"
412
+ end
413
+ end
414
+ # rubocop:enable Style/MissingRespondToMissing
415
+
416
+ protected def respond_to_missing?(symbol, include_private = false)
417
+ @values && @values.key?(symbol) || super
418
+ end
419
+
420
+ # Re-initializes the object based on a hash of values (usually one that's
421
+ # come back from an API call). Adds or removes value accessors as necessary
422
+ # and updates the state of internal data.
423
+ #
424
+ # Protected on purpose! Please do not expose.
425
+ #
426
+ # ==== Options
427
+ #
428
+ # * +:values:+ Hash used to update accessors and values.
429
+ # * +:opts:+ Options for StripeObject like an API key.
430
+ # * +:partial:+ Indicates that the re-initialization should not attempt to
431
+ # remove accessors.
432
+ protected def initialize_from(values, opts, partial = false)
433
+ @opts = Util.normalize_opts(opts)
434
+
435
+ # the `#send` is here so that we can keep this method private
436
+ @original_values = self.class.send(:deep_copy, values)
437
+
438
+ removed = partial ? Set.new : Set.new(@values.keys - values.keys)
439
+ added = Set.new(values.keys - @values.keys)
440
+
441
+ # Wipe old state before setting new. This is useful for e.g. updating a
442
+ # customer, where there is no persistent card parameter. Mark those
443
+ # values which don't persist as transient
444
+
445
+ remove_accessors(removed)
446
+ add_accessors(added, values)
447
+
448
+ removed.each do |k|
449
+ @values.delete(k)
450
+ @transient_values.add(k)
451
+ @unsaved_values.delete(k)
452
+ end
453
+
454
+ update_attributes(values, opts, dirty: false)
455
+ values.each_key do |k|
456
+ @transient_values.delete(k)
457
+ @unsaved_values.delete(k)
458
+ end
459
+
460
+ self
461
+ end
462
+
463
+ protected def serialize_params_value(value, original, unsaved, force,
464
+ key: nil)
465
+ if value.nil?
466
+ ""
467
+
468
+ # The logic here is that essentially any object embedded in another
469
+ # object that had a `type` is actually an API resource of a different
470
+ # type that's been included in the response. These other resources must
471
+ # be updated from their proper endpoints, and therefore they are not
472
+ # included when serializing even if they've been modified.
473
+ #
474
+ # There are _some_ known exceptions though.
475
+ #
476
+ # For example, if the value is unsaved (meaning the user has set it), and
477
+ # it looks like the API resource is persisted with an ID, then we include
478
+ # the object so that parameters are serialized with a reference to its
479
+ # ID.
480
+ #
481
+ # Another example is that on save API calls it's sometimes desirable to
482
+ # update a customer's default source by setting a new card (or other)
483
+ # object with `#source=` and then saving the customer. The
484
+ # `#save_with_parent` flag to override the default behavior allows us to
485
+ # handle these exceptions.
486
+ #
487
+ # We throw an error if a property was set explicitly but we can't do
488
+ # anything with it because the integration is probably not working as the
489
+ # user intended it to.
490
+ elsif value.is_a?(APIResource) && !value.save_with_parent
491
+ if !unsaved
492
+ nil
493
+ elsif value.respond_to?(:id) && !value.id.nil?
494
+ value
245
495
  else
246
- raise
496
+ raise ArgumentError, "Cannot save property `#{key}` containing " \
497
+ "an API resource. It doesn't appear to be persisted and is " \
498
+ "not marked as `save_with_parent`."
247
499
  end
500
+
501
+ elsif value.is_a?(Array)
502
+ update = value.map { |v| serialize_params_value(v, nil, true, force) }
503
+
504
+ # This prevents an array that's unchanged from being resent.
505
+ update if update != serialize_params_value(original, nil, true, force)
506
+
507
+ # Handle a Hash for now, but in the long run we should be able to
508
+ # eliminate all places where hashes are stored as values internally by
509
+ # making sure any time one is set, we convert it to a StripeObject. This
510
+ # will simplify our model by making data within an object more
511
+ # consistent.
512
+ #
513
+ # For now, you can still run into a hash if someone appends one to an
514
+ # existing array being held by a StripeObject. This could happen for
515
+ # example by appending a new hash onto `additional_owners` for an
516
+ # account.
517
+ elsif value.is_a?(Hash)
518
+ Util.convert_to_stripe_object(value, @opts).serialize_params
519
+
520
+ elsif value.is_a?(StripeObject)
521
+ update = value.serialize_params(force: force)
522
+
523
+ # If the entire object was replaced and this is an additive object,
524
+ # then we need blank each field of the old object that held a value
525
+ # because otherwise the update to the keys of the object will be
526
+ # additive instead of a full replacement. The new serialized values
527
+ # will override any of these empty values.
528
+ if original && unsaved && key && self.class.additive_object_param?(key)
529
+ update = empty_values(original).merge(update)
530
+ end
531
+
532
+ update
533
+
534
+ else
535
+ value
248
536
  end
249
537
  end
250
538
 
251
- def respond_to_missing?(symbol, include_private = false)
252
- @values && @values.has_key?(symbol) || super
539
+ # Produces a deep copy of the given object including support for arrays,
540
+ # hashes, and StripeObjects.
541
+ private_class_method def self.deep_copy(obj)
542
+ case obj
543
+ when Array
544
+ obj.map { |e| deep_copy(e) }
545
+ when Hash
546
+ obj.each_with_object({}) do |(k, v), copy|
547
+ copy[k] = deep_copy(v)
548
+ copy
549
+ end
550
+ when StripeObject
551
+ obj.class.construct_from(
552
+ deep_copy(obj.instance_variable_get(:@values)),
553
+ obj.instance_variable_get(:@opts).select do |k, _v|
554
+ Util::OPTS_COPYABLE.include?(k)
555
+ end
556
+ )
557
+ else
558
+ obj
559
+ end
560
+ end
561
+
562
+ private def dirty_value!(value)
563
+ case value
564
+ when Array
565
+ value.map { |v| dirty_value!(v) }
566
+ when StripeObject
567
+ value.dirty!
568
+ end
569
+ end
570
+
571
+ # Returns a hash of empty values for all the values that are in the given
572
+ # StripeObject.
573
+ private def empty_values(obj)
574
+ values = case obj
575
+ when Hash then obj
576
+ when StripeObject then obj.instance_variable_get(:@values)
577
+ else
578
+ raise ArgumentError,
579
+ "#empty_values got unexpected object type: " \
580
+ "#{obj.class.name}"
581
+ end
582
+
583
+ values.each_with_object({}) do |(k, _), update|
584
+ update[k] = ""
585
+ end
253
586
  end
254
587
  end
255
588
  end