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
@@ -1,14 +1,54 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
- # StripeResponse encapsulates some vitals of a response that came back from
3
- # the Stripe API.
4
- class StripeResponse
5
- # The data contained by the HTTP body of the response deserialized from
6
- # JSON.
7
- attr_accessor :data
4
+ # Headers provides an access wrapper to an API response's header data. It
5
+ # mainly exists so that we don't need to expose the entire
6
+ # `Net::HTTPResponse` object while still getting some of its benefits like
7
+ # case-insensitive access to header names and flattening of header values.
8
+ class StripeResponseHeaders
9
+ # Initializes a Headers object from a Net::HTTP::HTTPResponse object.
10
+ def self.from_net_http(resp)
11
+ new(resp.to_hash)
12
+ end
8
13
 
9
- # The raw HTTP body of the response.
10
- attr_accessor :http_body
14
+ # `hash` is expected to be a hash mapping header names to arrays of
15
+ # header values. This is the default format generated by calling
16
+ # `#to_hash` on a `Net::HTTPResponse` object because headers can be
17
+ # repeated multiple times. Using `#[]` will collapse values down to just
18
+ # the first.
19
+ def initialize(hash)
20
+ if !hash.is_a?(Hash) ||
21
+ !hash.keys.all? { |n| n.is_a?(String) } ||
22
+ !hash.values.all? { |a| a.is_a?(Array) } ||
23
+ !hash.values.all? { |a| a.all? { |v| v.is_a?(String) } }
24
+ raise ArgumentError,
25
+ "expect hash to be a map of string header names to arrays of " \
26
+ "header values"
27
+ end
28
+
29
+ @hash = {}
11
30
 
31
+ # This shouldn't be strictly necessary because `Net::HTTPResponse` will
32
+ # produce a hash with all headers downcased, but do it anyway just in
33
+ # case an object of this class was constructed manually.
34
+ #
35
+ # Also has the effect of duplicating the hash, which is desirable for a
36
+ # little extra object safety.
37
+ hash.each do |k, v|
38
+ @hash[k.downcase] = v
39
+ end
40
+ end
41
+
42
+ def [](name)
43
+ values = @hash[name.downcase]
44
+ if values && values.count > 1
45
+ warn("Duplicate header values for `#{name}`; returning only first")
46
+ end
47
+ values ? values.first : nil
48
+ end
49
+ end
50
+
51
+ module StripeResponseBase
12
52
  # A Hash of the HTTP headers of the response.
13
53
  attr_accessor :http_headers
14
54
 
@@ -18,30 +58,52 @@ module Stripe
18
58
  # The Stripe request ID of the response.
19
59
  attr_accessor :request_id
20
60
 
21
- # Initializes a StripeResponse object from a Hash like the kind returned as
22
- # part of a Faraday exception.
23
- #
24
- # This may throw JSON::ParserError if the response body is not valid JSON.
25
- def self.from_faraday_hash(http_resp)
26
- resp = StripeResponse.new
27
- resp.data = JSON.parse(http_resp[:body], symbolize_names: true)
28
- resp.http_body = http_resp[:body]
29
- resp.http_headers = http_resp[:headers]
30
- resp.http_status = http_resp[:status]
31
- resp.request_id = http_resp[:headers]["Request-Id"]
32
- resp
61
+ def self.populate_for_net_http(resp, http_resp)
62
+ resp.http_headers = StripeResponseHeaders.from_net_http(http_resp)
63
+ resp.http_status = http_resp.code.to_i
64
+ resp.request_id = http_resp["request-id"]
33
65
  end
66
+ end
34
67
 
35
- # Initializes a StripeResponse object from a Faraday HTTP response object.
36
- #
37
- # This may throw JSON::ParserError if the response body is not valid JSON.
38
- def self.from_faraday_response(http_resp)
68
+ # StripeResponse encapsulates some vitals of a response that came back from
69
+ # the Stripe API.
70
+ class StripeResponse
71
+ include StripeResponseBase
72
+ # The data contained by the HTTP body of the response deserialized from
73
+ # JSON.
74
+ attr_accessor :data
75
+
76
+ # The raw HTTP body of the response.
77
+ attr_accessor :http_body
78
+
79
+ # Initializes a StripeResponse object from a Net::HTTP::HTTPResponse
80
+ # object.
81
+ def self.from_net_http(http_resp)
39
82
  resp = StripeResponse.new
