### Install and Run stripe-mock Source: https://github.com/stripe/stripe-python/blob/master/README.md Install stripe-mock using go and run it in the background. This is required for the test suite. ```sh go install github.com/stripe/stripe-mock@latest stripe-mock ``` -------------------------------- ### Execute a Stripe Python example Source: https://github.com/stripe/stripe-python/blob/master/examples/README.md Use the PYTHONPATH environment variable to run example scripts from the examples directory. ```bash PYTHONPATH=../ python your_example.py ``` ```bash PYTHONPATH=../ python thinevent_webhook_handler.py ``` -------------------------------- ### Install Stripe Python Library from Source Source: https://github.com/stripe/stripe-python/blob/master/README.md Install the Stripe Python library directly from its source code. ```sh python -m pip install . ``` -------------------------------- ### Install Public Preview Stripe SDK Source: https://github.com/stripe/stripe-python/blob/master/README.md To use public preview features, install a version of the stripe-python package with the `bX` suffix (e.g., `12.2.0b2`). Pin the package version to avoid unexpected breaking changes. ```bash pip install stripe== ``` -------------------------------- ### Enable Logging for Stripe SDK Source: https://github.com/stripe/stripe-python/blob/master/README.md Provides examples for enabling logging for the Stripe SDK, including setting environment variables or configuring Python's logging module. ```sh $ export STRIPE_LOG=debug ``` ```python import stripe stripe.log = 'debug' ``` ```python import logging logging.basicConfig() logging.getLogger('stripe').setLevel(logging.DEBUG) ``` -------------------------------- ### Install Stripe Python Library Source: https://github.com/stripe/stripe-python/blob/master/README.md Install the Stripe Python library using pip. It is recommended to upgrade to the latest version. ```sh pip install --upgrade stripe ``` -------------------------------- ### Handle Application Fee Refund in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Explains the change in the `ApplicationFee.refund()` method, which now returns an `ApplicationFee` instance instead of mutating the existing one. The example shows how to capture the returned instance if the old behavior is needed. ```python # before fee.refund() # after fee = fee.refund() ``` -------------------------------- ### Handle Subscription Discount Deletion in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Illustrates the change in `Subscription.delete_discount()`, which now returns the deleted discount object rather than modifying the subscription instance directly. The example shows how to reassign the subscription if the previous behavior is desired. ```python # before subscription.delete_discount() # after subscription = subscription.delete_discount() ``` -------------------------------- ### Python: Update StripeClient Calls to v1 Namespace Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Demonstrates how to update existing StripeClient calls to use the new v1 namespace. This change is necessary for Stripe Python SDK versions 12.5.0 and later to distinguish between v1 and v2 APIs. The example shows a before-and-after diff for retrieving a customer. ```diff client = StripeClient("sk_test...") - client.customers.retrieve("cus_123"); + client.v1.customers.retrieve("cus_123"); ``` -------------------------------- ### Manage Customer Discount Deletion in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Details the modification in `Customer.delete_discount()`, which now returns the deleted discount object instead of resetting the customer's discount property to `None`. The example demonstrates how to manually reset the property if required. ```python # before customer.delete_discount() # after customer.delete_discount() customer.discount = None ``` -------------------------------- ### Initialize StripeClient Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Demonstrates how to initialize the StripeClient instead of setting global configuration variables. This allows for multiple client instances with distinct configurations. ```python # Before stripe.api_key = "sk_test_123" # After client = stripe.StripeClient("sk_test_123") ``` ```python # Before 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" # After client = stripe.StripeClient( "sk_test_123", stripe_version="2022-11-15", max_network_retries=3, proxy="https://user:pass@example.com:1234", ) ``` -------------------------------- ### Set up Development Virtual Environment Source: https://github.com/stripe/stripe-python/blob/master/README.md Create a virtual environment for development using 'just venv' or manually with Python's venv module and pip. ```sh just venv # or: python -m venv venv && venv/bin/python -I -m pip install -e . ``` -------------------------------- ### Initialize StripeClient and List/Retrieve Customers Source: https://github.com/stripe/stripe-python/blob/master/README.md Demonstrates how to initialize the StripeClient with a secret key and perform basic customer operations like listing and retrieving. ```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) ``` -------------------------------- ### Configure StripeClient with a Proxy Source: https://github.com/stripe/stripe-python/blob/master/README.md Demonstrates how to set up a proxy for the StripeClient using the 'proxy' option. ```python client = StripeClient("sk_test_...", proxy="https://user:pass@example.com:1234") ``` -------------------------------- ### Python: Type Hinting for Stripe Method Parameters Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Illustrates how to correctly type hint parameters when creating a Stripe Customer, especially when passing parameters as a dictionary. It shows the difference between direct parameter passing and using dictionary unpacking with and without explicit type hints. ```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) ``` -------------------------------- ### Per-Request Configuration with StripeClient Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to configure individual requests with options like API key, Stripe account, and Stripe version. ```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", } ) ``` -------------------------------- ### Initialize and Use Custom HTTP Clients for Async Requests Source: https://github.com/stripe/stripe-python/blob/master/README.md Configure custom HTTP clients like `HTTPXClient` or `AIOHTTPClient` for asynchronous requests. By default, `HTTPXClient` raises an exception for sync methods unless `allow_sync_methods` is set to `True`. ```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 ``` -------------------------------- ### Compare and Set Decimal Values in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Demonstrates how to correctly compare invoice line amounts using the Decimal class and how to initialize request parameters using Decimal instead of strings to ensure precision. ```python from decimal import Decimal from stripe.params import PriceCreateParams # Comparison invoice.lines.data[0].pricing.unit_amount_decimal == Decimal("9.99") # Request parameter initialization params: PriceCreateParams = { "unit_amount_decimal": Decimal("9.99"), "currency": "usd", "recurring": {"interval": "month"}, "product": "prod_xxx", } ``` -------------------------------- ### Convert Nested Resource Operations Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Demonstrates how to handle nested resource operations by separating parameters and options into distinct dictionaries. ```python # Before stripe.Customer.list_balance_transactions( "cus_123", limit=3, stripe_version="2022-11-15", ) # After customer = client.customers.balance_transactions.list( "cus_123", params={"limit": 3}, options={"stripe_version": "2022-11-15"}, ); ``` -------------------------------- ### Run Linter Source: https://github.com/stripe/stripe-python/blob/master/README.md Check code quality and style using flake8 with 'just lint' or directly via Python's module execution. ```sh just lint # or: venv/bin/python -m flake8 --show-source stripe tests ``` -------------------------------- ### Run All Tests Source: https://github.com/stripe/stripe-python/blob/master/README.md Execute the entire test suite using 'just test' or directly with pytest within the virtual environment. ```sh just test # or: venv/bin/pytest ``` -------------------------------- ### Configure StripeClient with HTTP Clients Source: https://github.com/stripe/stripe-python/blob/master/README.md Illustrates how to configure the StripeClient to use specific HTTP clients like urlfetch, requests, pycurl, or urllib. ```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()) ``` -------------------------------- ### Basic Customer Creation Without Direct Parameter Type Reference Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v13 Illustrates a standard customer creation request using the Stripe Python SDK where parameter types are not directly referenced, showing no necessary changes for this usage pattern. ```python from stripe import StripeClient client = StripeClient(API_KEY) client.v1.customers.create({ name="Foo", email="bar@example.com" }) ``` -------------------------------- ### Update Customer Creation with Unified Parameters in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v13 Demonstrates how to update customer creation calls in the Stripe Python SDK when parameter types have been unified. This change moves parameter types to the `stripe.params` package for better consistency. ```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) ``` -------------------------------- ### Bash: Run SDK Migrator for Typed Python Codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Provides bash commands to use the Stripe SDK Migrator for typed Python codebases. The first command previews the files that will be migrated by adding the v1 namespace. The second command executes the migration, modifying the files in place. ```bash npx @stripe/sdk-migrator --language python --migration v1-namespace -d ``` ```bash npx @stripe/sdk-migrator --language python --migration v1-namespace -d --execute ``` -------------------------------- ### Format Code Source: https://github.com/stripe/stripe-python/blob/master/README.md Format the codebase using Ruff's formatter with 'just format' or directly via the Ruff command. ```sh just format # or: venv/bin/ruff format . --quiet ``` -------------------------------- ### Configure Global API Version in Stripe-Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 Demonstrates how to explicitly set the API version globally when initializing the stripe-python library to maintain compatibility with older API versions. ```python import stripe stripe.api_key = "sk_test_..." stripe.api_version = '2020-08-27' ``` -------------------------------- ### Access Response Code and Headers Source: https://github.com/stripe/stripe-python/blob/master/README.md Illustrates how to access the HTTP response code and headers from the 'last_response' property of a returned resource. ```python customer = client.v1.customers.retrieve( "cus_123456789" ) print(customer.last_response.code) print(customer.last_response.headers) ``` -------------------------------- ### Identify Your Plugin with Stripe SDK Source: https://github.com/stripe/stripe-python/blob/master/README.md Use `stripe.set_app_info()` to identify your plugin when it makes calls to the Stripe API. This helps Stripe improve its services. ```python stripe.set_app_info("MyAwesomePlugin", version="1.2.34", url="https://myawesomeplugin.info") ``` -------------------------------- ### Construct Webhook Event Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Shows the updated method signature for constructing webhook events using the StripeClient instance. ```python # Before event = stripe.Webhook.construct_event( payload, sig_header, secret ) # After event = client.construct_event( payload, sig_header, secret ) ``` -------------------------------- ### Update Customer Resource with Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v5 Demonstrates how to update a customer resource using the `modify` method, replacing the deprecated `save` method. It shows how to change a customer's email and how to unset a description by assigning an empty string. ```python import stripe # Before (deprecated) customer = stripe.Customer.retrieve("cus_123") customer.email = "example@test.com" customer.save() # After stripe.Customer.modify("cus_123", email="example@test.com") # Before (deprecated - unsetting description) customer = stripe.Customer.retrieve("cus_123") customer.description = None customer.save() # After (preserving behavior by assigning empty string) stripe.Customer.modify("cus_123", description = "") ``` -------------------------------- ### Bash: Run SDK Migrator for Untyped Python Codebases Source: https://github.com/stripe/stripe-python/wiki/v1-namespace-in-StripeClient Provides bash commands to use the Stripe SDK Migrator for untyped or minimally typed Python codebases. The --untyped flag is used to ensure compatibility. The first command previews the migration, and the second command executes it. ```bash npx @stripe/sdk-migrator --language python -d ~/stripe-integration --migration v1-namespace --untyped ``` ```bash npx @stripe/sdk-migrator --language python -d ~/stripe-integration --migration v1-namespace --untyped --execute ``` -------------------------------- ### Run Tests in a Single File Source: https://github.com/stripe/stripe-python/blob/master/README.md Focus testing on a specific file by providing its path to 'just test' or pytest. ```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 ``` -------------------------------- ### Convert Resource Method Calls Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Shows how to convert standard resource-based API calls to the service-based pattern, where request parameters and options are passed as separate dictionaries. ```python # Before customer = stripe.Customer.create(email="jenny.rosen@example.com", stripe_account="acct_123") # After customer = client.customers.create(params={"email": "jenny.rosen@example.com"}, options={"stripe_account": "acct_123"}) ``` -------------------------------- ### Run a Single Test Source: https://github.com/stripe/stripe-python/blob/master/README.md Execute an individual test case by specifying its full path and name to 'just test' or pytest. ```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 ``` -------------------------------- ### Add Beta Version for Preview Features Source: https://github.com/stripe/stripe-python/blob/master/README.md If a preview feature requires a specific `Stripe-Version` header, use the `stripe.add_beta_version` function. This function is only available in public preview SDKs. ```python stripe.add_beta_version("feature_beta", "v3") ``` -------------------------------- ### Run a Single Test Suite Source: https://github.com/stripe/stripe-python/blob/master/README.md Execute a specific test suite within a file by specifying the suite name to 'just test' or pytest. ```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 Subscription Item Usage Record Summaries in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Illustrates the transition from the deprecated `item.usage_record_summaries()` method to the recommended `SubscriptionItem.list_usage_record_summaries()` for fetching usage record summaries. This update ensures compatibility with current API standards. ```python # before item.usage_record_summaries() # after SubscriptionItem.list_usage_record_summaries(item.id) ``` -------------------------------- ### Iterate Through Customers Asynchronously Source: https://github.com/stripe/stripe-python/blob/master/README.md Asynchronously iterate through a list of customers using `list_async` and `auto_paging_iter`. ```python # .auto_paging_iter() implements both AsyncIterable and Iterable async for c in await stripe.Customer.list_async().auto_paging_iter(): ... ``` -------------------------------- ### Configure Automatic Retries with StripeClient Source: https://github.com/stripe/stripe-python/blob/master/README.md Shows how to enable and configure automatic retries for transient network errors by setting 'max_network_retries'. ```python client = StripeClient("sk_test_...", max_network_retries=2) ``` -------------------------------- ### Migrate V2 Amount Type Annotations 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, including how to update type annotations and access amount properties. ```python from stripe.v2 import Amount # Accessing the shared Amount type account = stripe.v2.core.AccountService.retrieve("acct_123") amount = account.identity.business_details.annual_revenue.amount print(amount.value) print(amount.currency) # Updating type annotations def process(amt: Amount): ... ``` -------------------------------- ### Perform Stripe API Request with Per-Request Versioning Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v6 Shows how to override the default pinned API version for a specific request by passing the stripe_version parameter. ```python import stripe stripe.api_key = "sk_test_..." stripe.Customer.create( name="Jenny Rosen", email="jennyrosen@example.com", stripe_version='2022-08-01', ) ``` -------------------------------- ### Update Request Options to Keyword Arguments Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Highlights the breaking change requiring request options to be passed as keyword arguments rather than positional arguments in resource methods. ```python # BEFORE stripe.Customer.create( "sk_test_123", "KG5LxwFBepaKHyUD", "2022-11-15", "acct_123", ) # AFTER stripe.Customer.create( api_key="sk_test_123", idempotency_key="KG5LxwFBepaKHyUD", stripe_version="2022-11-15", stripe_account="acct_123", ) ``` -------------------------------- ### Python: Handling Optional Email Field with Type Assertions Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Demonstrates how to safely access an optional email field from a Stripe Customer object using type assertions to satisfy type checkers. This prevents errors when a field might be None. ```python import stripe def print_email(s: str): print(s) cus = stripe.Customer.retrieve("xyz") assert cus.email is not None print_email(cus.email) ``` -------------------------------- ### Retrieve Customer Asynchronously Source: https://github.com/stripe/stripe-python/blob/master/README.md Asynchronous retrieval of a customer using `retrieve_async` with `StripeClient` or the global client. ```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") ``` -------------------------------- ### Migrate Charge Refund Method in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Shows the change from the deprecated `charge.refund()` method to the current standard of using `Refund.create(charge=charge.id)` for processing refunds. This reflects the recommended approach for refund operations. ```python # before charge.refund() # after Refund.create(charge=charge.id) ``` -------------------------------- ### Accessing Stripe Object Data (Python) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Demonstrates how to access data from Stripe objects after the change where StripeObject no longer inherits from dict. Attribute access, bracket notation, and membership testing remain the same. The `to_dict()` method is introduced for converting Stripe objects to plain dictionaries. ```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" # Migrating to dict conversion data = customer.to_dict() for key, value in customer.to_dict().items(): ... # Replacing .get() with getattr or to_dict().get() name = getattr(customer, "name", "default") ``` -------------------------------- ### Migrate Source Transactions Method in Stripe Python Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v4 Demonstrates the migration from the deprecated `source.source_transactions()` method to the preferred `Source.list_source_transactions()` for retrieving source transactions. This change aligns with updated API practices. ```python # before source.source_transactions() # after Source.list_source_transactions(item.id) ``` -------------------------------- ### Handling Decimal Fields in Stripe API (Python) Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Illustrates the change in handling decimal fields in the Stripe Python SDK v15. Fields previously represented as strings are now Python Decimal objects. This section shows how to read and set these fields, and highlights potential issues with string comparisons. ```python # Reading decimal fields 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 # Setting decimal params from decimal import Decimal stripe.Price.create( unit_amount_decimal=Decimal("9.99"), currency="usd", recurring={"interval": "month"}, product="prod_xxx", ) # String comparison issue # 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 ``` -------------------------------- ### V2 Amount Type Consolidation Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Explains the consolidation of Amount types in V2 resources, replacing per-resource nested Amount classes with a single shared `stripe.v2.Amount` type. ```APIDOC ## V2 Amount Type Consolidation ### Description This section details the consolidation of `Amount` types within Stripe V2 resources. Previously, each monetary amount property generated a separate, nested `Amount` class. These have been replaced by a single, shared `stripe.v2.Amount` type for consistency. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```python # Before: Referencing a nested Amount class # 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: Using the shared stripe.v2.Amount type from stripe.v2 import Amount # Assuming 'account' is retrieved as before account = stripe.v2.core.AccountService.retrieve("acct_123") amount = account.identity.business_details.annual_revenue.amount # amount is now typed as Amount print(amount.value) # Expected: int print(amount.currency) # Expected: str, e.g. "usd" # If updating type annotations: # 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): ... ``` ### Response N/A ### Key Changes - Replaced per-resource nested `Amount` classes (e.g., `Account.Identity.BusinessDetails.AnnualRevenue.Amount`) with a single shared `stripe.v2.Amount` type. - The `Amount` type has `value` (int) and `currency` (str) fields. - Update import paths if directly referencing nested `Amount` classes in type annotations. ``` -------------------------------- ### Asynchronous Operations Source: https://github.com/stripe/stripe-python/blob/master/README.md Provides asynchronous versions of request-making methods by suffixing the method name with `_async`. This allows for non-blocking I/O operations. ```APIDOC ## Asynchronous Operations ### Description Asynchronous versions of request-making methods are available by suffixing the method name with `_async`. This enables non-blocking operations, particularly useful in web applications or when dealing with multiple concurrent requests. ### Methods - `retrieve_async(id)`: Asynchronously retrieves a resource. - `list_async()`: Asynchronously lists resources. - `auto_paging_iter()`: Implements both AsyncIterable and Iterable for paginated results. ### Examples ```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(): ... ``` ### Note on `.save_async` There is no `.save_async` as `.save` is deprecated since stripe-python v5. Please migrate to `.modify_async`. ``` -------------------------------- ### Custom Requests with raw_request Source: https://github.com/stripe/stripe-python/blob/master/README.md Allows sending requests to undocumented APIs or bypassing method definitions by specifying request details directly. This feature is available from version 11 of the SDK. ```APIDOC ## POST /v1/beta_endpoint ### Description Allows sending requests to undocumented APIs or bypassing method definitions by specifying request details directly. ### Method POST ### Endpoint /v1/beta_endpoint ### Parameters #### Query Parameters - **stripe_version** (string) - Required - Example: "2022-11-15; feature_beta=v3" #### Request Body - **param** (any) - Required - Example: 123 ### Request Example ```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') ``` ### Response #### Success Response (200) - **response** (StripeResponse) - The response from the API. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### Update Resource Method Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v8-(StripeClient) Illustrates the rename of the modify method to update when using the StripeClient service pattern. ```python # Before customer = stripe.Customer.modify( "cus_123", description="new description", ) # After customer = client.customers.update( "cus_123", params={ "description": "new description", } ) ``` -------------------------------- ### Decimal Type Usage for Monetary Values Source: https://github.com/stripe/stripe-python/wiki/Migration-guide-for-v15 Demonstrates the correct usage of Decimal for monetary values in Stripe API requests and comparisons. ```APIDOC ## Usage of Decimal for Monetary Values ### Description This section illustrates how to use `Decimal` objects for monetary values in Stripe API interactions, replacing the previous string representation. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```python from decimal import Decimal # Example of comparing a unit amount with a Decimal value # invoice.lines.data[0].pricing.unit_amount_decimal == Decimal("9.99") # Expected: True # Example of creating Price parameters with Decimal from stripe.params import PriceCreateParams params: PriceCreateParams = { "unit_amount_decimal": Decimal("9.99"), # Use Decimal, not str "currency": "usd", "recurring": {"interval": "month"}, "product": "prod_xxx", } ``` ### Response N/A ### Affected Fields Fields that have changed from `str` to `Decimal` across various Stripe resources: **Billing** - `stripe.Plan`: `amount_decimal` - `stripe.Plan`: `tiers[].flat_amount_decimal` - `stripe.Plan`: `tiers[].unit_amount_decimal` - `stripe.Price`: `unit_amount_decimal` - `stripe.Price`: `tiers[].flat_amount_decimal` - `stripe.Price`: `tiers[].unit_amount_decimal` - `stripe.Price`: `currency_options[].unit_amount_decimal` - `stripe.Price`: `currency_options[].tiers[].flat_amount_decimal` - `stripe.Price`: `currency_options[].tiers[].unit_amount_decimal` - `stripe.InvoiceItem`: `quantity_decimal` - `stripe.InvoiceItem`: `pricing.unit_amount_decimal` - `stripe.InvoiceLineItem`: `quantity_decimal` - `stripe.InvoiceLineItem`: `pricing.unit_amount_decimal` - `stripe.CreditNoteLineItem`: `unit_amount_decimal` **Climate** - `stripe.climate.Order`: `metric_tons` - `stripe.climate.Product`: `metric_tons_available` **Checkout** - `stripe.checkout.Session`: `currency_conversion.fx_rate` **Issuing** - `stripe.issuing.Authorization`: `fleet.reported_breakdown.fuel.gross_amount_decimal` - `stripe.issuing.Authorization`: `fleet.reported_breakdown.non_fuel.gross_amount_decimal` - `stripe.issuing.Authorization`: `fleet.reported_breakdown.tax.local_amount_decimal` - `stripe.issuing.Authorization`: `fleet.reported_breakdown.tax.national_amount_decimal` - `stripe.issuing.Authorization`: `fuel.quantity_decimal` - `stripe.issuing.Authorization`: `fuel.unit_cost_decimal` - `stripe.issuing.Transaction`: `purchase_details.fleet.reported_breakdown.fuel.gross_amount_decimal` - `stripe.issuing.Transaction`: `purchase_details.fleet.reported_breakdown.non_fuel.gross_amount_decimal` - `stripe.issuing.Transaction`: `purchase_details.fleet.reported_breakdown.tax.local_amount_decimal` - `stripe.issuing.Transaction`: `purchase_details.fleet.reported_breakdown.tax.national_amount_decimal` - `stripe.issuing.Transaction`: `purchase_details.fuel.quantity_decimal` - `stripe.issuing.Transaction`: `purchase_details.fuel.unit_cost_decimal` **V2** - `stripe.v2.core.Account`: `identity.individuals[].relationship.percent_ownership` - `stripe.v2.core.AccountPerson`: `relationship.percent_ownership` *Note: Request-only decimal fields also change (e.g., `price_data.unit_amount_decimal` on Subscription, SubscriptionItem, SubscriptionSchedule, Quote, PaymentLink, Invoice line creation params).* ``` -------------------------------- ### Make Custom API Requests with StripeClient Source: https://github.com/stripe/stripe-python/blob/master/README.md Use `raw_request` to send requests to undocumented APIs or to bypass library method definitions. This feature is available from SDK version 11. ```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') ``` -------------------------------- ### Update CA Certificates Source: https://github.com/stripe/stripe-python/blob/master/README.md Update bundled CA certificates from the Mozilla cURL release using the 'just update-certs' command. ```sh just update-certs ``` -------------------------------- ### Python: Suppressing Type Errors for Optional Fields Source: https://github.com/stripe/stripe-python/wiki/Inline-type-annotations Shows how to suppress type checker errors when dealing with potentially None fields, like a customer's email, by adding a '# type: ignore' comment. This is useful when the developer is certain about the field's existence. ```python import stripe def print_email(s: str): print(s) cus = stripe.Customer.retrieve("xyz") print_email(cus.email) # type: ignore ``` -------------------------------- ### Disable Telemetry in Stripe SDK Source: https://github.com/stripe/stripe-python/blob/master/README.md By default, the Stripe Python library sends telemetry data to Stripe. You can disable this behavior by setting `stripe.enable_telemetry` to `False`. ```python stripe.enable_telemetry = False ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.