### Run an example script Source: https://github.com/stripe/stripe-python/blob/master/examples/README.md Execute a Python example script from the examples directory by setting the PYTHONPATH to include the parent directory. ```bash PYTHONPATH=../ python your_example.py ``` -------------------------------- ### Run the webhook handler example Source: https://github.com/stripe/stripe-python/blob/master/examples/README.md Execute the specific webhook handler example script using the required PYTHONPATH configuration. ```bash PYTHONPATH=../ python thinevent_webhook_handler.py ``` -------------------------------- ### Install and run stripe-mock Source: https://github.com/stripe/stripe-python/blob/master/README.md Fetch and run stripe-mock from a background terminal. Required for the test suite. ```sh go install github.com/stripe/stripe-mock@latest stripe-mock ``` -------------------------------- ### Install Stripe Python library from PyPI Source: https://github.com/stripe/stripe-python/blob/master/README.md Use this command to install the latest version of the Stripe Python library from PyPI. This is the recommended installation method. ```sh pip install --upgrade stripe ``` -------------------------------- ### Install Stripe Python library from source Source: https://github.com/stripe/stripe-python/blob/master/README.md Use this command to install the Stripe Python library directly from the source code. This is an alternative to installing from PyPI. ```sh python -m pip install . ``` -------------------------------- ### Install a public preview SDK with pip Source: https://github.com/stripe/stripe-python/blob/master/README.md Use this command to install a specific version of the Stripe Python SDK, particularly a public preview version with a 'bX' suffix. Replace the placeholder with the desired version from the releases page. Pinning the exact version is recommended to avoid breaking changes between preview releases. ```bash pip install stripe== ``` -------------------------------- ### Setting decimal parameters before v15 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Example showing how decimal parameters were passed as strings before the v15 update. ```python stripe.Price.create( unit_amount_decimal="9.99", currency="usd", recurring={"interval": "month"}, product="prod_xxx", ) ``` -------------------------------- ### Set up development virtualenv Source: https://github.com/stripe/stripe-python/blob/master/README.md Creates a virtualenv for development. The just command is recommended; the alternative uses python -m venv and pip install. ```sh just venv # or: python -m venv venv && venv/bin/python -I -m pip install -e . ``` -------------------------------- ### Setting decimal parameters in v15 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Example showing how decimal parameters are passed using the Decimal class in v15. ```python from decimal import Decimal stripe.Price.create( unit_amount_decimal=Decimal("9.99"), currency="usd", recurring={"interval": "month"}, product="prod_xxx", ) ``` -------------------------------- ### Example StripeObject for to_dict() demonstrations Source: https://github.com/stripe/stripe-python/blob/master/README.md An example Customer object with a nested Subscription, used to illustrate the to_dict() helper methods in the table below. ```python obj = Customer(id='cus_123', subscription=Subscription(id='sub_456', amount=Decimal('7.89')) ``` -------------------------------- ### Reading decimal fields before v15 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Example showing how decimal fields were accessed as strings prior to the v15 update. ```python invoice = stripe.Invoice.retrieve("in_xxx") amount = invoice.lines.data[0].pricing.unit_amount_decimal # "9.99" (str) parsed = float(amount) ``` -------------------------------- ### Reading decimal fields in v15 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Example showing how decimal fields are accessed as Decimal objects in v15, requiring conversion if string or float types are needed. ```python invoice = stripe.Invoice.retrieve("in_xxx") amount = invoice.lines.data[0].pricing.unit_amount_decimal # Decimal("9.99") str(amount) # "9.99" float(amount) # 9.99 ``` -------------------------------- ### Type annotations for decimal parameters Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Example of using Decimal for type annotations in request parameters. ```python from decimal import Decimal from stripe.params import PriceCreateParams params: PriceCreateParams = { "unit_amount_decimal": Decimal("9.99"), # Decimal, not str "currency": "usd", "recurring": {"interval": "month"}, "product": "prod_xxx", } ``` -------------------------------- ### Pass path parameters positionally for customer retrieve Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v16 Path parameters must now be passed positionally instead of by keyword. This example shows the change for client.v1.customers.retrieve. ```python customer = client.v1.customers.retrieve(customer="cus_123") ``` ```python customer = client.v1.customers.retrieve("cus_123") ``` -------------------------------- ### Replace save with modify for updating a customer Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v5 The `save` method is deprecated; use `modify` instead. This example shows the old pattern of retrieving a customer, setting an attribute, and calling `save`, and the new pattern of calling `modify` directly with the attribute as a keyword argument. ```python # Before customer = stripe.Customer.retrieve("cus_123") customer.email = "example@test.com" customer.save() # After stripe.Customer.modify("cus_123", email="example@test.com") ``` -------------------------------- ### Add a beta version header with stripe.add_beta_version Source: https://github.com/stripe/stripe-python/blob/master/README.md Use this function to set a required beta version header for preview features. This is only available in public preview SDKs. The example sets the 'feature_beta' header to 'v3'. ```python stripe.add_beta_version("feature_beta", "v3") ``` -------------------------------- ### Type error example: Optional email field Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Shows a function that expects a string but receives an Optional[str] from Customer.retrieve().email, causing a type error after v7.1.0. ```python def print_email(s: str): print(s) print_email(stripe.Customer.retrieve("xyz").email) ``` -------------------------------- ### Initialize StripeClient with configuration options Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Demonstrates passing global configuration options as keyword arguments to the StripeClient constructor. ```python stripe.api_key = "sk_test_123" stripe.api_version = "2022-11-15" stripe.max_network_retries = 3 stripe.proxy = "https://user:pass@example.com:1234" ``` ```python client = stripe.StripeClient( "sk_test_123", stripe_version="2022-11-15", max_network_retries=3, proxy="https://user:pass@example.com:1234", ) ``` -------------------------------- ### Initialize StripeClient Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Shows the transition from setting global stripe.api_key to initializing a StripeClient instance. ```python stripe.api_key = "sk_test_123" ``` ```python client = stripe.StripeClient("sk_test_123") ``` -------------------------------- ### Configure HTTP clients for async and sync requests Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to initialize HTTPXClient and AIOHTTPClient, and how to pass them to StripeClient or set as the global default. HTTPXClient raises an exception on sync methods unless allow_sync_methods=True. AIOHTTPClient does not support sync requests. ```python # By default, an explicitly initialized HTTPXClient will raise an exception if you # attempt to call a sync method. If you intend to only use async, this is useful to # make sure you don't unintentionally make a synchronous request. my_http_client = stripe.HTTPXClient() # If you want to use httpx to make sync requests, you can disable this # behavior. my_http_client = stripe.HTTPXClient(allow_sync_methods=True) # aiohttp is also available (does not support sync requests) my_http_client = stripe.AIOHTTPClient() # With StripeClient client = StripeClient("sk_test_...", http_client=my_http_client) # With the global client stripe.default_http_client = my_http_client ``` -------------------------------- ### Run the formatter Source: https://github.com/stripe/stripe-python/blob/master/README.md Formats code with Ruff. The library uses Ruff for formatting; code must be formatted with Black before PRs, but the just command uses Ruff. ```sh just format # or: venv/bin/ruff format . --quiet ``` -------------------------------- ### Per-request configuration with options argument Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to pass api_key, stripe_account, and stripe_version options for individual requests, useful for connected accounts or specific API versions. ```python from stripe import StripeClient client = StripeClient("sk_test_...") # list customers client.v1.customers.list( options={ "api_key": "sk_test_...", "stripe_account": "acct_...", "stripe_version": "2019-02-19", } ) # retrieve single customer client.v1.customers.retrieve( "cus_123456789", options={ "api_key": "sk_test_...", "stripe_account": "acct_...", "stripe_version": "2019-02-19", } ) ``` -------------------------------- ### Preview migration for typed Python codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Run this command to view the files that will be modified by the SDK migrator in a typed codebase. ```bash npx @stripe/sdk-migrator --language python --migration v1-namespace -d ``` -------------------------------- ### Configure HTTP client with StripeClient Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to instantiate StripeClient with different HTTP clients: urlfetch, requests, pycurl, or urllib. Without a configured client, the library attempts to load libraries in this order, preferring urlfetch and using urllib as a last resort; requests is usually recommended. ```python client = StripeClient("sk_test_...", http_client=stripe.UrlFetchClient()) client = StripeClient("sk_test_...", http_client=stripe.RequestsClient()) client = StripeClient("sk_test_...", http_client=stripe.PycurlClient()) client = StripeClient("sk_test_...", http_client=stripe.UrllibClient()) ``` -------------------------------- ### Run the linter Source: https://github.com/stripe/stripe-python/blob/master/README.md Runs flake8 with show-source on the stripe and tests directories. The just command is recommended; the alternative uses the virtualenv's Python. ```sh just lint # or: venv/bin/python -m flake8 --show-source stripe tests ``` -------------------------------- ### Create a customer without specifying API version (v5 vs v6 behavior) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 This request uses the account's default API version in v5 but uses the pinned version 2023-08-16 in v6. It creates a customer with name and email. ```python import stripe stripe.api_key = "sk_test_..." stripe.Customer.create( name="Jenny Rosen", email="jennyrosen@example.com", ) ``` -------------------------------- ### Convert resource method calls Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Shows how to pass request parameters and options as separate dictionaries in the service-based pattern. ```python customer = stripe.Customer.create(email="jenny.rosen@example.com", stripe_account="acct_123") ``` ```python customer = client.customers.create(params={"email": "jenny.rosen@example.com"}, options={"stripe_account": "acct_123"}) ``` -------------------------------- ### Replace charge.refund() with Refund.create(charge=charge.id) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 The deprecated `Charge.refund` method was removed. Use `Refund.create(charge=charge.id)` instead. ```python # before charge.refund() # after Refund.create(charge=charge.id) ``` -------------------------------- ### Configure StripeClient and list/retrieve customers Source: https://github.com/stripe/stripe-python/blob/master/README.md Sets the Stripe API key and demonstrates listing customers and retrieving a specific customer by ID. The client is instantiated with a secret key from the Stripe Dashboard. ```python from stripe import StripeClient client = StripeClient("sk_test_...") # list customers customers = client.v1.customers.list() # print the first customer's email print(customers.data[0].email) # retrieve specific Customer customer = client.v1.customers.retrieve("cus_123456789") # print that customer's email print(customer.email) ``` -------------------------------- ### Preview migration for untyped Python codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Use the --untyped flag to view migration changes for codebases without type information. ```bash npx @stripe/sdk-migrator --language python -d ~/stripe-integration --migration v1-namespace --untyped ``` -------------------------------- ### Run all tests Source: https://github.com/stripe/stripe-python/blob/master/README.md Runs the full test suite. The just command is recommended; the alternative uses pytest directly. ```sh just test # or: venv/bin/pytest ``` -------------------------------- ### Construct webhook events Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Shows the migration to using the StripeClient.construct_event() method for webhooks. ```python event = stripe.Webhook.construct_event( payload, sig_header, secret ) ``` ```python event = client.construct_event( payload, sig_header, secret ) ``` -------------------------------- ### Execute migration for untyped Python codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Apply the v1 namespace migration to an untyped codebase using the --execute flag. ```bash npx @stripe/sdk-migrator --language python -d ~/stripe-integration --migration v1-namespace --untyped --execute ``` -------------------------------- ### Convert nested resource operations Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Demonstrates converting nested resource calls to the service-based pattern with separate params and options dictionaries. ```python stripe.Customer.list_balance_transactions( "cus_123", limit=3, stripe_version="2022-11-15", ) ``` ```python customer = client.customers.balance_transactions.list( "cus_123", params={"limit": 3}, options={"stripe_version": "2022-11-15"}, ); ``` -------------------------------- ### Replace item.usage_record_summaries() with SubscriptionItem.list_usage_record_summaries(item.id) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 The deprecated `SubscriptionItem.usage_record_summaries` method was removed. Use `SubscriptionItem.list_usage_record_summaries(item.id)` instead. ```python # before item.usage_record_summaries() # after SubscriptionItem.list_usage_record_summaries(item.id) ``` -------------------------------- ### Execute migration for typed Python codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Use the --execute flag to apply the v1 namespace migration to your typed codebase. ```bash npx @stripe/sdk-migrator --language python --migration v1-namespace -d --execute ``` -------------------------------- ### Comparing decimal fields Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Demonstrates how string-based comparisons fail in v15 and provides the fix using Decimal objects. ```python # Before — worked invoice.lines.data[0].pricing.unit_amount_decimal == "9.99" # True # After — breaks (Decimal != str) invoice.lines.data[0].pricing.unit_amount_decimal == "9.99" # False # Fix — compare as Decimal from decimal import Decimal invoice.lines.data[0].pricing.unit_amount_decimal == Decimal("9.99") # True ``` -------------------------------- ### Typing parameters with Unpack[TypedDict] Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Demonstrates that passing parameters inline works without errors, but spreading a dict without a type hint causes a type error. Adding an explicit type annotation resolves it. ```python # no error cus = stripe.Customer.create(email="monty@python.org") # type error params = {"email": "monty@python.org"} cus = stripe.Customer.create(**params) # no error params: stripe.Customer.CreateParams = {"email": "monty@python.org"} cus = stripe.Customer.create(**params) ``` -------------------------------- ### Create a customer with per-request API version 2022-08-01 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 This request uses API version 2022-08-01 in both v5 and v6 by passing the stripe_version request option. ```python import stripe stripe.api_key = "sk_test_..." stripe.Customer.create( name="Jenny Rosen", email="jennyrosen@example.com", stripe_version='2022-08-01', ) ``` -------------------------------- ### Configure proxy with StripeClient Source: https://github.com/stripe/stripe-python/blob/master/README.md Sets a proxy for the StripeClient using the proxy option. The proxy URL includes user, password, host, and port. ```python client = StripeClient("sk_test_...", proxy="https://user:pass@example.com:1234") ``` -------------------------------- ### Replace source.source_transactions() with Source.list_source_transactions(item.id) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 The deprecated `Source.source_transactions` method was removed. Use `Source.list_source_transactions(item.id)` instead. ```python # before source.source_transactions() # after Source.list_source_transactions(item.id) ``` -------------------------------- ### ApplicationFee.refund now returns an instance of ApplicationFee Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 To be consistent with other resource methods, `ApplicationFee.refund` now returns an instance of `ApplicationFee` and does not mutate the instance. To revert to old behavior, assign the result back to the variable. ```python # before fee.refund() # after fee = fee.refund() ``` -------------------------------- ### Replace .get() with attribute access or bracket notation Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Shows how to replace the removed .get() method with to_dict().get() or getattr() to provide a default value. ```python # Before name = customer.get("name", "default") # After name = customer.to_dict().get("name", "default") # or name = getattr(customer, "name", "default") ``` -------------------------------- ### Pass path parameters positionally for retrieve_payment_method Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v16 Legacy resource methods like Customer.retrieve_payment_method also require positional path parameters. Update calls to pass path parameters before any request parameters or options. ```python # Before payment_method = customer.retrieve_payment_method( payment_method="pm_123" ) payment_method = stripe.Customer.retrieve_payment_method( customer="cus_123", payment_method="pm_123" ) # After payment_method = customer.retrieve_payment_method("pm_123") payment_method = stripe.Customer.retrieve_payment_method( "cus_123", "pm_123" ) ``` -------------------------------- ### Update request options to keyword arguments Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Request options like api_key, stripe_account, stripe_version, and idempotency_key must now be passed as keyword arguments instead of positionally. ```python stripe.Customer.create( "sk_test_123", # api key "KG5LxwFBepaKHyUD", # idempotency key "2022-11-15", # stripe version "acct_123", # stripe account ) ``` ```python stripe.Customer.create( api_key="sk_test_123", idempotency_key="KG5LxwFBepaKHyUD", stripe_version="2022-11-15", stripe_account="acct_123", ) ``` -------------------------------- ### StripeObject dict methods no longer work Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Lists the dict methods that are no longer available on StripeObject, such as .get(), .keys(), .values(), .items(), dict(customer), and iteration, and notes that .items() now returns the subscription's items if applicable. ```python # dict methods are gone customer.get("name") # AttributeError customer.keys() # AttributeError customer.values() # AttributeError customer.items() # now returns the subscription's items (if applicable), # not dict.items() dict(customer) # empty / no longer dumps data for key in customer: # no longer iterates over keys ... ``` -------------------------------- ### Run all tests in a single file Source: https://github.com/stripe/stripe-python/blob/master/README.md Runs all tests in a specific test file. The just command is recommended; the alternative uses pytest directly. ```sh just test tests/api_resources/abstract/test_updateable_api_resource.py # or: venv/bin/pytest tests/api_resources/abstract/test_updateable_api_resource.py ``` -------------------------------- ### Create a customer with global API version 2020-08-27 Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 This request uses API version 2020-08-27 in both v5 and v6 because the version is set globally via stripe.api_version. ```python import stripe stripe.api_key = "sk_test_..." stripe.api_version = "2020-08-27" stripe.Customer.create( name="Jenny Rosen", email="jennyrosen@example.com", ) ``` -------------------------------- ### Access response code and headers with last_response Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to retrieve the HTTP response code and headers from a resource using the last_response property. ```python customer = client.v1.customers.retrieve( "cus_123456789" ) print(customer.last_response.code) print(customer.last_response.headers) ``` -------------------------------- ### Enable logging via Python logging module Source: https://github.com/stripe/stripe-python/blob/master/README.md Enables logging through Python's logging module by setting the 'stripe' logger level to DEBUG. ```python import logging logging.basicConfig() logging.getLogger('stripe').setLevel(logging.DEBUG) ``` -------------------------------- ### Run a single test suite Source: https://github.com/stripe/stripe-python/blob/master/README.md Runs a specific test suite (class) within a test file. The just command is recommended; the alternative uses pytest directly. ```sh just test tests/api_resources/abstract/test_updateable_api_resource.py::TestUpdateableAPIResource # or: venv/bin/pytest tests/api_resources/abstract/test_updateable_api_resource.py::TestUpdateableAPIResource ``` -------------------------------- ### Migrate to to_dict() for plain dictionary conversion Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Shows the before and after of converting a StripeObject to a plain dictionary using to_dict(), which recursively converts nested objects to native Python types. ```python # Before data = dict(customer) for key, value in customer.items(): ... # After data = customer.to_dict() for key, value in customer.to_dict().items(): ... ``` -------------------------------- ### StripeObject attribute access and bracket notation still work Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Shows that attribute access, bracket notation, membership testing, string representation, and writing to StripeObject properties remain unchanged in v15. ```python # Attribute access — unchanged customer.name # Bracket notation — unchanged customer["name"] # Membership testing — unchanged "name" in customer # String representation — unchanged print(customer) # still prints formatted JSON # Writing — unchanged customer.name = "New Name" customer["name"] = "New Name" ``` -------------------------------- ### Set app info for plugins Source: https://github.com/stripe/stripe-python/blob/master/README.md Identifies a plugin using stripe.set_app_info(). This information is passed along when the library makes calls to the Stripe API. ```python stripe.set_app_info("MyAwesomePlugin", version="1.2.34", url="https://myawesomeplugin.info") ``` -------------------------------- ### Run a single test Source: https://github.com/stripe/stripe-python/blob/master/README.md Runs a single test method within a test suite. The just command is recommended; the alternative uses pytest directly. ```sh just test tests/api_resources/abstract/test_updateable_api_resource.py::TestUpdateableAPIResource::test_save # or: venv/bin/pytest tests/api_resources/abstract/test_updateable_api_resource.py::TestUpdateableAPIResource::test_save ``` -------------------------------- ### Update V2 Amount type annotations Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Demonstrates how to update type annotations when referencing the nested Amount class directly. ```python # Before from stripe.v2.core._account import Account def process(amt: Account.Identity.BusinessDetails.AnnualRevenue.Amount): ... # After from stripe.v2 import Amount def process(amt: Amount): ... ``` -------------------------------- ### Set API version when initializing stripe-python (diff) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 Shows the change needed to explicitly set an older API version (2020-08-27) when initializing stripe-python. The diff adds the line 'stripe.api_version = '2020-08-27''. ```diff import stripe stripe.api_key = "sk_test_..." + stripe.api_version = '2020-08-27' ``` -------------------------------- ### Set stripe.log to debug Source: https://github.com/stripe/stripe-python/blob/master/README.md Enables logging by setting the stripe.log attribute to 'debug'. ```python import stripe stripe.log = 'debug' ``` -------------------------------- ### Use async request methods with StripeClient and global client Source: https://github.com/stripe/stripe-python/blob/master/README.md Asynchronous versions of request methods are available by suffixing with _async. Works with both StripeClient and the global client. The auto_paging_iter() method supports both async and sync iteration. ```python # With StripeClient client = StripeClient("sk_test_...") customer = await client.v1.customers.retrieve_async("cus_xyz") # With global client stripe.api_key = "sk_test_..." customer = await stripe.Customer.retrieve_async("cus_xyz") # .auto_paging_iter() implements both AsyncIterable and Iterable async for c in await stripe.Customer.list_async().auto_paging_iter(): ... ``` -------------------------------- ### Update StripeClient calls to v1 namespace Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient When upgrading to version 12.5.0 or higher, prepend v1 to existing StripeClient service calls. ```diff client = StripeClient("sk_test...") - client.customers.retrieve("cus_123"); + client.v1.customers.retrieve("cus_123"); ``` -------------------------------- ### Subscription.delete_discount now returns an instance of deleted discount Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 The `Subscription.delete_discount` method now returns an instance of the deleted discount and does not mutate the `Subscription` instance. To revert to old behavior, assign the result back to the variable. ```python # before subscription.delete_discount() # after subscription = subscription.delete_discount() ``` -------------------------------- ### Customer.delete_discount no longer resets discount property Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 The `Customer.delete_discount` method no longer resets the `discount` property to `None` and returns the deleted discount instead. If you relied on the old behavior, reset the discount property manually. ```python # before customer.delete_discount() # after customer.delete_discount() customer.discount = None ``` -------------------------------- ### Update V2 Amount type usage Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Shows the transition from resource-specific nested Amount classes to the shared stripe.v2.Amount class. ```python # Before account = stripe.v2.core.AccountService.retrieve("acct_123") amount = account.identity.business_details.annual_revenue.amount # amount was typed as Account.Identity.BusinessDetails.AnnualRevenue.Amount # After from stripe.v2 import Amount amount = account.identity.business_details.annual_revenue.amount # amount is now typed as Amount print(amount.value) # int print(amount.currency) # str, e.g. "usd" ``` -------------------------------- ### Replace StripeObject.request() with client.raw_request() Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v16 The deprecated StripeObject.request() method has been removed. To make custom API requests, create a StripeClient and use raw_request() instead. ```python # Before response = stripe_object.request("get", "/v1/example") # After client = stripe.StripeClient("sk_test_...") response = client.raw_request("get", "/v1/example") ``` -------------------------------- ### Unset a parameter with modify using empty string Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v5 When using `save` to unset a parameter by assigning `None`, switch to `modify` and assign the parameter to an empty string `""` to preserve the previous behavior. ```python # before customer = stripe.Customer.retrieve("cus_123") customer.description = None customer.save() # after stripe.Customer.modify("cus_123", description = "") ``` -------------------------------- ### Enable automatic retries with max_network_retries Source: https://github.com/stripe/stripe-python/blob/master/README.md Enables automatic retries on transient failures by setting max_network_retries. Retries can be triggered by connection errors, timeouts, and certain API responses like HTTP 409 Conflict. Idempotency keys are automatically generated when not provided. ```python client = StripeClient("sk_test_...", max_network_retries=2) ``` -------------------------------- ### Narrowing Optional type with assertion Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Uses an assert to narrow the Optional[str] type of Customer.email to str, resolving the type error. ```python cus = stripe.Customer.retrieve("xyz") assert cus.email is not None print_email(cus.email) ``` -------------------------------- ### Send a custom request with StripeClient.raw_request Source: https://github.com/stripe/stripe-python/blob/master/README.md Use raw_request to call an undocumented API endpoint. Requires SDK version 11 or later. The response is a StripeResponse; optionally deserialize it with client.deserialize. ```python client = StripeClient("sk_test_...") response = client.raw_request( "post", "/v1/beta_endpoint", param=123, stripe_version="2022-11-15; feature_beta=v3" ) # (Optional) response is a StripeResponse. You can use `client.deserialize` to get a StripeObject. deserialized_resp = client.deserialize(response, api_mode='V1') ``` -------------------------------- ### Set STRIPE_LOG environment variable Source: https://github.com/stripe/stripe-python/blob/master/README.md Sets the STRIPE_LOG environment variable to enable logging. The value can be 'debug' or 'info'; 'info' is usually most appropriate for production. ```sh $ export STRIPE_LOG=debug ``` -------------------------------- ### Rename stripe.Reversal to stripe.TransferReversal Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v16 Replace all references to stripe.Reversal with stripe.TransferReversal in imports, isinstance checks, and type annotations. The methods for creating, retrieving, modifying, and listing transfer reversals have not changed. ```python # Before reversal = stripe.Transfer.retrieve_reversal("tr_123", "trr_123") isinstance(reversal, stripe.Reversal) # After reversal = stripe.Transfer.retrieve_reversal("tr_123", "trr_123") isinstance(reversal, stripe.TransferReversal) ``` -------------------------------- ### Update API naming convention Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Illustrates that Update APIs use the update() method instead of modify(). ```python customer = stripe.Customer.modify( "cus_123", description="new description", ) ``` ```python customer = client.customers.update( "cus_123", params={ "description": "new description", } ) ``` -------------------------------- ### Requesting without direct parameter type references Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v13 No changes are required if you do not reference parameter types directly when making requests. ```python from stripe import StripeClient client = StripeClient(API_KEY) client.v1.customers.create({ name="Foo", email="bar@example.com" }) ``` -------------------------------- ### Updating parameter type imports Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v13 If you reference parameter types directly, you must update your imports to use the new stripe.params package structure. ```python ## Before from stripe import StripeClient from stripe import CustomerService client = StripeClient(API_KEY) params: CustomerService.CreateParams = { "name": "Foo", "email": "bar@example.com" } client.v1.customers.create(params) ## After from stripe import StripeClient from stripe.params import CustomerCreateParams client = StripeClient(API_KEY) params: CustomerCreateParams = { "name": "Foo", "email": "bar@example.com" } client.v1.customers.create(params) ``` -------------------------------- ### Update bundled CA certificates Source: https://github.com/stripe/stripe-python/blob/master/README.md Updates the bundled CA certificates from the Mozilla cURL release. ```sh just update-certs ``` -------------------------------- ### Access StripeObject properties in multiple ways Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows attribute, subscript, membership, and getattr access to StripeObject properties. Useful for tolerating absent fields. ```python customer = client.v1.customers.retrieve("cus_123456789") customer.email # attribute access customer["email"] # subscript access "email" in customer # membership getattr(customer, "discount", None) # tolerate a field that may be absent ``` -------------------------------- ### Suppressing type error with type: ignore Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Suppresses the type error by adding a '# type: ignore' comment to the line that passes the Optional value. ```python cus = stripe.Customer.retrieve("xyz") print_email(cus.email) # type: ignore ``` -------------------------------- ### Disable telemetry Source: https://github.com/stripe/stripe-python/blob/master/README.md Disables telemetry sent to Stripe regarding request latency and feature usage. ```python stripe.enable_telemetry = False ```