40
83
  resp.data = JSON.parse(http_resp.body, symbolize_names: true)
41
84
  resp.http_body = http_resp.body
42
- resp.http_headers = http_resp.headers
43
- resp.http_status = http_resp.status
44
- resp.request_id = http_resp.headers["Request-Id"]
85
+ StripeResponseBase.populate_for_net_http(resp, http_resp)
86
+ resp
87
+ end
88
+ end
89
+
90
+ # We have to alias StripeResponseHeaders to StripeResponse::Headers, as this
91
+ # class used to be embedded within StripeResponse and we want to be backwards
92
+ # compatible.
93
+ StripeResponse::Headers = StripeResponseHeaders
94
+
95
+ # StripeHeadersOnlyResponse includes only header-related vitals of the
96
+ # response. This is used for streaming requests where the response was read
97
+ # directly in a block and we explicitly don't want to store the body of the
98
+ # response in memory.
99
+ class StripeHeadersOnlyResponse
100
+ include StripeResponseBase
101
+
102
+ # Initializes a StripeHeadersOnlyResponse object from a
103
+ # Net::HTTP::HTTPResponse object.
104
+ def self.from_net_http(http_resp)
105
+ resp = StripeHeadersOnlyResponse.new
106
+ StripeResponseBase.populate_for_net_http(resp, http_resp)
45
107
  resp
46
108
  end
47
109
  end
data/lib/stripe/util.rb CHANGED
@@ -1,62 +1,97 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require "cgi"
2
4
 
3
5
  module Stripe
4
6
  module Util
5
- def self.objects_to_ids(h)
6
- case h
7
+ # Options that a user is allowed to specify.
8
+ OPTS_USER_SPECIFIED = Set[
9
+ :api_key,
10
+ :idempotency_key,
11
+ :stripe_account,
12
+ :stripe_version
13
+ ].freeze
14
+
15
+ # Options that should be copyable from one StripeObject to another
16
+ # including options that may be internal.
17
+ OPTS_COPYABLE = (
18
+ OPTS_USER_SPECIFIED + Set[:api_base]
19
+ ).freeze
20
+
21
+ # Options that should be persisted between API requests. This includes
22
+ # client, which is an object containing an HTTP client to reuse.
23
+ OPTS_PERSISTABLE = (
24
+ OPTS_USER_SPECIFIED + Set[:client] - Set[:idempotency_key]
25
+ ).freeze
26
+
27
+ def self.objects_to_ids(obj)
28
+ case obj
7
29
  when APIResource
8
- h.id
30
+ obj.id
9
31
  when Hash
10
32
  res = {}
11
- h.each { |k, v| res[k] = objects_to_ids(v) unless v.nil? }
33
+ obj.each { |k, v| res[k] = objects_to_ids(v) unless v.nil? }
12
34
  res
13
35
  when Array
14
- h.map { |v| objects_to_ids(v) }
36
+ obj.map { |v| objects_to_ids(v) }
15
37
  else
16
- h
38
+ obj
17
39
  end
18
40
  end
19
41
 
20
42
  def self.object_classes
