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,33 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class SubscriptionSchedule < APIResource
6
+ extend Stripe::APIOperations::Create
7
+ extend Stripe::APIOperations::List
8
+ include Stripe::APIOperations::Save
9
+
10
+ OBJECT_NAME = "subscription_schedule"
11
+
12
+ custom_method :cancel, http_verb: :post
13
+ custom_method :release, http_verb: :post
14
+
15
+ def cancel(params = {}, opts = {})
16
+ request_stripe_object(
17
+ method: :post,
18
+ path: resource_url + "/cancel",
19
+ params: params,
20
+ opts: opts
21
+ )
22
+ end
23
+
24
+ def release(params = {}, opts = {})
25
+ request_stripe_object(
26
+ method: :post,
27
+ path: resource_url + "/release",
28
+ params: params,
29
+ opts: opts
30
+ )
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ class TaxId < APIResource
5
+ include Stripe::APIOperations::Delete
6
+ extend Stripe::APIOperations::List
7
+
8
+ OBJECT_NAME = "tax_id"
9
+
10
+ def resource_url
11
+ if !respond_to?(:customer) || customer.nil?
12
+ raise NotImplementedError,
13
+ "Tax IDs cannot be accessed without a customer ID."
14
+ end
15
+ "#{Customer.resource_url}/#{CGI.escape(customer)}/tax_ids" \
16
+ "/#{CGI.escape(id)}"
17
+ end
18
+
19
+ def self.retrieve(_id, _opts = {})
20
+ raise NotImplementedError,
21
+ "Tax IDs cannot be retrieved without a customer ID. Retrieve a " \
22
+ "tax ID using `Customer.retrieve_tax_id('customer_id', " \
23
+ "'tax_id_id')`"
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,12 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class TaxRate < APIResource
6
+ extend Stripe::APIOperations::Create
7
+ extend Stripe::APIOperations::List
8
+ include Stripe::APIOperations::Save
9
+
10
+ OBJECT_NAME = "tax_rate"
11
+ end
12
+ end
@@ -0,0 +1,12 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ module Terminal
6
+ class ConnectionToken < APIResource
7
+ extend Stripe::APIOperations::Create
8
+
9
+ OBJECT_NAME = "terminal.connection_token"
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,15 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ module Terminal
6
+ class Location < APIResource
7
+ extend Stripe::APIOperations::Create
8
+ include Stripe::APIOperations::Delete
9
+ extend Stripe::APIOperations::List
10
+ include Stripe::APIOperations::Save
11
+
12
+ OBJECT_NAME = "terminal.location"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,15 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ module Terminal
6
+ class Reader < APIResource
7
+ extend Stripe::APIOperations::Create
8
+ include Stripe::APIOperations::Delete
9
+ extend Stripe::APIOperations::List
10
+ include Stripe::APIOperations::Save
11
+
12
+ OBJECT_NAME = "terminal.reader"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,14 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class ThreeDSecure < APIResource
6
+ extend Stripe::APIOperations::Create
7
+
8
+ OBJECT_NAME = "three_d_secure"
9
+
10
+ def self.resource_url
11
+ "/v1/3d_secure"
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,10 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class Token < APIResource
6
+ extend Stripe::APIOperations::Create
7
+
8
+ OBJECT_NAME = "token"
9
+ end
10
+ end
@@ -0,0 +1,23 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class Topup < APIResource
6
+ extend Stripe::APIOperations::Create
7
+ extend Stripe::APIOperations::List
8
+ include Stripe::APIOperations::Save
9
+
10
+ OBJECT_NAME = "topup"
11
+
12
+ custom_method :cancel, http_verb: :post
13
+
14
+ def cancel(params = {}, opts = {})
15
+ request_stripe_object(
16
+ method: :post,
17
+ path: resource_url + "/cancel",
18
+ params: params,
19
+ opts: opts
20
+ )
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,27 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class Transfer < APIResource
6
+ extend Stripe::APIOperations::Create
7
+ extend Stripe::APIOperations::List
8
+ include Stripe::APIOperations::Save
9
+ extend Stripe::APIOperations::NestedResource
10
+
11
+ OBJECT_NAME = "transfer"
12
+
13
+ custom_method :cancel, http_verb: :post
14
+
15
+ nested_resource_class_methods :reversal,
16
+ operations: %i[create retrieve update list]
17
+
18
+ def cancel(params = {}, opts = {})
19
+ request_stripe_object(
20
+ method: :post,
21
+ path: resource_url + "/cancel",
22
+ params: params,
23
+ opts: opts
24
+ )
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ class UsageRecord < APIResource
5
+ OBJECT_NAME = "usage_record"
6
+ end
7
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Stripe
4
+ class UsageRecordSummary < StripeObject
5
+ OBJECT_NAME = "usage_record_summary"
6
+ end
7
+ end
@@ -0,0 +1,13 @@
1
+ # File generated from our OpenAPI spec
2
+ # frozen_string_literal: true
3
+
4
+ module Stripe
5
+ class WebhookEndpoint < APIResource
6
+ extend Stripe::APIOperations::Create
7
+ include Stripe::APIOperations::Delete
8
+ extend Stripe::APIOperations::List
9
+ include Stripe::APIOperations::Save
10
+
11
+ OBJECT_NAME = "webhook_endpoint"
12
+ end
13
+ end
@@ -1,18 +1,24 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Stripe
2
4
  class SingletonAPIResource < APIResource
3
- def self.url
5
+ def self.resource_url
4
6
  if self == SingletonAPIResource
5
- raise NotImplementedError.new('SingletonAPIResource is an abstract class. You should perform actions on its subclasses (Account, etc.)')
7
+ raise NotImplementedError,
8
+ "SingletonAPIResource is an abstract class. You should " \
9
+ "perform actions on its subclasses (Balance, etc.)"
6
10
  end
