### Run Ruby Example Source: https://github.com/stripe/stripe-ruby/blob/master/examples/README.md To run an example script from the examples folder, set the RUBYLIB environment variable to '../lib' and then execute the desired Ruby file. ```bash RUBYLIB=../lib ruby your_example.rb ``` ```bash RUBYLIB=../lib ruby event_notification_webhook_handler.rb ``` -------------------------------- ### Install and Run Stripe Mock Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Install the stripe-mock tool using Go and run it in the background. This is required for running the test suite. ```sh go install github.com/stripe/stripe-mock@latest stripe-mock ``` -------------------------------- ### Add New Ruby Example Source: https://github.com/stripe/stripe-ruby/blob/master/examples/README.md To add a new example, clone the 'new_example.rb' template, implement your code, fill out the file comment with a description and key steps, and then run it using the standard command. ```bash # Clone new_example.rb # Implement your example # Fill out the file comment. Include a description and key steps that are being demonstrated. # Run it (as per above) # 👍 ``` -------------------------------- ### Install Public Preview SDK Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Use this command to install a specific beta version of the Stripe Ruby SDK. Replace `` with the desired beta version number. ```sh gem install stripe -v ``` -------------------------------- ### Install Stripe Ruby Gem Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Install the Stripe Ruby gem using the gem command. This is the standard way to add the library to your Ruby environment if not using Bundler. ```shell gem install stripe ``` -------------------------------- ### Customer Session CreateParams with Sorbet Annotation Source: https://github.com/stripe/stripe-ruby/wiki/Static-Type-Annotations-(with-Sorbet) Demonstrates explicit parameter classes with attributes for types and required/optional status, as shown in `CustomerSession::CreateParams`. This example includes a Sorbet annotation for the `components` attribute. ```ruby class CreateParams < Stripe::RequestParams class Components < Stripe::RequestParams ... end # Configuration for buy button. sig { returns(T.nilable(::Stripe::CustomerSession::CreateParams::Components)) } attr_accessor :components end ``` -------------------------------- ### V2 Amount Type Consolidation Example Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Shows how to access monetary amount data using the consolidated `Stripe::V2::Amount` type. Previously, nested classes were used per resource. This example retrieves an account and accesses its annual revenue amount. ```ruby # account = client.v2.core.accounts.retrieve("acct_123") # amount = account.identity.business_details.annual_revenue.amount # amount is now a Stripe::V2::Amount puts amount.value # Integer puts amount.currency # String, e.g. "usd" ``` -------------------------------- ### BigDecimal Arithmetic Example Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Demonstrates natural arithmetic operations with BigDecimal for monetary values, ensuring no precision loss. This is relevant due to `bigdecimal` becoming an explicit runtime dependency. ```ruby total = line_item.unit_amount_decimal * line_item.quantity_decimal ``` -------------------------------- ### Initialize StripeClient with API Key and Version Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Pass global configuration options like `stripe_version` as keyword arguments to the `StripeClient` constructor. Unspecified options fall back to `StripeConfiguration`. ```ruby Stripe.api_key = "sk_test_123" Stripe.api_version = "2022-11-15" ``` ```ruby client = Stripe::StripeClient.new( "sk_test_123", stripe_version: "2022-11-15", ) ``` -------------------------------- ### Create Customer Using Hash Parameters (v16) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v16 Demonstrates creating a customer using hash parameters, which remains unchanged in v16. Requires the 'stripe' gem. ```ruby require 'stripe' client = Stripe::StripeClient.new(API_KEY) client.v1.customers.create({ name: "Foo", email: "bar@example.com" }) ``` -------------------------------- ### Initialize Stripe Client and List Customers Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Initialize the Stripe client with your secret key and perform basic operations like listing customers. ```ruby require 'stripe' client = Stripe::StripeClient.new("sk_test_...") # list customers customers = client.v1.customers.list() # retrieve single customer customer = client.v1.customers.retrieve('cus_123456789') ``` -------------------------------- ### Initialize StripeClient with API Key Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Migrate from setting the global API key to initializing a `StripeClient` instance with the API key. ```ruby Stripe.api_key = "sk_test_123" ``` ```ruby client = Stripe::StripeClient.new("sk_test_123") ``` -------------------------------- ### Run a Single Test Suite Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Execute a specific test suite file using Ruby and the 'bundle exec' command. ```sh bundle exec ruby -Ilib/ test/stripe/util_test.rb ``` -------------------------------- ### Migrating from Params Hashes to Params Classes Source: https://github.com/stripe/stripe-ruby/wiki/Static-Type-Annotations-(with-Sorbet) Illustrates the migration from using hash-based parameters to dedicated parameter classes for API calls. Using parameter classes enables per-param type checking with Sorbet. ```ruby client = StripeClient.new("sk_test_123") # using params hashes client.v1.customers.create( {name: "John Doe", email: "john@example.com"} ) # using params class # This will have per-param type checking params = CustomerService::CreateParams.new(name: "John Doe", email: "john@example.com") client.v1.customers.create(**params) ``` -------------------------------- ### Enable Logging via Environment Variable Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Enable library logging by setting the STRIPE_LOG environment variable to 'debug' or 'info'. ```sh $ export STRIPE_LOG=info ``` -------------------------------- ### Update Customer Creation with Unified Parameter Types (v16) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v16 Shows how to update customer creation when using direct parameter types, reflecting the unification in v16. Requires the 'stripe' gem. ```ruby ## Before require 'stripe' client = Stripe::StripeClient.new(API_KEY) params = Stripe::CustomerService::CreateParams.new( name: "Foo", email: "bar@example.com" ) client.v1.customers.create(params) ## After require 'stripe' client = Stripe::StripeClient.new(API_KEY) params = Stripe::CustomerCreateParams.new( name: "Foo", email: "bar@example.com" ) client.v1.customers.create(params) ``` -------------------------------- ### Enable Logging via Stripe.log_level Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Configure the logging level programmatically using `Stripe.log_level` with constants like `Stripe::LEVEL_INFO`. ```ruby Stripe.log_level = Stripe::LEVEL_INFO ``` -------------------------------- ### Run All Tests Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Execute the entire test suite for the Stripe Ruby library using the 'just' command or the underlying 'bundle exec rake' command. ```sh just test # or: bundle exec rake test ``` -------------------------------- ### Convert Instance Resource Method Calls Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Migrate instance resource method calls (e.g., `Stripe::Customer.retrieve` followed by `customer.delete`) to direct calls on the `StripeClient` service. ```ruby customer = Stripe::Customer.retrieve("cus_123"); customer.delete(); ``` ```ruby client.v1.customers.delete("cus_123"); ``` -------------------------------- ### Access Resource Properties using Indexer and Accessor Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Demonstrates retrieving resource property values using both the indexer (square brackets) and accessors (dot notation). The indexer returns nil for undefined properties, while accessors raise a NoMethodError. ```ruby customer = client.v1.customers.retrieve('cus_123456789') puts customer['id'] puts customer.id ``` ```ruby customer = client.v1.customers.retrieve('cus_123456789') puts customer['unknown'] # nil puts customer.unknown # raises NoMethodError ``` -------------------------------- ### Run Linter Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Execute the linter for the Stripe Ruby library using the 'just' command or the underlying 'bundle exec rubocop' command. ```sh just lint # or: bundle exec rubocop ``` -------------------------------- ### Configure Per-Request API Key and Account Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Set a per-request API key and/or account for applications needing to use multiple keys, such as with Stripe Connect. ```ruby require "stripe" client = Stripe::StripeClient.new("sk_test_...") client.v1.customers.list( {}, { api_key: 'sk_test_...', stripe_account: 'acct_...', stripe_version: '2018-02-28', } ) ``` -------------------------------- ### Add Beta Version Header Source: https://github.com/stripe/stripe-ruby/blob/master/README.md If a preview feature requires a specific `Stripe-Version` header, use this function to set it. This is only available in public preview SDKs. ```python Stripe.add_beta_version("feature_beta", "v3") ``` -------------------------------- ### Decimal String Fields: Before (Reading and Writing) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Shows how `decimal_string` fields were handled before the v19 update, where `fx_rate` was a String and request parameters like `metric_tons` were also expected as Strings. ```ruby # Reading — was String session = Stripe::Checkout::Session.retrieve("cs_test_xxx") rate = session.currency_conversion.fx_rate puts rate.class # => String puts rate # => "9.99" # Writing — passed String Stripe::Climate::Order.create( product: "climsku_xxx", metric_tons: "5.5" ) ``` -------------------------------- ### Webhook Parsing: After (Loud Error with Guidance) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Demonstrates the updated behavior where `Stripe::Webhook.construct_event` now raises an `ArgumentError` when an incorrect event payload version is provided, offering guidance on the correct method to use. ```ruby # Now raises ArgumentError event = Stripe::Webhook.construct_event(v2_payload, sig_header, secret) ``` -------------------------------- ### Use StripeClient#raw_request Instead of APIResource.request Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Replace calls to `Stripe::APIResource.request` with `StripeClient#raw_request`. The new method uses the configuration set on the `StripeClient` instance instead of the global configuration. ```ruby # Instead of Stripe::APIResource.request(:get, "/v1/endpoint", params, opts) # do client = Stripe::StripeClient.new(...) resp = client.raw_request(:get, "/v1/endpoint", params: params, opts: opts) ``` -------------------------------- ### Create Customer with Request-Specific API Version Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v9 This request uses the '2022-08-01' API version, specified as an option during the customer creation call. This ensures the specified version is used in both v8 and v9. ```ruby require 'stripe' Stripe.api_key = "sk_test..." Stripe::Customer.create({ name: 'Jenny Rosen', email: 'jennyrosen@example.com', }, {stripe_version: '2022-08-01'}) ``` -------------------------------- ### Configure Stripe Proxy Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Set a proxy for all Stripe requests by assigning a URL to `Stripe.proxy`. ```ruby Stripe.proxy = 'https://user:pass@example.com:1234' ``` -------------------------------- ### Update Singleton Retrieve Method Call Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Update calls to singleton retrieve methods to pass `params` as the first argument, followed by `opts`. This change is necessary because `params` is now a required first argument. ```ruby params = { expand: ["available"] } opts = { stripe_account: "acct_123" } # ☠ No longer works Stripe::Balance.retrieve(opts) # ✅ Correct way to call retrieve method Stripe::Balance.retrieve(params, opts) ``` -------------------------------- ### Convert Class Resource Method Calls Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Replace calls to class resource methods (e.g., `Stripe::Customer.create`) with calls on the `StripeClient` instance, accessing services via `v1` or `v2`. ```ruby customer = Stripe::Customer.create({email: "jenny.rosen@example.com"}, {stripe_account: "acct_123"}) ``` ```ruby customer = client.v1.customers.create({email: "jenny.rosen@example.com"}, {stripe_account: "acct_123"}) ``` -------------------------------- ### Replace SubscriptionItem Usage Record Summaries Method Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v7 The `usage_record_summaries` method on the `SubscriptionItem` resource has been removed. Use `list_usage_record_summaries` instead. ```ruby # change from Stripe::SubscriptionItem.usage_record_summaries("si_12345") # to Stripe::SubscriptionItem.list_usage_record_summaries("si_12345") ``` -------------------------------- ### Migrate from `StripeClient#request` to `raw_request` and `deserialize` Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Replace the deprecated `StripeClient#request` method with `StripeClient.raw_request` for making custom requests and `StripeClient.deserialize` for processing the response. ```ruby client = StripeClient.new charge, resp = client.request { Charge.create } ``` ```ruby client = StripeClient.new("sk_test_123") resp = client.raw_request(:post, "/v1/charges") charge = client.deserialize(resp.data) ``` -------------------------------- ### Update Customer Cash Balance Method Signature Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v7 The `update_cash_balance` method on the `Customer` resource no longer requires the second argument to be `nil`. It now accepts `customer_id`, `params`, and `opts`. ```ruby # change from Stripe::Customer:: update_cash_balance("cus_12345", nil, { /* params */ }, { /* opts */ }) # to Stripe::Customer:: update_cash_balance("cus_12345", { /* params */ }, { /* opts */ }) ``` -------------------------------- ### Decimal String Fields: Migration Pattern (Formatting) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Offers a migration pattern for formatting `decimal_string` fields for display, using `to_s("F")` to ensure plain decimal string output. ```ruby # String formatting — use to_s("F") for display # Before: # puts "Rate: #{rate}" # "1.23" # After: puts "Rate: #{rate.to_s("F")}" # "1.23" ``` -------------------------------- ### Configure Timeouts Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Set open, read, and write timeouts for network requests in seconds. Note that write timeout is only supported on Ruby 2.6+. ```ruby Stripe.open_timeout = 30 # in seconds Stripe.read_timeout = 80 Stripe.write_timeout = 30 # only supported on Ruby 2.6+ ``` -------------------------------- ### Build Stripe Ruby Gem from Source Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Build the Stripe Ruby gem from its source code. This is typically done when you need to modify the gem's source or contribute to its development. ```shell gem build stripe.gemspec ``` -------------------------------- ### Run a Single Test Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Execute a specific test case within a test suite file using Ruby, specifying the test name with the '-n' flag. ```sh bundle exec ruby -Ilib/ test/stripe/util_test.rb -n /should.convert.names.to.symbols/ ``` -------------------------------- ### Decimal String Fields: Migration Pattern (Comparison) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Provides a migration pattern for comparing `decimal_string` fields, updating string comparisons to use `BigDecimal` for accurate comparisons. ```ruby # String comparison — update to use BigDecimal # Before: # if line_item.unit_amount_decimal == "0.50" # After: if line_item.unit_amount_decimal == BigDecimal("0.50") ``` -------------------------------- ### Configure CA Bundle Path Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Specify a custom path to a CA certificate bundle using `Stripe.ca_bundle_path`. ```ruby Stripe.ca_bundle_path = 'path/to/ca/bundle' ``` -------------------------------- ### Pass Parameters and Options to `raw_request` Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 When using `StripeClient.raw_request`, pass parameters and options as keyword arguments to the method. ```ruby resp = client.raw_request( :post, "/v1/charges", params: { amount: 4242, currency: "usd", source: tok_visa", }, opts: { stripe_account: "acct_123" }) ``` -------------------------------- ### Configure Bundler for Stripe Gem Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Configure your Gemfile to use the Stripe gem with Bundler. Ensure you are using the 'https' rubygems source for security. ```ruby source 'https://rubygems.org' gem 'rails' gem 'stripe' ``` -------------------------------- ### Webhook Parsing: Correct Method Usage Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Shows the correct methods to use for parsing different event versions: `Stripe::Webhook.construct_event` for V1 events and `client.parse_event_notification` for V2 event notifications. ```ruby # V1 events (object: "event") event = Stripe::Webhook.construct_event(payload, sig_header, secret) # V2 event notifications (object: "v2.core.event") event = client.parse_event_notification(payload, sig_header, secret) ``` -------------------------------- ### Create Customer with Default API Version (v8 vs v9) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v9 In stripe-ruby v8, this request would use your Stripe account's default API Version. In v9, it will use the pinned version (2023-08-16) unless explicitly overridden. ```ruby require 'stripe' Stripe.api_key = "sk_test..." Stripe::Customer.create({ name: 'Jenny Rosen', email: 'jennyrosen@example.com', }) ``` -------------------------------- ### Replace Subscription Delete with Cancel Method Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v7 The `delete` method on the `Subscription` resource is deprecated. Use the `cancel` method instead. ```ruby # change from Stripe::Subscription::delete("sub_12345") # to Stripe::Subscription.cancel("sub_12345") ``` -------------------------------- ### Update APIRequestor.execute_request Return Value Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 The `APIRequestor.new.execute_request` method now returns a tuple where the second element contains request options (e.g., `api_key`, `stripe_account`), replacing the previous behavior of returning only the API key. ```ruby # Before obj, api_key = StripeClient.new.execute_request(method, path, api_base: nil, api_key: nil, headers: {}, params: {}, usage: []) # is now, with base_address being one of [:api, :files, :connect, :meter_events] obj, opts = APIRequestor.new.execute_request(method, path, base_address, params: {}, opts: {}, usage: []) puts(opts) # will output {api_key: "sk_test_123", stripe_account: "acct_123"} ``` -------------------------------- ### Convert Nested Resource Operations Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 Adapt nested resource operations, such as listing balance transactions for a customer, to use the `StripeClient` service pattern. ```ruby Stripe::Customer.list_balance_transactions( "cus_123", {limit: 3}, {stripe_version: "2022-11-15"} ) ``` ```ruby customer = client.v1.customers.balance_transactions.list( "cus_123", {"limit": 3}, {"stripe_version": "2022-11-15"}, ); ``` -------------------------------- ### Make Custom Raw Request Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Use the `raw_request` method on `StripeClient` to send requests to undocumented or private beta APIs. This method is available from SDK version 13. The `opts` parameter can include `stripe_version` for specific feature requirements. ```ruby client = Stripe::StripeClient.new('sk_test_...') resp = client.raw_request(:post, "/v1/beta_endpoint", params: {param: 123}, opts: {stripe_version: "2022-11-15; feature_beta=v3"}) # (Optional) resp is a StripeResponse. You can use `Stripe.deserialize` to get a StripeObject. deserialized_resp = client.deserialize(resp.http_body) ``` -------------------------------- ### Set App Info for Stripe Ruby Plugin Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Identify your plugin or application when it makes calls to the Stripe API. This helps Stripe understand how their API is being used and by which integrations. ```ruby Stripe.set_app_info('MyAwesomePlugin', version: '1.2.34', url: 'https://myawesomeplugin.info') ``` -------------------------------- ### Configure API Version Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Override the default API version used by the library by setting `Stripe.api_version`. ```ruby Stripe.api_version = '2018-02-28' ``` -------------------------------- ### Update APIResource.execute_resource_request Signature Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 When using `APIResource.execute_resource_request`, include the `base_address` parameter, which defaults to `:api`. The `base_address` can be one of [:api, :files, :connect, :meter_events]. ```ruby APIResource.execute_resource_request(method, url, params = {}, opts = {}, usage = []) # is now, with base_address being one of [:api, :files, :connect, :meter_events] APIResource.execute_resource_request(method, url, base_address = :api, params = {}, opts = {}, usage = []) ``` -------------------------------- ### Configure Automatic Retries Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Enable automatic retries for transient network errors by setting the maximum number of retries with `Stripe.max_network_retries`. ```ruby Stripe.max_network_retries = 2 ``` -------------------------------- ### Customer Session Resource Attributes Source: https://github.com/stripe/stripe-ruby/wiki/Static-Type-Annotations-(with-Sorbet) Shows explicit field attributes for resources, like `client_secret` and `components` on the CustomerSession resource. These attributes are now precisely described by RBI annotations. ```ruby # =========checkout_session.rb========= # The client secret of this Customer Session. Used on the client to set up secure access to the given `customer`. # # The client secret can be used to provide access to `customer` from your frontend. It should not be stored, logged, or exposed to anyone other than the relevant customer. Make sure that you have TLS enabled on any page that includes the client secret. attr_reader :client_secret # Configuration for the components supported by this Customer Session. attr_reader :components ``` ```ruby # =========checkout_session.rbi========= # The client secret of this Customer Session. Used on the client to set up secure access to the given `customer`. # # The client secret can be used to provide access to `customer` from your frontend. It should not be stored, logged, or exposed to anyone other than the relevant customer. Make sure that you have TLS enabled on any page that includes the client secret. sig { returns(String) } attr_reader :client_secret # Configuration for the components supported by this Customer Session. sig { returns(Components) } attr_reader :components ``` -------------------------------- ### Create Customer with Explicit API Version (v8 and v9) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v9 This request explicitly sets the API version to '2020-08-27', ensuring it is used in both stripe-ruby v8 and v9. ```ruby require 'stripe' Stripe.api_key = "sk_test..." Stripe.api_version = '2020-08-27' Stripe::Customer.create({ name: 'Jenny Rosen', email: 'jennyrosen@example.com', }) ``` -------------------------------- ### Accessing Response Object Details Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Retrieve HTTP status code and headers from the response object using the `last_response` property. ```ruby customer = client.v1.customers.retrieve('cus_123456789') print(customer.last_response.http_status) # to retrieve status code print(customer.last_response.http_headers) # to retrieve headers ``` -------------------------------- ### Update Refund Resource with Stripe Ruby Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v8 Prefer the static `update` method over the deprecated `save` method for updating refund resources. The `update` method does not require retrieving the resource first. ```ruby # before refund = Stripe::Refund.retrieve("re_123") refund.description = "Refund description" refund.save # after Stripe::Refund.update("re_123", description: "Refund description") ``` -------------------------------- ### Update CA Certificates Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Update the bundled CA certificates from the Mozilla cURL release using the 'just' command or the underlying 'bundle exec rake' command. ```sh just update-certs # or: bundle exec rake update_certs ``` -------------------------------- ### Decimal String Fields: After (Reading and Writing) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Demonstrates the behavior after the v19 update, where `decimal_string` fields are now `BigDecimal`. Responses are automatically converted, and requests accept `BigDecimal`, `Integer`, `Float`, or `String`. ```ruby # Reading — now BigDecimal session = Stripe::Checkout::Session.retrieve("cs_test_xxx") rate = session.currency_conversion.fx_rate puts rate.class # => BigDecimal puts rate # => 0.123e1 (BigDecimal display) puts rate.to_s("F") # => "1.23" (plain decimal string) # Writing — BigDecimal is preferred, but String/Integer/Float still work Stripe::Climate::Order.create( product: "climsku_xxx", metric_tons: BigDecimal("5.5") ) # These also work (coerced automatically): metric_tons: "5.5" # String → still accepted metric_tons: 5.5 # Float → coerced (but may lose precision) metric_tons: 5 # Integer → coerced ``` -------------------------------- ### Cancel Subscription with Stripe Ruby Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v8 Use the `cancel` method instead of the deprecated `delete` method on the `Subscription` resource. ```ruby # before Stripe::Subscription::delete("sub_12345") # after Stripe::Subscription::cancel("sub_12345") ``` -------------------------------- ### Webhook Parsing: Before (Silently Broken) Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Illustrates the previous behavior where passing an incorrect event payload version to `Stripe::Webhook.construct_event` would not raise an error, leading to malformed objects. ```ruby # V2 payload accidentally passed to V1 method — returned garbage, no error event = Stripe::Webhook.construct_event(v2_payload, sig_header, secret) ``` -------------------------------- ### Subscribe to Request End Events in Ruby Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Subscribe to the `:request_end` event to process details about HTTP requests. This is useful for logging, metrics, or custom request handling. Ensure you handle potential key conflicts if multiple subscribers share the `user_data` hash. ```ruby Stripe::Instrumentation.subscribe(:request_end) do |request_event| # Filter out high-cardinality ids from `path` path_parts = request_event.path.split("/").drop(2) resource = path_parts.map { |part| part.match?(/<>[a-z_]+>/) ? part : ":id" }.join("/") tags = { method: request_event.method, resource: resource, code: request_event.http_status, retries: request_event.num_retries } StatsD.distribution('stripe_request', request_event.duration, tags: tags) end ``` -------------------------------- ### Stripe::Util.objects_to_ids Signature Change Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Illustrates the new `serialize_empty:` keyword argument for `Stripe::Util.objects_to_ids`. Set to `true` to preserve `nil` values in hashes, which is necessary for V2 JSON bodies. ```ruby Stripe::Util.objects_to_ids(params) ``` ```ruby # Preserve nils for V2 JSON bodies: Stripe::Util.objects_to_ids(params, serialize_empty: true) ``` -------------------------------- ### Set Default API Version in stripe-ruby Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v9 To avoid or postpone upgrading API Versions, explicitly set an API version when initializing stripe-ruby. If you were already explicitly setting an API version, no change is necessary. ```ruby require 'stripe' Stripe.api_key = "sk_test..." Stripe.api_version = '2020-08-27' ``` -------------------------------- ### Unset Refund Parameter with Stripe Ruby Update Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v8 When switching from `save` to `update` to unset a parameter by assigning `nil`, use an empty string `""` instead to preserve the previous behavior. ```ruby # before refund = Stripe::Refund.retrieve("re_123") refund.description = nil refund.save # after Stripe::Refund.update("re_123", description: "") ``` -------------------------------- ### Sorbet Type Signature Update for Amount Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v19 Provides the updated Sorbet type signature for monetary amounts after the V2 type consolidation. The signature changes from a resource-specific nested type to the shared `Stripe::V2::Amount`. ```ruby # Before # sig { params(amt: Stripe::V2::Core::Account::Identity::BusinessDetails::AnnualRevenue::Amount).void } # After sig { params(amt: Stripe::V2::Amount).void } ``` -------------------------------- ### Access `last_response` from Deserialized Objects Source: https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13 To retrieve the raw `StripeResponse` object after deserialization, access the `last_response` property on the deserialized object. ```ruby charge = client.v1.charges.create(...) charge.last_response ``` -------------------------------- ### Disable Telemetry in Stripe Ruby Source: https://github.com/stripe/stripe-ruby/blob/master/README.md Control whether the Stripe Ruby SDK sends telemetry data to Stripe. Disabling this prevents the SDK from reporting request latency and feature usage statistics. ```ruby Stripe.enable_telemetry = false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.