21
- @object_classes ||= {
22
- # data structures
23
- 'list' => ListObject,
24
-
25
- # business objects
26
- 'account' => Account,
27
- 'alipay_account' => AlipayAccount,
28
- 'apple_pay_domain' => ApplePayDomain,
29
- 'application_fee' => ApplicationFee,
30
- 'balance' => Balance,
31
- 'balance_transaction' => BalanceTransaction,
32
- 'bank_account' => BankAccount,
33
- 'bitcoin_receiver' => BitcoinReceiver,
34
- 'bitcoin_transaction' => BitcoinTransaction,
35
- 'card' => Card,
36
- 'charge' => Charge,
37
- 'country_spec' => CountrySpec,
38
- 'coupon' => Coupon,
39
- 'customer' => Customer,
40
- 'dispute' => Dispute,
41
- 'event' => Event,
42
- 'fee_refund' => ApplicationFeeRefund,
43
- 'file_upload' => FileUpload,
44
- 'invoice' => Invoice,
45
- 'invoiceitem' => InvoiceItem,
46
- 'order' => Order,
47
- 'order_return' => OrderReturn,
48
- 'plan' => Plan,
49
- 'product' => Product,
50
- 'recipient' => Recipient,
51
- 'refund' => Refund,
52
- 'sku' => SKU,
53
- 'subscription' => Subscription,
54
- 'subscription_item' => SubscriptionItem,
55
- 'three_d_secure' => ThreeDSecure,
56
- 'token' => Token,
57
- 'transfer' => Transfer,
58
- 'transfer_reversal' => Reversal,
59
- }
43
+ @object_classes ||= Stripe::ObjectTypes.object_names_to_classes
44
+ end
45
+
46
+ def self.object_name_matches_class?(object_name, klass)
47
+ Util.object_classes[object_name] == klass
48
+ end
49
+
50
+ # Adds a custom method to a resource class. This is used to add support for
51
+ # non-CRUDL API requests, e.g. capturing charges. custom_method takes the
52
+ # following parameters:
53
+ # - name: the name of the custom method to create (as a symbol)
54
+ # - http_verb: the HTTP verb for the API request (:get, :post, or :delete)
55
+ # - http_path: the path to append to the resource's URL. If not provided,
56
+ # the name is used as the path
57
+ # - resource: the resource implementation class
58
+ # - target: the class that custom static method will be added to
59
+ #
60
+ # For example, this call:
61
+ # custom_method :capture, http_verb: post
62
+ # adds a `capture` class method to the resource class that, when called,
63
+ # will send a POST request to `/v1/<object_name>/capture`.
64
+ def self.custom_method(resource, target, name, http_verb, http_path)
65
+ unless %i[get post delete].include?(http_verb)
66
+ raise ArgumentError,
67
+ "Invalid http_verb value: #{http_verb.inspect}. Should be one " \
68
+ "of :get, :post or :delete."
69
+ end
70
+ unless target.respond_to?(:resource_url)
71
+ raise ArgumentError,
72
+ "Invalid target value: #{target}. Target class should have a " \
73
+ "`resource_url` method."
74
+ end
75
+ http_path ||= name.to_s
76
+ target.define_singleton_method(name) do |id, params = {}, opts = {}|
77
+ unless id.is_a?(String)
78
+ raise ArgumentError,
79
+ "id should be a string representing the ID of an API resource"
80
+ end
81
+
82
+ url = "#{target.resource_url}/"\
83
+ "#{CGI.escape(id)}/"\
84
+ "#{CGI.escape(http_path)}"
85
+
86
+ resp, opts = resource.execute_resource_request(
87
+ http_verb,
88
+ url,
89
+ params,
90
+ opts
91
+ )
92
+
93
+ Util.convert_to_stripe_object(resp.data, opts)
94
+ end
60
95
  end
61
96
 
62
97
  # Converts a hash of fields or an array of hashes into a +StripeObject+ or
@@ -71,28 +106,49 @@ module Stripe
71
106
  # * +data+ - Hash of fields and values to be converted into a StripeObject.
72
107
  # * +opts+ - Options for +StripeObject+ like an API key that will be reused
73
108
  # on subsequent API calls.
74
- def self.convert_to_stripe_object(data, opts)
109
+ def self.convert_to_stripe_object(data, opts = {})
110
+ opts = normalize_opts(opts)
111
+
75
112
  case data
76
113
  when Array
77
114
  data.map { |i| convert_to_stripe_object(i, opts) }
78
115
  when Hash
79
- # Try converting to a known object class. If none available, fall back to generic StripeObject
80
- object_classes.fetch(data[:object], StripeObject).construct_from(data, opts)
116
+ # Try converting to a known object class. If none available, fall back
117
+ # to generic StripeObject
118
+ object_classes.fetch(data[:object], StripeObject)
119
+ .construct_from(data, opts)
81
120
  else
82
121
  data
83
122
  end
84
123
  end
85
124
 
86
- def self.file_readable(file)
87
- # This is nominally equivalent to File.readable?, but that can
88
- # report incorrect results on some more oddball filesystems
89
- # (such as AFS)
90
- begin
91
- File.open(file) { |f| }
92
- rescue
93
- false
94
- else
95
- true
125
+ def self.log_error(message, data = {})
126
+ config = data.delete(:config) || Stripe.config
127
+ logger = config.logger || Stripe.logger
128
+ if !logger.nil? ||
129
+ !config.log_level.nil? && config.log_level <= Stripe::LEVEL_ERROR
130
+ log_internal(message, data, color: :cyan, level: Stripe::LEVEL_ERROR,
131
+ logger: Stripe.logger, out: $stderr)
132
+ end
133
+ end
134
+
135
+ def self.log_info(message, data = {})
136
+ config = data.delete(:config) || Stripe.config
137
+ logger = config.logger || Stripe.logger
138
+ if !logger.nil? ||
139
+ !config.log_level.nil? && config.log_level <= Stripe::LEVEL_INFO
140
+ log_internal(message, data, color: :cyan, level: Stripe::LEVEL_INFO,
141
+ logger: Stripe.logger, out: $stdout)
142
+ end
143
+ end
144
+
145
+ def self.log_debug(message, data = {})
146
+ config = data.delete(:config) || Stripe.config
147
+ logger = config.logger || Stripe.logger
148
+ if !logger.nil? ||
149
+ !config.log_level.nil? && config.log_level <= Stripe::LEVEL_DEBUG
150
+ log_internal(message, data, color: :blue, level: Stripe::LEVEL_DEBUG,
151
+ logger: Stripe.logger, out: $stdout)
96
152
  end