7
- "/v1/#{CGI.escape(class_name.downcase)}"
11
+ # Namespaces are separated in object names with periods (.) and in URLs
12
+ # with forward slashes (/), so replace the former with the latter.
13
+ "/v1/#{self::OBJECT_NAME.downcase.tr('.', '/')}"
8
14
  end
9
15
 
10
- def url
11
- self.class.url
16
+ def resource_url
17
+ self.class.resource_url
12
18
  end
13
19
 
14
- def self.retrieve(opts={})
15
- instance = self.new(nil, Util.normalize_opts(opts))
20
+ def self.retrieve(opts = {})
21
+ instance = new(nil, Util.normalize_opts(opts))
16
22
  instance.refresh
17
23
  instance
18
24
  end
@@ -0,0 +1,989 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "stripe/instrumentation"
4
+
5
+ module Stripe
6
+ # StripeClient executes requests against the Stripe API and allows a user to
7
+ # recover both a resource a call returns as well as a response object that
8
+ # contains information on the HTTP call.
9
+ class StripeClient
10
+ # A set of all known thread contexts across all threads and a mutex to
11
+ # synchronize global access to them.
12
+ @thread_contexts_with_connection_managers = Set.new
13
+ @thread_contexts_with_connection_managers_mutex = Mutex.new
14
+ @last_connection_manager_gc = Util.monotonic_time
15
+
16
+ # Initializes a new StripeClient
17
+ def initialize(config_arg = {})
18
+ @system_profiler = SystemProfiler.new
19
+ @last_request_metrics = nil
20
+
21
+ @config = case config_arg
22
+ when Hash
23
+ Stripe.config.reverse_duplicate_merge(config_arg)
24
+ when Stripe::ConnectionManager
25
+ # Supports accepting a connection manager object for backwards
26
+ # compatibility only, and that use is DEPRECATED.
27
+ Stripe.config.dup
28
+ when Stripe::StripeConfiguration
29
+ config_arg
30
+ when String
31
+ Stripe.config.reverse_duplicate_merge(
32
+ { api_key: config_arg }
33
+ )
34
+ else
35
+ raise ArgumentError, "Can't handle argument: #{config_arg}"
36
+ end
37
+ end
38
+
39
+ attr_reader :config
40
+ attr_reader :options
41
+
42
+ # Gets a currently active `StripeClient`. Set for the current thread when
43
+ # `StripeClient#request` is being run so that API operations being executed
44
+ # inside of that block can find the currently active client. It's reset to
45
+ # the original value (hopefully `nil`) after the block ends.
46
+ #
47
+ # For internal use only. Does not provide a stable API and may be broken
48
+ # with future non-major changes.
49
+ def self.active_client
50
+ current_thread_context.active_client || default_client
51
+ end
52
+
53
+ # Finishes any active connections by closing their TCP connection and
54
+ # clears them from internal tracking in all connection managers across all
55
+ # threads.
56
+ #
57
+ # If passed a `config` object, only clear connection managers for that
58
+ # particular configuration.
59
+ #
60
+ # For internal use only. Does not provide a stable API and may be broken
61
+ # with future non-major changes.
62
+ def self.clear_all_connection_managers(config: nil)
63
+ # Just a quick path for when configuration is being set for the first
64
+ # time before any connections have been opened. There is technically some
65
+ # potential for thread raciness here, but not in a practical sense.
66
+ return if @thread_contexts_with_connection_managers.empty?
67
+
68
+ @thread_contexts_with_connection_managers_mutex.synchronize do
69
+ pruned_contexts = Set.new
70
+
71
+ @thread_contexts_with_connection_managers.each do |thread_context|
72
+ # Note that the thread context itself is not destroyed, but we clear
73
+ # its connection manager and remove our reference to it. If it ever
74
+ # makes a new request we'll give it a new connection manager and
75
+ # it'll go back into `@thread_contexts_with_connection_managers`.
76
+ thread_context.default_connection_managers.reject! do |cm_config, cm|
77
+ if config.nil? || config.key == cm_config
78
+ cm.clear
79
+ true
80
+ end
81
+ end
82
+
83
+ if thread_context.default_connection_managers.empty?
84
+ pruned_contexts << thread_context
85
+ end
86
+ end
87
+
88
+ @thread_contexts_with_connection_managers.subtract(pruned_contexts)
89
+ end
90
+ end
91
+
92
+ # A default client for the current thread.
93
+ def self.default_client
94
+ current_thread_context.default_client ||= StripeClient.new(Stripe.config)
95
+ end
96
+
97
+ # A default connection manager for the current thread scoped to the
98
+ # configuration object that may be provided.
99
+ def self.default_connection_manager(config = Stripe.config)
100
+ current_thread_context.default_connection_managers[config.key] ||= begin
101
+ connection_manager = ConnectionManager.new(config)
102
+
103
+ @thread_contexts_with_connection_managers_mutex.synchronize do
104
+ maybe_gc_connection_managers
105
+ @thread_contexts_with_connection_managers << current_thread_context
106
+ end
107
+
108
+ connection_manager
109
+ end
110
+ end
111
+
112
+ # Checks if an error is a problem that we should retry on. This includes
113
+ # both socket errors that may represent an intermittent problem and some
114
+ # special HTTP statuses.
115
+ def self.should_retry?(error,
116
+ method:, num_retries:, config: Stripe.config)
117
+ return false if num_retries >= config.max_network_retries
118
+
119
+ case error
120
+ when Net::OpenTimeout, Net::ReadTimeout
121
+ # Retry on timeout-related problems (either on open or read).
122
+ true
123
+ when EOFError, Errno::ECONNREFUSED, Errno::ECONNRESET,
124
+ Errno::EHOSTUNREACH, Errno::ETIMEDOUT, SocketError
125
+ # Destination refused the connection, the connection was reset, or a
126
+ # variety of other connection failures. This could occur from a single
127
+ # saturated server, so retry in case it's intermittent.
128
+ true
129
+ when Stripe::StripeError
130
+ # The API may ask us not to retry (e.g. if doing so would be a no-op),
131
+ # or advise us to retry (e.g. in cases of lock timeouts). Defer to
132
+ # those instructions if given.
133
+ return false if error.http_headers["stripe-should-retry"] == "false"
134
+ return true if error.http_headers["stripe-should-retry"] == "true"
135
+
136
+ # 409 Conflict
137
+ return true if error.http_status == 409
138
+
139
+ # 429 Too Many Requests
140
+ #
141
+ # There are a few different problems that can lead to a 429. The most
142
+ # common is rate limiting, on which we *don't* want to retry because
143
+ # that'd likely contribute to more contention problems. However, some
144
+ # 429s are lock timeouts, which is when a request conflicted with
145
+ # another request or an internal process on some particular object.
146
+ # These 429s are safe to retry.
147
+ return true if error.http_status == 429 && error.code == "lock_timeout"
148
+
149
+ # 500 Internal Server Error
150
+ #
151
+ # We only bother retrying these for non-POST requests. POSTs end up
152
+ # being cached by the idempotency layer so there's no purpose in
153
+ # retrying them.
154
+ return true if error.http_status == 500 && method != :post
155
+
156
+ # 503 Service Unavailable
157
+ error.http_status == 503
158
+ else
159
+ false
160
+ end
161
+ end
162
+
163
+ def self.sleep_time(num_retries, config: Stripe.config)
164
+ # Apply exponential backoff with initial_network_retry_delay on the
165
+ # number of num_retries so far as inputs. Do not allow the number to
166
+ # exceed max_network_retry_delay.
167
+ sleep_seconds = [
168
+ config.initial_network_retry_delay * (2**(num_retries - 1)),
169
+ config.max_network_retry_delay,
170
+ ].min
171
+
172
+ # Apply some jitter by randomizing the value in the range of
173
+ # (sleep_seconds / 2) to (sleep_seconds).
174
+ sleep_seconds *= (0.5 * (1 + rand))
175
+
176
+ # But never sleep less than the base sleep seconds.
177
+ [config.initial_network_retry_delay, sleep_seconds].max
178
+ end
179
+
180
+ # Gets the connection manager in use for the current `StripeClient`.
181
+ #
182
+ # This method is DEPRECATED and for backwards compatibility only.
183
+ def connection_manager
184
+ self.class.default_connection_manager
185
+ end
186
+ extend Gem::Deprecate
187
+ deprecate :connection_manager, :none, 2020, 9
188
+
189
+ # Executes the API call within the given block. Usage looks like:
190
+ #
191
+ # client = StripeClient.new
192
+ # charge, resp = client.request { Charge.create }
193
+ #
194
+ def request
195
+ old_stripe_client = self.class.current_thread_context.active_client
196
+ self.class.current_thread_context.active_client = self
197
+
198
+ if self.class.current_thread_context.last_responses&.key?(object_id)
199
+ raise "calls to StripeClient#request cannot be nested within a thread"
200
+ end
201
+
202
+ self.class.current_thread_context.last_responses ||= {}
203
+ self.class.current_thread_context.last_responses[object_id] = nil
204
+
205
+ begin
206
+ res = yield
207
+ [res, self.class.current_thread_context.last_responses[object_id]]
208
+ ensure
209
+ self.class.current_thread_context.active_client = old_stripe_client
210
+ self.class.current_thread_context.last_responses.delete(object_id)
211
+ end
212
+ end
213
+
214
+ def execute_request(method, path,
215
+ api_base: nil, api_key: nil, headers: {}, params: {})
216
+ raise ArgumentError, "method should be a symbol" \
217
+ unless method.is_a?(Symbol)
218
+ raise ArgumentError, "path should be a string" \
219
+ unless path.is_a?(String)
220
+
221
+ api_base ||= config.api_base
222
+ api_key ||= config.api_key
223
+ params = Util.objects_to_ids(params)
224
+
225
+ check_api_key!(api_key)
226
+
227
+ body_params = nil
228
+ query_params = nil
229
+ case method
230
+ when :get, :head, :delete
231
+ query_params = params
232
+ else
233
+ body_params = params
234
+ end
235
+
236
+ query_params, path = merge_query_params(query_params, path)
237
+
238
+ headers = request_headers(api_key, method)
239
+ .update(Util.normalize_headers(headers))
240
+ url = api_url(path, api_base)
241
+
242
+ # Merge given query parameters with any already encoded in the path.
243
+ query = query_params ? Util.encode_parameters(query_params) : nil
244
+
245
+ # Encoding body parameters is a little more complex because we may have
246
+ # to send a multipart-encoded body. `body_log` is produced separately as
247
+ # a log-friendly variant of the encoded form. File objects are displayed
248
+ # as such instead of as their file contents.
249
+ body, body_log =
250
+ body_params ? encode_body(body_params, headers) : [nil, nil]
251
+
252
+ # stores information on the request we're about to make so that we don't
253
+ # have to pass as many parameters around for logging.
254
+ context = RequestLogContext.new
255
+ context.account = headers["Stripe-Account"]
256
+ context.api_key = api_key
257
+ context.api_version = headers["Stripe-Version"]
258
+ context.body = body_log
259
+ context.idempotency_key = headers["Idempotency-Key"]
260
+ context.method = method
261
+ context.path = path
262
+ context.query = query
263
+
264
+ http_resp = execute_request_with_rescues(method, api_base, context) do
265
+ self.class
266
+ .default_connection_manager(config)
267
+ .execute_request(method, url,
268
+ body: body,
269
+ headers: headers,
270
+ query: query)
271
+ end
272
+
273
+ begin
274
+ resp = StripeResponse.from_net_http(http_resp)
275
+ rescue JSON::ParserError
276
+ raise general_api_error(http_resp.code.to_i, http_resp.body)
277
+ end
278
+
279
+ # If being called from `StripeClient#request`, put the last response in
280
+ # thread-local memory so that it can be returned to the user. Don't store
281
+ # anything otherwise so that we don't leak memory.
282
+ store_last_response(object_id, resp)
283
+
284
+ [resp, api_key]
285
+ end
286
+
287
+ def store_last_response(object_id, resp)
288
+ return unless last_response_has_key?(object_id)
289
+
290
+ self.class.current_thread_context.last_responses[object_id] = resp
291
+ end
292
+
293
+ def last_response_has_key?(object_id)
294
+ self.class.current_thread_context.last_responses&.key?(object_id)
295
+ end
296
+
297
+ #
298
+ # private
299
+ #
300
+
301
+ # Time (in seconds) that a connection manager has not been used before it's
302
+ # eligible for garbage collection.
303
+ CONNECTION_MANAGER_GC_LAST_USED_EXPIRY = 120
304
+
305
+ # How often to check (in seconds) for connection managers that haven't been
306
+ # used in a long time and which should be garbage collected.
307
+ CONNECTION_MANAGER_GC_PERIOD = 60
308
+
309
+ ERROR_MESSAGE_CONNECTION =
310
+ "Unexpected error communicating when trying to connect to " \
311
+ "Stripe (%s). You may be seeing this message because your DNS is not " \
312
+ "working or you don't have an internet connection. To check, try " \
313
+ "running `host stripe.com` from the command line."
314
+ ERROR_MESSAGE_SSL =
315
+ "Could not establish a secure connection to Stripe (%s), you " \
316
+ "may need to upgrade your OpenSSL version. To check, try running " \
317
+ "`openssl s_client -connect api.stripe.com:443` from the command " \
318
+ "line."
319
+
320
+ # Common error suffix sared by both connect and read timeout messages.
321
+ ERROR_MESSAGE_TIMEOUT_SUFFIX =
322
+ "Please check your internet connection and try again. " \
323
+ "If this problem persists, you should check Stripe's service " \
324
+ "status at https://status.stripe.com, or let us know at " \
325
+ "support@stripe.com."
326
+
327
+ ERROR_MESSAGE_TIMEOUT_CONNECT = (
328
+ "Timed out connecting to Stripe (%s). " +
329
+ ERROR_MESSAGE_TIMEOUT_SUFFIX
330
+ ).freeze
331
+
332
+ ERROR_MESSAGE_TIMEOUT_READ = (
333
+ "Timed out communicating with Stripe (%s). " +
334
+ ERROR_MESSAGE_TIMEOUT_SUFFIX
335
+ ).freeze
336
+
337
+ # Maps types of exceptions that we're likely to see during a network
338
+ # request to more user-friendly messages that we put in front of people.
339
+ # The original error message is also appended onto the final exception for
340
+ # full transparency.
341
+ NETWORK_ERROR_MESSAGES_MAP = {
342
+ EOFError => ERROR_MESSAGE_CONNECTION,
343
+ Errno::ECONNREFUSED => ERROR_MESSAGE_CONNECTION,
344
+ Errno::ECONNRESET => ERROR_MESSAGE_CONNECTION,
345
+ Errno::EHOSTUNREACH => ERROR_MESSAGE_CONNECTION,
346
+ Errno::ETIMEDOUT => ERROR_MESSAGE_TIMEOUT_CONNECT,
347
+ SocketError => ERROR_MESSAGE_CONNECTION,
348
+
349
+ Net::OpenTimeout => ERROR_MESSAGE_TIMEOUT_CONNECT,
350
+ Net::ReadTimeout => ERROR_MESSAGE_TIMEOUT_READ,
351
+
352
+ OpenSSL::SSL::SSLError => ERROR_MESSAGE_SSL,
353
+ }.freeze
354
+ private_constant :NETWORK_ERROR_MESSAGES_MAP
355
+
356
+ # A record representing any data that `StripeClient` puts into
357
+ # `Thread.current`. Making it a class likes this gives us a little extra
358
+ # type safety and lets us document what each field does.
359
+ #
360
+ # For internal use only. Does not provide a stable API and may be broken
361
+ # with future non-major changes.
362
+ class ThreadContext
363
+ # A `StripeClient` that's been flagged as currently active within a
364
+ # thread by `StripeClient#request`. A client stays active until the
365
+ # completion of the request block.
366
+ attr_accessor :active_client
367
+
368
+ # A default `StripeClient` object for the thread. Used in all cases where
369
+ # the user hasn't specified their own.
370
+ attr_accessor :default_client
371
+
372
+ # A temporary map of object IDs to responses from last executed API
373
+ # calls. Used to return a responses from calls to `StripeClient#request`.
374
+ #
375
+ # Stored in the thread data to make the use of a single `StripeClient`
376
+ # object safe across multiple threads. Stored as a map so that multiple
377
+ # `StripeClient` objects can run concurrently on the same thread.
378
+ #
379
+ # Responses are only left in as long as they're needed, which means
380
+ # they're removed as soon as a call leaves `StripeClient#request`, and
381
+ # because that's wrapped in an `ensure` block, they should never leave
382
+ # garbage in `Thread.current`.
383
+ attr_accessor :last_responses
384
+
385
+ # A map of connection mangers for the thread. Normally shared between
386
+ # all `StripeClient` objects on a particular thread, and created so as to
387
+ # minimize the number of open connections that an application needs.
388
+ def default_connection_managers
389
+ @default_connection_managers ||= {}
390
+ end
391
+
392
+ def reset_connection_managers
393
+ @default_connection_managers = {}
394
+ end
395
+ end
396
+
397
+ # Access data stored for `StripeClient` within the thread's current
398
+ # context. Returns `ThreadContext`.
399
+ #
400
+ # For internal use only. Does not provide a stable API and may be broken
401
+ # with future non-major changes.
402
+ def self.current_thread_context
403
+ Thread.current[:stripe_client__internal_use_only] ||= ThreadContext.new
404
+ end
405
+
406
+ # Garbage collects connection managers that haven't been used in some time,
407
+ # with the idea being that we want to remove old connection managers that
408
+ # belong to dead threads and the like.
409
+ #
410
+ # Prefixed with `maybe_` because garbage collection will only run
411
+ # periodically so that we're not constantly engaged in busy work. If
412
+ # connection managers live a little passed their useful age it's not
413
+ # harmful, so it's not necessary to get them right away.
414
+ #
415
+ # For testability, returns `nil` if it didn't run and the number of
416
+ # connection managers that were garbage collected otherwise.
417
+ #
418
+ # IMPORTANT: This method is not thread-safe and expects to be called inside
419
+ # a lock on `@thread_contexts_with_connection_managers_mutex`.
420
+ #
421
+ # For internal use only. Does not provide a stable API and may be broken
422
+ # with future non-major changes.
423
+ def self.maybe_gc_connection_managers
424
+ next_gc_time = @last_connection_manager_gc + CONNECTION_MANAGER_GC_PERIOD
425
+ return nil if next_gc_time > Util.monotonic_time
426
+
427
+ last_used_threshold =
428
+ Util.monotonic_time - CONNECTION_MANAGER_GC_LAST_USED_EXPIRY
429
+
430
+ pruned_contexts = []
431
+ @thread_contexts_with_connection_managers.each do |thread_context|
432
+ thread_context
433
+ .default_connection_managers
434
+ .each do |config_key, connection_manager|
435
+ next if connection_manager.last_used > last_used_threshold
436
+
437
+ connection_manager.clear
438
+ thread_context.default_connection_managers.delete(config_key)
439
+ end
440
+ end
441
+
442
+ @thread_contexts_with_connection_managers.each do |thread_context|
443
+ next unless thread_context.default_connection_managers.empty?
444
+
445
+ pruned_contexts << thread_context
446
+ end
447
+
448
+ @thread_contexts_with_connection_managers -= pruned_contexts
449
+ @last_connection_manager_gc = Util.monotonic_time
450
+
451
+ pruned_contexts.count
452
+ end
453
+
454
+ private def api_url(url = "", api_base = nil)
455
+ (api_base || config.api_base) + url
456
+ end
457
+
458
+ private def check_api_key!(api_key)
459
+ unless api_key
460
+ raise AuthenticationError, "No API key provided. " \
461
+ 'Set your API key using "Stripe.api_key = <API-KEY>". ' \
462
+ "You can generate API keys from the Stripe web interface. " \
463
+ "See https://stripe.com/api for details, or email " \
464
+ "support@stripe.com if you have any questions."
465
+ end
466
+
467
+ return unless api_key =~ /\s/
468
+
469
+ raise AuthenticationError, "Your API key is invalid, as it contains " \
470
+ "whitespace. (HINT: You can double-check your API key from the " \
471
+ "Stripe web interface. See https://stripe.com/api for details, or " \
472
+ "email support@stripe.com if you have any questions.)"
473
+ end
474
+
475
+ # Encodes a set of body parameters using multipart if `Content-Type` is set
476
+ # for that, or standard form-encoding otherwise. Returns the encoded body
477
+ # and a version of the encoded body that's safe to be logged.
478
+ private def encode_body(body_params, headers)
479
+ body = nil
480
+ flattened_params = Util.flatten_params(body_params)
481
+
482
+ if headers["Content-Type"] == MultipartEncoder::MULTIPART_FORM_DATA
483
+ body, content_type = MultipartEncoder.encode(flattened_params)
484
+
485
+ # Set a new content type that also includes the multipart boundary.
486
+ # See `MultipartEncoder` for details.
487
+ headers["Content-Type"] = content_type
488
+
489
+ # `#to_s` any complex objects like files and the like to build output
490
+ # that's more condusive to logging.
491
+ flattened_params =
492
+ flattened_params.map { |k, v| [k, v.is_a?(String) ? v : v.to_s] }.to_h
493
+ else
494
+ body = Util.encode_parameters(body_params)
495
+ end
496
+
497
+ # We don't use `Util.encode_parameters` partly as an optimization (to not
498
+ # redo work we've already done), and partly because the encoded forms of
499
+ # certain characters introduce a lot of visual noise and it's nice to
500
+ # have a clearer format for logs.
501
+ body_log = flattened_params.map { |k, v| "#{k}=#{v}" }.join("&")
502
+
503
+ [body, body_log]
504
+ end
505
+
506
+ private def execute_request_with_rescues(method, api_base, context)
507
+ num_retries = 0
508
+
509
+ begin
510
+ request_start = nil
511
+ user_data = nil
512
+
513
+ log_request(context, num_retries)
514
+ user_data = notify_request_begin(context)
515
+
516
+ request_start = Util.monotonic_time
517
+ resp = yield
518
+ request_duration = Util.monotonic_time - request_start
519
+
520
+ http_status = resp.code.to_i
521
+ context = context.dup_from_response_headers(resp)
522
+
523
+ handle_error_response(resp, context) if http_status >= 400
524
+
525
+ log_response(context, request_start, http_status, resp.body)
526
+ notify_request_end(context, request_duration, http_status,
527
+ num_retries, user_data)
528
+
529
+ if config.enable_telemetry? && context.request_id
530
+ request_duration_ms = (request_duration * 1000).to_i
531
+ @last_request_metrics =
532
+ StripeRequestMetrics.new(context.request_id, request_duration_ms)
533
+ end
534
+
535
+ # We rescue all exceptions from a request so that we have an easy spot to
536
+ # implement our retry logic across the board. We'll re-raise if it's a
537
+ # type of exception that we didn't expect to handle.
538
+ rescue StandardError => e
539
+ # If we modify context we copy it into a new variable so as not to
540
+ # taint the original on a retry.
541
+ error_context = context
542
+ http_status = nil
543
+ request_duration = Util.monotonic_time - request_start if request_start
544
+
545
+ if e.is_a?(Stripe::StripeError)
546
+ error_context = context.dup_from_response_headers(e.http_headers)
547
+ http_status = resp.code.to_i
548
+ log_response(error_context, request_start,
549
+ e.http_status, e.http_body)
550
+ else
551
+ log_response_error(error_context, request_start, e)
552
+ end
553
+ notify_request_end(context, request_duration, http_status, num_retries,
554
+ user_data)
555
+
556
+ if self.class.should_retry?(e,
557
+ method: method,
558
+ num_retries: num_retries,
559
+ config: config)
560
+ num_retries += 1
561
+ sleep self.class.sleep_time(num_retries, config: config)
562
+ retry
563
+ end
564
+
565
+ case e
566
+ when Stripe::StripeError
567
+ raise
568
+ when *NETWORK_ERROR_MESSAGES_MAP.keys
569
+ handle_network_error(e, error_context, num_retries, api_base)
570
+
571
+ # Only handle errors when we know we can do so, and re-raise otherwise.
572
+ # This should be pretty infrequent.
573
+ else
574
+ raise
575
+ end
576
+ end
577
+
578
+ resp
579
+ end
580
+
581
+ private def notify_request_begin(context)
582
+ return unless Instrumentation.any_subscribers?(:request_begin)
583
+
584
+ event = Instrumentation::RequestBeginEvent.new(
585
+ method: context.method,
586
+ path: context.path,
587
+ user_data: {}
588
+ )
589
+ Stripe::Instrumentation.notify(:request_begin, event)
590
+
591
+ # This field may be set in the `request_begin` callback. If so, we'll
592
+ # forward it onto `request_end`.
593
+ event.user_data
594
+ end
595
+
596
+ private def notify_request_end(context, duration, http_status, num_retries,
597
+ user_data)
598
+ return if !Instrumentation.any_subscribers?(:request_end) &&
599
+ !Instrumentation.any_subscribers?(:request)
600
+
601
+ event = Instrumentation::RequestEndEvent.new(
602
+ duration: duration,
603
+ http_status: http_status,
604
+ method: context.method,
605
+ num_retries: num_retries,
606
+ path: context.path,
607
+ user_data: user_data || {}
608
+ )
609
+ Stripe::Instrumentation.notify(:request_end, event)
610
+
611
+ # The name before `request_begin` was also added. Provided for backwards
612
+ # compatibility.
613
+ Stripe::Instrumentation.notify(:request, event)
614
+ end
615
+
616
+ private def general_api_error(status, body)
617
+ APIError.new("Invalid response object from API: #{body.inspect} " \
618
+ "(HTTP response code was #{status})",
619
+ http_status: status, http_body: body)
620
+ end
621
+
622
+ # Formats a plugin "app info" hash into a string that we can tack onto the
623
+ # end of a User-Agent string where it'll be fairly prominent in places like
624
+ # the Dashboard. Note that this formatting has been implemented to match
625
+ # other libraries, and shouldn't be changed without universal consensus.
626
+ private def format_app_info(info)
627
+ str = info[:name]
628
+ str = "#{str}/#{info[:version]}" unless info[:version].nil?
629
+ str = "#{str} (#{info[:url]})" unless info[:url].nil?
630
+ str
631
+ end
632
+
633
+ private def handle_error_response(http_resp, context)
634
+ begin
635
+ resp = StripeResponse.from_net_http(http_resp)
636
+ error_data = resp.data[:error]
637
+
638
+ raise StripeError, "Indeterminate error" unless error_data
639
+ rescue JSON::ParserError, StripeError
640
+ raise general_api_error(http_resp.code.to_i, http_resp.body)
641
+ end
642
+
643
+ error = if error_data.is_a?(String)
644
+ specific_oauth_error(resp, error_data, context)
645
+ else
646
+ specific_api_error(resp, error_data, context)
647
+ end
648
+
649
+ error.response = resp
650
+ raise(error)
651
+ end
652
+
653
+ # Works around an edge case where we end up with both query parameters from
654
+ # parameteers and query parameters that were appended onto the end of the
655
+ # given path.
656
+ #
657
+ # Decode any parameters that were added onto the end of a path and add them
658
+ # to a unified query parameter hash so that all parameters end up in one
659
+ # place and all of them are correctly included in the final request.
660
+ private def merge_query_params(query_params, path)
661
+ u = URI.parse(path)
662
+
663
+ # Return original results if there was nothing to be found.
664
+ return query_params, path if u.query.nil?
665
+
666
+ query_params ||= {}
667
+ query_params = Hash[URI.decode_www_form(u.query)].merge(query_params)
668
+
669
+ # Reset the path minus any query parameters that were specified.
670
+ path = u.path
671
+
672
+ [query_params, path]
673
+ end
674
+
675
+ private def specific_api_error(resp, error_data, context)
676
+ Util.log_error("Stripe API error",
677
+ status: resp.http_status,
678
+ error_code: error_data[:code],
679
+ error_message: error_data[:message],
680
+ error_param: error_data[:param],
681
+ error_type: error_data[:type],
682
+ idempotency_key: context.idempotency_key,
683
+ request_id: context.request_id,
684
+ config: config)
685
+
686
+ # The standard set of arguments that can be used to initialize most of
687
+ # the exceptions.
688
+ opts = {
689
+ http_body: resp.http_body,
690
+ http_headers: resp.http_headers,
691
+ http_status: resp.http_status,
692
+ json_body: resp.data,
693
+ code: error_data[:code],
694
+ }
695
+
696
+ case resp.http_status
697
+ when 400, 404
698
+ case error_data[:type]
699
+ when "idempotency_error"
700
+ IdempotencyError.new(error_data[:message], **opts)
701
+ else
702
+ InvalidRequestError.new(
703
+ error_data[:message], error_data[:param],
704
+ **opts
705
+ )
706
+ end
707
+ when 401
708
+ AuthenticationError.new(error_data[:message], **opts)
709
+ when 402
710
+ CardError.new(
711
+ error_data[:message], error_data[:param],
712
+ **opts
713
+ )
714
+ when 403
715
+ PermissionError.new(error_data[:message], **opts)
716
+ when 429
717
+ RateLimitError.new(error_data[:message], **opts)
718
+ else
719
+ APIError.new(error_data[:message], **opts)
720
+ end
721
+ end
722
+
723
+ # Attempts to look at a response's error code and return an OAuth error if
724
+ # one matches. Will return `nil` if the code isn't recognized.
725
+ private def specific_oauth_error(resp, error_code, context)
726
+ description = resp.data[:error_description] || error_code
727
+
728
+ Util.log_error("Stripe OAuth error",
729
+ status: resp.http_status,
730
+ error_code: error_code,
731
+ error_description: description,
732
+ idempotency_key: context.idempotency_key,
733
+ request_id: context.request_id,
734
+ config: config)
735
+
736
+ args = {
737
+ http_status: resp.http_status, http_body: resp.http_body,
738
+ json_body: resp.data, http_headers: resp.http_headers,
739
+ }
740
+
741
+ case error_code
742
+ when "invalid_client"
743
+ OAuth::InvalidClientError.new(error_code, description, **args)
744
+ when "invalid_grant"
745
+ OAuth::InvalidGrantError.new(error_code, description, **args)
746
+ when "invalid_request"
747
+ OAuth::InvalidRequestError.new(error_code, description, **args)
748
+ when "invalid_scope"
749
+ OAuth::InvalidScopeError.new(error_code, description, **args)
750
+ when "unsupported_grant_type"
751
+ OAuth::UnsupportedGrantTypeError.new(error_code, description, **args)
752
+ when "unsupported_response_type"
753
+ OAuth::UnsupportedResponseTypeError.new(error_code, description, **args)
754
+ else
755
+ # We'd prefer that all errors are typed, but we create a generic
756
+ # OAuthError in case we run into a code that we don't recognize.
757
+ OAuth::OAuthError.new(error_code, description, **args)
758
+ end
759
+ end
760
+
761
+ private def handle_network_error(error, context, num_retries,
762
+ api_base = nil)
763
+ Util.log_error("Stripe network error",
764
+ error_message: error.message,
765
+ idempotency_key: context.idempotency_key,
766
+ request_id: context.request_id,
767
+ config: config)
768
+
769
+ errors, message = NETWORK_ERROR_MESSAGES_MAP.detect do |(e, _)|
770
+ error.is_a?(e)
771
+ end
772
+
773
+ if errors.nil?
774
+ message = "Unexpected error #{error.class.name} communicating " \
775
+ "with Stripe. Please let us know at support@stripe.com."
776
+ end
777
+
778
+ api_base ||= config.api_base
779
+ message = message % api_base
780
+
781
+ message += " Request was retried #{num_retries} times." if num_retries > 0
782
+
783
+ raise APIConnectionError,
784
+ message + "\n\n(Network error: #{error.message})"
785
+ end
786
+
787
+ private def request_headers(api_key, method)
788
+ user_agent = "Stripe/v1 RubyBindings/#{Stripe::VERSION}"
789
+ unless Stripe.app_info.nil?
790
+ user_agent += " " + format_app_info(Stripe.app_info)
791
+ end
792
+
793
+ headers = {
794
+ "User-Agent" => user_agent,
795
+ "Authorization" => "Bearer #{api_key}",
796
+ "Content-Type" => "application/x-www-form-urlencoded",
797
+ }
798
+
799
+ if config.enable_telemetry? && !@last_request_metrics.nil?
800
+ headers["X-Stripe-Client-Telemetry"] = JSON.generate(
801
+ last_request_metrics: @last_request_metrics.payload
802
+ )
803
+ end
804
+
805
+ # It is only safe to retry network failures on post and delete
806
+ # requests if we add an Idempotency-Key header
807
+ if %i[post delete].include?(method) && config.max_network_retries > 0
808
+ headers["Idempotency-Key"] ||= SecureRandom.uuid
809
+ end
810
+
811
+ headers["Stripe-Version"] = config.api_version if config.api_version
812
+ headers["Stripe-Account"] = config.stripe_account if config.stripe_account
813
+
814
+ user_agent = @system_profiler.user_agent
815
+ begin
816
+ headers.update(
817
+ "X-Stripe-Client-User-Agent" => JSON.generate(user_agent)
818
+ )
819
+ rescue StandardError => e
820
+ headers.update(
821
+ "X-Stripe-Client-Raw-User-Agent" => user_agent.inspect,
822
+ :error => "#{e} (#{e.class})"
823
+ )
824
+ end
825
+
826
+ headers
827
+ end
828
+
829
+ private def log_request(context, num_retries)
830
+ Util.log_info("Request to Stripe API",
831
+ account: context.account,
832
+ api_version: context.api_version,
833
+ idempotency_key: context.idempotency_key,
834
+ method: context.method,
835
+ num_retries: num_retries,
836
+ path: context.path,
837
+ config: config)
838
+ Util.log_debug("Request details",
839
+ body: context.body,
840
+ idempotency_key: context.idempotency_key,
841
+ query: context.query,
842
+ config: config)
843
+ end
844
+
845
+ private def log_response(context, request_start, status, body)
846
+ Util.log_info("Response from Stripe API",
847
+ account: context.account,
848
+ api_version: context.api_version,
849
+ elapsed: Util.monotonic_time - request_start,
850
+ idempotency_key: context.idempotency_key,
851
+ method: context.method,
852
+ path: context.path,
853
+ request_id: context.request_id,
854
+ status: status,
855
+ config: config)
856
+ Util.log_debug("Response details",
857
+ body: body,
858
+ idempotency_key: context.idempotency_key,
859
+ request_id: context.request_id,
860
+ config: config)
861
+
862
+ return unless context.request_id
863
+
864
+ Util.log_debug("Dashboard link for request",
865
+ idempotency_key: context.idempotency_key,
866
+ request_id: context.request_id,
867
+ url: Util.request_id_dashboard_url(context.request_id,
868
+ context.api_key),
869
+ config: config)
870
+ end
871
+
872
+ private def log_response_error(context, request_start, error)
873
+ elapsed = request_start ? Util.monotonic_time - request_start : nil
874
+ Util.log_error("Request error",
875
+ elapsed: elapsed,
876
+ error_message: error.message,
877
+ idempotency_key: context.idempotency_key,
878
+ method: context.method,
879
+ path: context.path,
880
+ config: config)
881
+ end
882
+
883
+ # RequestLogContext stores information about a request that's begin made so
884
+ # that we can log certain information. It's useful because it means that we
885
+ # don't have to pass around as many parameters.
886
+ class RequestLogContext
887
+ attr_accessor :body
888
+ attr_accessor :account
889
+ attr_accessor :api_key
890
+ attr_accessor :api_version
891
+ attr_accessor :idempotency_key
892
+ attr_accessor :method
893
+ attr_accessor :path
894
+ attr_accessor :query
895
+ attr_accessor :request_id
896
+
897
+ # The idea with this method is that we might want to update some of
898
+ # context information because a response that we've received from the API
899
+ # contains information that's more authoritative than what we started
900
+ # with for a request. For example, we should trust whatever came back in
901
+ # a `Stripe-Version` header beyond what configuration information that we
902
+ # might have had available.
903
+ def dup_from_response_headers(headers)
904
+ context = dup
905
+ context.account = headers["Stripe-Account"]
906
+ context.api_version = headers["Stripe-Version"]
907
+ context.idempotency_key = headers["Idempotency-Key"]
908
+ context.request_id = headers["Request-Id"]
909
+ context
910
+ end
911
+ end
912
+
913
+ # SystemProfiler extracts information about the system that we're running
914
+ # in so that we can generate a rich user agent header to help debug
915
+ # integrations.
916
+ class SystemProfiler
917
+ def self.uname
918
+ if ::File.exist?("/proc/version")
919
+ ::File.read("/proc/version").strip
920
+ else
921
+ case RbConfig::CONFIG["host_os"]
922
+ when /linux|darwin|bsd|sunos|solaris|cygwin/i
923
+ uname_from_system
924
+ when /mswin|mingw/i
925
+ uname_from_system_ver
926
+ else
927
+ "unknown platform"
928
+ end
929
+ end
930
+ end
931
+
932
+ def self.uname_from_system
933
+ (`uname -a 2>/dev/null` || "").strip
934
+ rescue Errno::ENOENT
935
+ "uname executable not found"
936
+ rescue Errno::ENOMEM # couldn't create subprocess
937
+ "uname lookup failed"
938
+ end
939
+
940
+ def self.uname_from_system_ver
941
+ (`ver` || "").strip
942
+ rescue Errno::ENOENT
943
+ "ver executable not found"
944
+ rescue Errno::ENOMEM # couldn't create subprocess
945
+ "uname lookup failed"
946
+ end
947
+
948
+ def initialize
949
+ @uname = self.class.uname
950
+ end
951
+
952
+ def user_agent
953
+ lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} " \
954
+ "(#{RUBY_RELEASE_DATE})"
955
+
956
+ {
957
+ application: Stripe.app_info,
958
+ bindings_version: Stripe::VERSION,
959
+ lang: "ruby",
960
+ lang_version: lang_version,
961
+ platform: RUBY_PLATFORM,
962
+ engine: defined?(RUBY_ENGINE) ? RUBY_ENGINE : "",
963
+ publisher: "stripe",
964
+ uname: @uname,
965
+ hostname: Socket.gethostname,
966
+ }.delete_if { |_k, v| v.nil? }
967
+ end
968
+ end
969
+
970
+ # StripeRequestMetrics tracks metadata to be reported to stripe for metrics
971
+ # collection
972
+ class StripeRequestMetrics
973
+ # The Stripe request ID of the response.
974
+ attr_accessor :request_id
975
+
976
+ # Request duration in milliseconds
977
+ attr_accessor :request_duration_ms
978
+
979
+ def initialize(request_id, request_duration_ms)
980
+ self.request_id = request_id
981
+ self.request_duration_ms = request_duration_ms
982
+ end
983
+
984
+ def payload
985
+ { request_id: request_id, request_duration_ms: request_duration_ms }
986
+ end
987
+ end
988
+ end
989
+ end