97
153
  end
98
154
 
@@ -101,7 +157,11 @@ module Stripe
101
157
  when Hash
102
158
  new_hash = {}
103
159
  object.each do |key, value|
104
- key = (key.to_sym rescue key) || key
160
+ key = (begin
161
+ key.to_sym
162
+ rescue StandardError
163
+ key
164
+ end) || key
105
165
  new_hash[key] = symbolize_names(value)
106
166
  end
107
167
  new_hash
@@ -117,22 +177,8 @@ module Stripe
117
177
  # involves escaping special characters from parameter keys and values (e.g.
118
178
  # `&`).
119
179
  def self.encode_parameters(params)
120
- Util.flatten_params(params).
121
- map { |k,v| "#{url_encode(k)}=#{url_encode(v)}" }.join('&')
122
- end
123
-
124
- # Transforms an array into a hash with integer keys. Used for a small
125
- # number of API endpoints. If the argument is not an Array, return it
126
- # unchanged. Example: [{foo: 'bar'}] => {"0" => {foo: "bar"}}
127
- def self.array_to_hash(array)
128
- case array
129
- when Array
130
- hash = {}
131
- array.each_with_index { |v,i| hash[i.to_s] = v }
132
- hash
133
- else
134
- array
135
- end
180
+ Util.flatten_params(params)
181
+ .map { |k, v| "#{url_encode(k)}=#{url_encode(v)}" }.join("&")
136
182
  end
137
183
 
138
184
  # Encodes a string in a way that makes it suitable for use in a set of
@@ -143,20 +189,19 @@ module Stripe
143
189
  # Don't use strict form encoding by changing the square bracket control
144
190
  # characters back to their literals. This is fine by the server, and
145
191
  # makes these parameter strings easier to read.
146
- gsub('%5B', '[').gsub('%5D', ']')
192
+ gsub("%5B", "[").gsub("%5D", "]")
147
193
  end
148
194
 
149
- def self.flatten_params(params, parent_key=nil)
195
+ def self.flatten_params(params, parent_key = nil)
150
196
  result = []
151
197
 
152
198
  # do not sort the final output because arrays (and arrays of hashes
153
199
  # especially) can be order sensitive, but do sort incoming parameters
154
200
  params.each do |key, value|
155
- calculated_key = parent_key ? "#{parent_key}[#{key}]" : "#{key}"
201
+ calculated_key = parent_key ? "#{parent_key}[#{key}]" : key.to_s
156
202
  if value.is_a?(Hash)
157
203
  result += flatten_params(value, calculated_key)
158
204
  elsif value.is_a?(Array)
159
- check_array_of_maps_start_keys!(value)
160
205
  result += flatten_params_array(value, calculated_key)
161
206
  else
162
207
  result << [calculated_key, value]
@@ -168,20 +213,32 @@ module Stripe
168
213
 
169
214
  def self.flatten_params_array(value, calculated_key)
170
215
  result = []
171
- value.each do |elem|
216
+ value.each_with_index do |elem, i|
172
217
  if elem.is_a?(Hash)
173
- result += flatten_params(elem, "#{calculated_key}[]")
218
+ result += flatten_params(elem, "#{calculated_key}[#{i}]")
174
219
  elsif elem.is_a?(Array)
175
220
  result += flatten_params_array(elem, calculated_key)
176
221
  else
177
- result << ["#{calculated_key}[]", elem]
222
+ result << ["#{calculated_key}[#{i}]", elem]
178
223
  end
179
224
  end
180
225
  result
181
226
  end
182
227
 
228
+ # `Time.now` can be unstable in cases like an administrator manually
229
+ # updating its value or a reconcilation via NTP. For this reason, prefer
230
+ # the use of the system's monotonic clock especially where comparing times
231
+ # to calculate an elapsed duration.
232
+ #
233
+ # Shortcut for getting monotonic time, mostly for purposes of line length
234
+ # and test stubbing. Returns time in seconds since the event used for
235
+ # monotonic reference purposes by the platform (e.g. system boot time).
236
+ def self.monotonic_time
237
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
238
+ end
239
+
183
240
  def self.normalize_id(id)
184
- if id.kind_of?(Hash) # overloaded id
241
+ if id.is_a?(Hash) # overloaded id
185
242
  params_hash = id.dup
186
243
  id = params_hash.delete(:id)
187
244
  else
@@ -195,62 +252,155 @@ module Stripe
195
252
  def self.normalize_opts(opts)
196
253
  case opts
197
254
  when String
198
- {:api_key => opts}
255
+ { api_key: opts }
199
256
  when Hash
200
- check_api_key!(opts.fetch(:api_key)) if opts.has_key?(:api_key)
201
- opts.clone
257
+ check_api_key!(opts.fetch(:api_key)) if opts.key?(:api_key)
258
+ # Explicitly use dup here instead of clone to avoid preserving freeze
259
+ # state on input params.
260
+ opts.dup
202
261
  else
203
- raise TypeError.new('normalize_opts expects a string or a hash')
262
+ raise TypeError, "normalize_opts expects a string or a hash"
204
263
  end
205
264
  end
206
265
 
207
266
  def self.check_string_argument!(key)
208
- raise TypeError.new("argument must be a string") unless key.is_a?(String)
267
+ raise TypeError, "argument must be a string" unless key.is_a?(String)
268
+
209
269
  key
210
270
  end
211
271
 
212
272
  def self.check_api_key!(key)
213
- raise TypeError.new("api_key must be a string") unless key.is_a?(String)
273
+ raise TypeError, "api_key must be a string" unless key.is_a?(String)
274
+
214
275
  key
215
276
  end
216
277
 
217
- private
278
+ # Normalizes header keys so that they're all lower case and each
279
+ # hyphen-delimited section starts with a single capitalized letter. For
280
+ # example, `request-id` becomes `Request-Id`. This is useful for extracting
281
+ # certain key values when the user could have set them with a variety of
282
+ # diffent naming schemes.
283
+ def self.normalize_headers(headers)
284
+ headers.each_with_object({}) do |(k, v), new_headers|
285
+ k = k.to_s.tr("_", "-") if k.is_a?(Symbol)
286
+ k = k.split("-").reject(&:empty?).map(&:capitalize).join("-")
287
+
288
+ new_headers[k] = v
289
+ end
290
+ end
291
+
292
+ # Generates a Dashboard link to inspect a request ID based off of a request
293
+ # ID value and an API key, which is used to attempt to extract whether the
294
+ # environment is livemode or testmode.
295
+ def self.request_id_dashboard_url(request_id, api_key)
296
+ env = !api_key.nil? && api_key.start_with?("sk_live") ? "live" : "test"
297
+ "https://dashboard.stripe.com/#{env}/logs/#{request_id}"
298
+ end
299
+
300
+ # Constant time string comparison to prevent timing attacks
301
+ # Code borrowed from ActiveSupport
302
+ def self.secure_compare(str_a, str_b)
303
+ return false unless str_a.bytesize == str_b.bytesize
304
+
305
+ l = str_a.unpack "C#{str_a.bytesize}"
306
+
307
+ res = 0
308
+ str_b.each_byte { |byte| res |= byte ^ l.shift }
309
+ res.zero?
310
+ end
218
311
 
219
- # We use a pretty janky version of form encoding (Rack's) that supports
220
- # more complex data structures like maps and arrays through the use of
221
- # specialized syntax. To encode an array of maps like:
222
- #
223
- # [{a: 1, b: 2}, {a: 3, b: 4}]
224
- #
225
- # We have to produce something that looks like this:
226
- #
227
- # arr[][a]=1&arr[][b]=2&arr[][a]=3&arr[][b]=4
228
312
  #
229
- # The only way for the server to recognize that this is a two item array is
230
- # that it notices the repetition of element "a", so it's key that these
231
- # repeated elements are encoded first.
313
+ # private
232
314
  #
233
- # This method is invoked for any arrays being encoded and checks that if
234
- # the array contains all non-empty maps, that each of those maps must start
235
- # with the same key so that their boundaries can be properly encoded.
236
- def self.check_array_of_maps_start_keys!(arr)
237
- expected_key = nil
238
- arr.each do |item|
239
- return if !item.is_a?(Hash)
240
- return if item.count == 0
241
-
242
- first_key = item.first[0]
243
-
244
- if expected_key
245
- if expected_key != first_key
246
- raise ArgumentError,
247
- "All maps nested in an array should start with the same key " +
248
- "(expected starting key '#{expected_key}', got '#{first_key}')"
249
- end
250
- else
251
- expected_key = first_key
252
- end
315
+
316
+ COLOR_CODES = {
317
+ black: 0, light_black: 60,
318
+ red: 1, light_red: 61,
319
+ green: 2, light_green: 62,
320
+ yellow: 3, light_yellow: 63,
321
+ blue: 4, light_blue: 64,
322
+ magenta: 5, light_magenta: 65,
323
+ cyan: 6, light_cyan: 66,
324
+ white: 7, light_white: 67,
325
+ default: 9,
326
+ }.freeze
327
+ private_constant :COLOR_CODES
328
+
329
+ # Uses an ANSI escape code to colorize text if it's going to be sent to a
330
+ # TTY.
331
+ def self.colorize(val, color, isatty)
332
+ return val unless isatty
333
+
334
+ mode = 0 # default
335
+ foreground = 30 + COLOR_CODES.fetch(color)
336
+ background = 40 + COLOR_CODES.fetch(:default)
337
+
338
+ "\033[#{mode};#{foreground};#{background}m#{val}\033[0m"
339
+ end
340
+ private_class_method :colorize
341
+
342
+ # Turns an integer log level into a printable name.
343
+ def self.level_name(level)
344
+ case level
345
+ when LEVEL_DEBUG then "debug"
346
+ when LEVEL_ERROR then "error"
347
+ when LEVEL_INFO then "info"
348
+ else level
349
+ end
350
+ end
351
+ private_class_method :level_name
352
+
353
+ def self.log_internal(message, data = {}, color:, level:, logger:, out:)
354
+ data_str = data.reject { |_k, v| v.nil? }
355
+ .map do |(k, v)|
356
+ format("%<key>s=%<value>s",
357
+ key: colorize(k, color, logger.nil? && !out.nil? && out.isatty),
358
+ value: wrap_logfmt_value(v))
359
+ end.join(" ")
360
+
361
+ if !logger.nil?
362
+ # the library's log levels are mapped to the same values as the
363
+ # standard library's logger
364
+ logger.log(level,
365
+ format("message=%<message>s %<data_str>s",
366
+ message: wrap_logfmt_value(message),
367
+ data_str: data_str))
368
+ elsif out.isatty
369
+ out.puts format("%<level>s %<message>s %<data_str>s",
370
+ level: colorize(level_name(level)[0, 4].upcase,
371
+ color, out.isatty),
372
+ message: message,
373
+ data_str: data_str)
374
+ else
375
+ out.puts format("message=%<message>s level=%<level>s %<data_str>s",
376
+ message: wrap_logfmt_value(message),
377
+ level: level_name(level),
378
+ data_str: data_str)
379
+ end
380
+ end
381
+ private_class_method :log_internal
382
+
383
+ # Wraps a value in double quotes if it looks sufficiently complex so that
384
+ # it can be read by logfmt parsers.
385
+ def self.wrap_logfmt_value(val)
386
+ # If value is any kind of number, just allow it to be formatted directly
387
+ # to a string (this will handle integers or floats).
388
+ return val if val.is_a?(Numeric)
389
+
390
+ # Hopefully val is a string, but protect in case it's not.
391
+ val = val.to_s
392
+
393
+ if %r{[^\w\-/]} =~ val
394
+ # If the string contains any special characters, escape any double
395
+ # quotes it has, remove newlines, and wrap the whole thing in quotes.
396
+ format(%("%<value>s"), value: val.gsub('"', '\"').delete("\n"))
397
+ else
398
+ # Otherwise use the basic value if it looks like a standard set of
399
+ # characters (and allow a few special characters like hyphens, and
400
+ # slashes)
401
+ val
253
402
  end
254
403
  end
404
+ private_class_method :wrap_logfmt_value
255
405
  end
256
406
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
- VERSION = '2.0.3'
4
+ VERSION = "5.55.0"
3
5
  end